apollo与springboot集成实现动态刷新配置的教程详解
分布式apollo简介
apollo(阿波罗)是携程框架部门研发的开源配置管理中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。
本文主要介绍如何使用apollo与springboot实现动态刷新配置,如果之前不了解apollo可以查看如下文档
学习了解一下apollo,再来查看本文
正文
apollo与spring实现动态刷新配置本文主要演示2种刷新,一种基于普通字段刷新、一种基于bean上使用了@configurationproperties刷新
1、普通字段刷新
a、pom.xml配置
<dependency> <groupid>com.ctrip.framework.apollo</groupid> <artifactid>apollo-client</artifactid> <version>1.6.0</version> </dependency>
b、客户端配置appid,apollo meta server
此配置有多种方法,本示例直接在application.yml配置,配置内容如下
app:
id: ${spring.application.name}
apollo:
meta:
bootstrap:
enabled: true
eagerload:
enabled: true
c、项目中启动类上加上@enableapolloconfig注解,形如下
@springbootapplication @enableapolloconfig(value = {"application","user.properties","product.properties","order.properties"}) public class apolloapplication { public static void main(string[] args) { springapplication.run(apolloapplication.class, args); } }
@enableapolloconfig不一定要加在启动类上,加在被spring管理的类上即可
d、在需刷新的字段上配置@value注解,形如
@value("${hello}") private string hello;
通过以上三步就可以实现普通字段的动态刷新
2.bean使用@configurationproperties动态刷新
bean使用@configurationproperties注解目前还不支持自动刷新,得编写一定的代码实现刷新。目前官方提供2种刷新方案
- 基于refreshscope实现刷新
- 基于environmentchangeevent实现刷新
- 本文再提供一种,当bean上如果使用了@conditionalonproperty如何实现刷新
a、基于refreshscope实现刷新
1、pom.xml要额外引入
<dependency> <groupid>org.springframework.cloud</groupid> <artifactid>spring-cloud-context</artifactid> <version>2.0.3.release</version> </dependency>
2、bean上使用@refreshscope注解
@component @configurationproperties(prefix = "product") @data @allargsconstructor @noargsconstructor @builder @refreshscope public class product { private long id; private string productname; private bigdecimal price; }
3、利用refreshscope搭配@apolloconfigchangelistener监听实现bean的动态刷新,其代码实现如下
@apolloconfigchangelistener(value="product.properties",interestedkeyprefixes = {"product."}) private void refresh(configchangeevent changeevent){ refreshscope.refresh("product"); printchangekeyutils.printchange(changeevent); }
b、基于environmentchangeevent实现刷新
利用spring的事件驱动配合@apolloconfigchangelistener监听实现bean的动态刷新,其代码如下
@component @slf4j public class userpropertiesrefresh implements applicationcontextaware { private applicationcontext applicationcontext; @apolloconfigchangelistener(value="user.properties",interestedkeyprefixes = {"user."}) private void refresh(configchangeevent changeevent){ applicationcontext.publishevent(new environmentchangeevent(changeevent.changedkeys())); printchangekeyutils.printchange(changeevent); } @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { this.applicationcontext = applicationcontext; } }
c、当bean上有@conditionalonproperty如何实现刷新
当bean上有@conditionalonproperty注解时,上述的两种方案可以说失效了,因为@conditionalonproperty是一个条件注解,当不满足条件注解时,bean是没法注册到spring容器中的。如果我们要实现此种情况的下的动态刷新,我们就得自己手动注册或者销毁bean了。其实现流程如下
1、当满足条件注解时,则手动创建bean,然后配合@apolloconfigchangelistener监听该bean的属性变化。当该bean属性有变化时,手动把属性注入bean。同时刷新依赖该bean的其他bean
2、当不满足条件注解时,则手动从spring容器中移除bean,同时刷新依赖该bean的其他bean
其刷新核心代码如下
public class orderpropertiesrefresh implements applicationcontextaware { private applicationcontext applicationcontext; @apolloconfig(value = "order.properties") private config config; @apolloconfigchangelistener(value="order.properties",interestedkeyprefixes = {"order."},interestedkeys = {"model.isshoworder"}) private void refresh(configchangeevent changeevent){ for (string basepackage : listbasepackages()) { set<class> conditionalclasses = classscannerutils.scan(basepackage, conditionalonproperty.class); if(!collectionutils.isempty(conditionalclasses)){ for (class conditionalclass : conditionalclasses) { conditionalonproperty conditionalonproperty = (conditionalonproperty) conditionalclass.getannotation(conditionalonproperty.class); string[] conditionalonpropertykeys = conditionalonproperty.name(); string beanchangecondition = this.getchangekey(changeevent,conditionalonpropertykeys); string conditionalonpropertyvalue = conditionalonproperty.havingvalue(); boolean ischangebean = this.changebean(conditionalclass, beanchangecondition, conditionalonpropertyvalue); if(!ischangebean){ // 更新相应的bean的属性值,主要是存在@configurationproperties注解的bean applicationcontext.publishevent(new environmentchangeevent(changeevent.changedkeys())); } } } } printchangekeyutils.printchange(changeevent); printallbeans(); } /** * 根据条件对bean进行注册或者移除 * @param conditionalclass * @param beanchangecondition bean发生改变的条件 * @param conditionalonpropertyvalue */ private boolean changebean(class conditionalclass, string beanchangecondition, string conditionalonpropertyvalue) { boolean isneedregisterbeanifkeychange = this.isneedregisterbeanifkeychange(beanchangecondition,conditionalonpropertyvalue); boolean isneedremovebeanifkeychange = this.isneedremovebeanifkeychange(beanchangecondition,conditionalonpropertyvalue); string beanname = stringutils.uncapitalize(conditionalclass.getsimplename()); if(isneedregisterbeanifkeychange){ boolean isalreadyregisterbean = this.isexistbean(beanname); if(!isalreadyregisterbean){ this.registerbean(beanname,conditionalclass); return true; } }else if(isneedremovebeanifkeychange){ this.unregisterbean(beanname); return true; } return false; } /** * bean注册 * @param beanname * @param beanclass */ public void registerbean(string beanname,class beanclass) { log.info("registerbean->beanname:{},beanclass:{}",beanname,beanclass); beandefinitionbuilder beandefinitionburinilder = beandefinitionbuilder.genericbeandefinition(beanclass); beandefinition beandefinition = beandefinitionburinilder.getbeandefinition(); setbeanfield(beanclass, beandefinition); getbeandefinitionregistry().registerbeandefinition(beanname,beandefinition); } /** * 设置bean字段值 * @param beanclass * @param beandefinition */ private void setbeanfield(class beanclass, beandefinition beandefinition) { configurationproperties configurationproperties = (configurationproperties) beanclass.getannotation(configurationproperties.class); if(objectutils.isnotempty(configurationproperties)){ string prefix = configurationproperties.prefix(); for (string propertyname : config.getpropertynames()) { string fieldprefix = prefix + "."; if(propertyname.startswith(fieldprefix)){ string fieldname = propertyname.substring(fieldprefix.length()); string fieldval = config.getproperty(propertyname,null); log.info("setbeanfield-->fieldname:{},fieldval:{}",fieldname,fieldval); beandefinition.getpropertyvalues().add(fieldname,fieldval); } } } } /** * bean移除 * @param beanname */ public void unregisterbean(string beanname){ log.info("unregisterbean->beanname:{}",beanname); getbeandefinitionregistry().removebeandefinition(beanname); } public <t> t getbean(string name) { return (t) applicationcontext.getbean(name); } public <t> t getbean(class<t> clz) { return (t) applicationcontext.getbean(clz); } public boolean isexistbean(string beanname){ return applicationcontext.containsbean(beanname); } public boolean isexistbean(class clz){ try { object bean = applicationcontext.getbean(clz); return true; } catch (beansexception e) { // log.error(e.getmessage(),e); } return false; } private boolean isneedregisterbeanifkeychange(string changekey,string conditionalonpropertyvalue){ if(stringutils.isempty(changekey)){ return false; } string apolloconfigvalue = config.getproperty(changekey,null); return conditionalonpropertyvalue.equals(apolloconfigvalue); } private boolean isneedremovebeanifkeychange(string changekey,string conditionalonpropertyvalue){ if(!stringutils.isempty(changekey)){ string apolloconfigvalue = config.getproperty(changekey,null); return !conditionalonpropertyvalue.equals(apolloconfigvalue); } return false; } private boolean ischangekey(configchangeevent changeevent,string conditionalonpropertykey){ set<string> changekeys = changeevent.changedkeys(); if(!collectionutils.isempty(changekeys) && changekeys.contains(conditionalonpropertykey)){ return true; } return false; } private string getchangekey(configchangeevent changeevent, string[] conditionalonpropertykeys){ if(arrayutils.isempty(conditionalonpropertykeys)){ return null; } string changekey = null; for (string conditionalonpropertykey : conditionalonpropertykeys) { if(ischangekey(changeevent,conditionalonpropertykey)){ changekey = conditionalonpropertykey; break; } } return changekey; } private beandefinitionregistry getbeandefinitionregistry(){ configurableapplicationcontext configurablecontext = (configurableapplicationcontext) applicationcontext; beandefinitionregistry beandefinitionregistry = (defaultlistablebeanfactory) configurablecontext.getbeanfactory(); return beandefinitionregistry; } private list<string> listbasepackages(){ configurableapplicationcontext configurablecontext = (configurableapplicationcontext) applicationcontext; return autoconfigurationpackages.get(configurablecontext.getbeanfactory()); } @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { this.applicationcontext = applicationcontext; } public void printallbeans() { string[] beans = applicationcontext.getbeandefinitionnames(); arrays.sort(beans); for (string beanname : beans) { class<?> beantype = applicationcontext.gettype(beanname); system.out.println(beantype); } } }
如果条件注解的值也是配置在apollo上,可能会出现依赖条件注解的bean的其他bean,在项目拉取apollo配置时,就已经注入spring容器中,此时就算条件注解满足条件,则引用该条件注解bean的其他bean,也会拿不到条件注解bean。此时有2种方法解决,一种是在依赖条件注解bean的其他bean注入之前,先手动注册条件注解bean到spring容器中,其核心代码如下
@component @slf4j public class refreshbeanfactory implements beanfactorypostprocessor { @override public void postprocessbeanfactory(configurablelistablebeanfactory configurablelistablebeanfactory) throws beansexception { config config = configservice.getconfig("order.properties"); list<string> basepackages = autoconfigurationpackages.get(configurablelistablebeanfactory); for (string basepackage : basepackages) { set<class> conditionalclasses = classscannerutils.scan(basepackage, conditionalonproperty.class); if(!collectionutils.isempty(conditionalclasses)){ for (class conditionalclass : conditionalclasses) { conditionalonproperty conditionalonproperty = (conditionalonproperty) conditionalclass.getannotation(conditionalonproperty.class); string[] conditionalonpropertykeys = conditionalonproperty.name(); string beanconditionkey = this.getconditionalonpropertykey(config,conditionalonpropertykeys); string conditionalonpropertyvalue = conditionalonproperty.havingvalue(); this.registerbeanifmatchcondition((defaultlistablebeanfactory)configurablelistablebeanfactory,config,conditionalclass,beanconditionkey,conditionalonpropertyvalue); } } } } private void registerbeanifmatchcondition(defaultlistablebeanfactory beanfactory,config config,class conditionalclass, string beanconditionkey, string conditionalonpropertyvalue) { boolean isneedregisterbean = this.isneedregisterbean(config,beanconditionkey,conditionalonpropertyvalue); string beanname = stringutils.uncapitalize(conditionalclass.getsimplename()); if(isneedregisterbean){ this.registerbean(config,beanfactory,beanname,conditionalclass); } } public void registerbean(config config,defaultlistablebeanfactory beanfactory, string beanname, class beanclass) { log.info("registerbean->beanname:{},beanclass:{}",beanname,beanclass); beandefinitionbuilder beandefinitionburinilder = beandefinitionbuilder.genericbeandefinition(beanclass); beandefinition beandefinition = beandefinitionburinilder.getbeandefinition(); setbeanfield(config,beanclass, beandefinition); beanfactory.registerbeandefinition(beanname,beandefinition); } private void setbeanfield(config config,class beanclass, beandefinition beandefinition) { configurationproperties configurationproperties = (configurationproperties) beanclass.getannotation(configurationproperties.class); if(objectutils.isnotempty(configurationproperties)){ string prefix = configurationproperties.prefix(); for (string propertyname : config.getpropertynames()) { string fieldprefix = prefix + "."; if(propertyname.startswith(fieldprefix)){ string fieldname = propertyname.substring(fieldprefix.length()); string fieldval = config.getproperty(propertyname,null); log.info("setbeanfield-->fieldname:{},fieldval:{}",fieldname,fieldval); beandefinition.getpropertyvalues().add(fieldname,fieldval); } } } } public boolean isneedregisterbean(config config,string beanconditionkey,string conditionalonpropertyvalue){ if(stringutils.isempty(beanconditionkey)){ return false; } string apolloconfigvalue = config.getproperty(beanconditionkey,null); return conditionalonpropertyvalue.equals(apolloconfigvalue); } private string getconditionalonpropertykey(config config, string[] conditionalonpropertykeys){ if(arrayutils.isempty(conditionalonpropertykeys)){ return null; } string changekey = null; for (string conditionalonpropertykey : conditionalonpropertykeys) { if(isconditionalonpropertykey(config,conditionalonpropertykey)){ changekey = conditionalonpropertykey; break; } } return changekey; } private boolean isconditionalonpropertykey(config config,string conditionalonpropertykey){ set<string> propertynames = config.getpropertynames(); if(!collectionutils.isempty(propertynames) && propertynames.contains(conditionalonpropertykey)){ return true; } return false; } }
其次利用懒加载的思想,在使用条件注解bean时,使用形如下方法
order order = (order) springcontextutils.getbean("order");
总结
本文主要介绍了常用的动态刷新,但本文的代码示例实现的功能不局限于此,本文的代码还实现如何通过自定义注解与apollo整合来实现一些业务操作,同时也实现了基于hystrix注解与apollo整合,实现基于线程隔离的动态熔断,感兴趣的朋友可以复制文末链接到浏览器,进行查看
apollo基本上是能满足我们日常的业务开发要求,但是对于一些需求,比如动态刷新线上数据库资源啥,我们还是得做一定的量的改造,好在携程也提供了apollo-use-cases,在里面可以找到常用的使用场景以及示例代码,其链接如下
感兴趣的朋友,可以查看下。
demo链接
到此这篇关于apollo与springboot集成实现动态刷新配置的文章就介绍到这了,更多相关apollo与springboot集成动态刷新配置内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!