springboot2整合disconf
阿新 • • 發佈:2018-11-03
1.新增Maven依賴
<dependency>
<groupId>com.baidu.disconf</groupId>
<artifactId>disconf-client</artifactId>
<version>2.6.36</version>
</dependency>
2.resources/disconf.properties配置
# 是否讀取遠端配置 enable.remote.conf=true # disconf HOST地址 conf_server_host=182.92.234.232:9080 # App name app=springboot-demo # version version=V1_0_0 # env env=local # 重試次數 conf_server_url_retry_times=3 # 重試睡眠時間 conf_server_url_retry_sleep_seconds=1 # 下載檔案的目錄 user_define_download_dir=./disconf/download
3.DisconfConfig
@Configuration public class DisconfConfig { @Bean(destroyMethod = "destroy") public DisconfMgrBean disconfMgrBean(){ DisconfMgrBean disconfMgrBean = new DisconfMgrBean(); disconfMgrBean.setScanPackage("no_used"); return disconfMgrBean; } @Bean(initMethod = "init", destroyMethod = "destroy") public DisconfMgrBeanSecond disconfMgrBeanSecond(){ return new DisconfMgrBeanSecond(); } @Bean(name = "reloadablePropertiesFactoryBean") @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) public ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean() { ReloadablePropertiesFactoryBean propertiesFactoryBean = new ReloadablePropertiesFactoryBean(); propertiesFactoryBean.setSingleton(true); // disconf 配置檔案 (這裡只有application.properties) List<String> fileNames = new ArrayList<>(); fileNames.add("classpath:application.properties"); propertiesFactoryBean.setLocations(fileNames); return propertiesFactoryBean; } @Bean(name = "propertyPlaceholderConfigurer") public PropertyPlaceholderConfigurer propertyPlaceholderConfigurer(ReloadablePropertiesFactoryBean reloadablePropertiesFactoryBean){ PropertyPlaceholderConfigurer placeholderConfigurer = new PropertyPlaceholderConfigurer(); placeholderConfigurer.setIgnoreResourceNotFound(false); placeholderConfigurer.setIgnoreUnresolvablePlaceholders(false); try { Properties properties = reloadablePropertiesFactoryBean.getObject(); placeholderConfigurer.setProperties(properties); } catch (IOException e) { throw new RuntimeException("unable to find properties", e); } return placeholderConfigurer; } }
4.讀取已下載的遠端檔案配置(application.properties)
@Configuration public class TestConfig { public static String username; public static String password; @Value("${test.username}") public void setUsername(String username) { TestConfig.username = username; } @Value("${test.password}") public void setPassword(String password) { TestConfig.password = password; } } disconf springboot-demo local application.properties具體配置 test.username=user123 test.password=pwd123456
5.測試遠端配置檔案讀取是否成功
@RestController
public class TestController {
@RequestMapping(name="test")
public String test() {
return TestConfig.username;
}
}
http://localhost:8080/test
原始碼 https://gitee.com/jsjack_wang/springboot-demo dev-disconf分支