spring cloud 自定义配置源及配置刷新
生活随笔
收集整理的這篇文章主要介紹了
spring cloud 自定义配置源及配置刷新
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
通過自定義配置源可以接入自己的配置服務,配合ContextRefresher可以讓應用運行中自動更新配置。
實現PropertySourceLocator
/*** 自定義配置源*/ public class MyPropertySourceLocator implements PropertySourceLocator {@Overridepublic PropertySource<?> locate(Environment environment) {String msg = new SimpleDateFormat("HH:mm:ss").format(new Date());Map<String, Object> map = new HashMap<>();map.put("demo.diy.msg", msg);System.err.println("MyPropertySourceLocator, demo.diy.msg = " + msg);//spring自帶的一個簡單的map結構配置集合,也可以繼承PropertySource自定義MapPropertySource source = new MapPropertySource("my-source", map);return source;} }配置類
@Configuration public class MyConfigBootstrapConfiguration {@Beanpublic MyPropertySourceLocator myPropertySourceLocator() {return new MyPropertySourceLocator();}}用Java代碼聲明bean,還需要在resources/META-INF/spring.factories中聲明
org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.netease.ag.demoweb.MyConfigBootstrapConfigurationSpring中類似與Java SPI的加載機制。它在META-INF/spring.factories文件中配置接口的實現類名稱,然后在程序中讀取這些配置文件并實例化。這種自定義的SPI機制是Spring Boot Starter實現的基礎。
使用自定義配置
@RefreshScope //可更新 @Component @Data public class ValueConfig {@Value("${demo.copy.msg}")private String copyMsg;@Value("${demo.diy.msg}")private String diyMsg;public ValueConfig() {System.err.println("ValueConfig init");} }application.properties中可以引用自定義配置
demo.copy.msg=${demo.diy.msg}springboot應用啟動
@SpringBootApplication @RestController public class DemowebApplication {@Resourceprivate ValueConfig valueConfig;@Resourceprivate ContextRefresher contextRefresher;public DemowebApplication() {System.err.println("DemowebApplication init");}public static void main(String[] args) {SpringApplication.run(DemowebApplication.class, args);}@RequestMapping("/t")public String t() {return valueConfig.toString();}//更新bean屬性@RequestMapping("/r")public Object r() {return contextRefresher.refresh();}啟動日志
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v1.5.2.RELEASE)MyPropertySourceLocator, demo.diy.msg = 17:18:22 ... DemowebApplication init ... ValueConfig init ...Tomcat started on port(s): 8080 (http)查詢,多次請求返回一致
請求:http://localhost:8080/t 響應:ValueConfig(copyMsg=17:18:22, diyMsg=17:18:22)
更新
請求:http://localhost:8080/r 響應:["demo.diy.msg"]
日志輸出:
MyPropertySourceLocator, demo.diy.msg = 17:27:44再次調用查詢接口,發現值改變,并且輸出日志
ValueConfig init證明更新字段實際是重新生成了一個bean
轉載于:https://my.oschina.net/liujiest/blog/2254176
總結
以上是生活随笔為你收集整理的spring cloud 自定义配置源及配置刷新的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【3y】从零单排学Redis【青铜】
- 下一篇: Elasticsearch索引定时清理