archaius(netflix出品)
特點:
作用:
一、啟動consul並創建KV
啟動consul與創建KV查看:第二十章 springboot + consul(1)
注意:kv的創建可以使用手動的方式去創建。
結果如下:
說明:
二、編寫程序
1、引入jar
1 <!-- archaius --> 2 <dependency> 3 <groupId>com.netflix.archaius</groupId> 4 <artifactId>archaius-core</artifactId> 5 <version>0.6.6</version> 6 </dependency> 7 <!-- 動態配置,archaius底層 --> 8 <dependency> 9 <groupId>commons-configuration</groupId> 10 <artifactId>commons-configuration</artifactId> 11 <version>1.8</version> 12 </dependency>
注意:引入的commons-configuration就是archaius的底層實現。
2、構建archaius讀取配置的源頭
1 package com.microservice.archaius; 2 3 import java.io.StringReader; 4 import java.util.HashMap; 5 import java.util.Map; 6 import java.util.Properties; 7 8 import org.apache.commons.lang3.StringUtils; 9 10 import com.google.common.base.Optional; 11 import com.netflix.config.PollResult; 12 import com.netflix.config.PolledConfigurationSource; 13 import com.orbitz.consul.Consul; 14 import com.orbitz.consul.KeyValueClient; 15 16 /** 17 * 指定archaius讀取配置的源頭 18 */ 19 public class ConsulConfigurationSource implements PolledConfigurationSource { 20 21 private String keyName; 22 23 public ConsulConfigurationSource(String keyName) { 24 this.keyName = keyName; 25 } 26 27 /** 28 * 默認情況下,每隔60s,該方法會執行一次 29 */ 30 @Override 31 public PollResult poll(boolean initial, Object checkPoint) throws Exception { 32 Consul consul = Consul.builder().build(); 33 KeyValueClient kvClient = consul.keyValueClient(); 34 Optional<String> kvOpt = kvClient.getValueAsString(keyName); 35 String kvStr = StringUtils.EMPTY; 36 if (kvOpt.isPresent()) { 37 kvStr = kvOpt.get(); 38 } 39 40 Properties props = new Properties(); 41 props.load(new StringReader(kvStr));//String->Properties 42 43 Map<String, Object> propMap = new HashMap<>(); 44 for (Object key : props.keySet()) { 45 propMap.put((String) key, props.get(key)); 46 } 47 return PollResult.createFull(propMap); 48 } 49 50 }
注意:
3、配置管理器並動態讀取
1 @ApiOperation("get KV from consul by archaius") 2 @RequestMapping(value="/kv2/",method=RequestMethod.GET) 3 public void getKVByArchaius(@RequestParam("key") String key) throws IOException { 4 5 PolledConfigurationSource source = new ConsulConfigurationSource(key);//定義讀取配置的源頭 6 AbstractPollingScheduler scheduler = new FixedDelayPollingScheduler();//設置讀取配置文件的 7 DynamicConfiguration configuration = new DynamicConfiguration(source, scheduler); 8 9 ConfigurationManager.install(configuration); 10 11 DynamicStringProperty dsp = DynamicPropertyFactory.getInstance().getStringProperty("mysql.driverClassName", "zhaojigangDriver"); 12 System.out.println("當前時間:" + LocalDateTime.now() + "-->值:" + dsp.get()); 13 try { 14 Thread.sleep(60000);//睡60s 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 System.out.println("當前時間:" + LocalDateTime.now() + "-->值:" + dsp.get()); 19 }
步驟:
微服務中的配置統一管理與動態管理完成!!!