springboot项目接入配置中心,实现@ConfigurationProperties的bean属性刷新方案

前言

  配置中心,通过key=value的形式存储环境变量。配置中心的属性做了修改,项目中可以通过配置中心的依赖(sdk)立即感知到。需要做的就是如何在属性发生变化时,改变带有@ConfigurationProperties的bean的相关属性。

配置中心

  在读配置中心源码的时候发现,里面维护了一个Environment,以及ZookeeperPropertySource。当配置中心属性发生变化的时候,清空ZookeeperPropertySource,并放入最新的属性值。

  

public class ZookeeperPropertySource extends EnumerablePropertySource<Properties>

  

  ZookeeperPropertySource重写了equals和hahscode方法,根据这两个方法可以判定配置中心是否修改了属性。

  

配置中心定义的属性变量

message.center.channels[0].type=HELIUYAN
message.center.channels[0].desc=和留言系统
message.center.channels[1].type=EC_BACKEND
message.center.channels[1].desc=电商后台
message.center.channels[2].type=BILL_FLOW
message.center.channels[2].desc=话费和流量提醒
message.center.channels[3].type=INTEGRATED_CASHIER
message.center.channels[3].desc=综合收银台message.center.businesses[0].type=BIZ_EXP_REMINDER
message.center.businesses[0].desc=业务到期提醒
message.center.businesses[0].topic=message-center-biz-expiration-reminder-topic
message.center.businesses[1].type=RECHARGE_TRANSACTION_PUSH
message.center.businesses[1].desc=充值交易实时推送
message.center.businesses[1].topic=message-center-recharge-transaction-push-topicmessage.center.businesses2Channels[BIZ_EXP_REMINDER]=EC_BACKEND
message.center.businesses2Channels[RECHARGE_TRANSACTION_PUSH]=INTEGRATED_CASHIERmessage.center.bizTypeForMsgType[RECHARGE_TRANSACTION_PUSH]=data.type:pay-finish,data.type:rechr-finish,data.type:refund-finish

java属性配置映射类

import org.springframework.boot.context.properties.ConfigurationProperties;import java.util.List;
import java.util.Map;
import java.util.Objects;/*** @author hujunzheng* @create 2018-06-28 11:37**/
@ConfigurationProperties(prefix = "message.center")
public class MessageCenterConstants {private List<Business> businesses;private List<Channel> channels;private Map<String, String> businesses2Channels;private Map<String, String> bizTypeForMsgType;public void setBusinesses(List<Business> businesses) {this.businesses = businesses;}public void setChannels(List<Channel> channels) {this.channels = channels;}public List<Business> getBusinesses() {return businesses;}public List<Channel> getChannels() {return channels;}public Map<String, String> getBusinesses2Channels() {return businesses2Channels;}public void setBusinesses2Channels(Map<String, String> businesses2Channels) {this.businesses2Channels = businesses2Channels;}public Map<String, String> getBizTypeForMsgType() {return bizTypeForMsgType;}public void setBizTypeForMsgType(Map<String, String> bizTypeForMsgType) {this.bizTypeForMsgType = bizTypeForMsgType;}public static class Business implements Comparable<Business> {//业务类型private String type;//业务描述private String desc;//对应 kafka 的 topicprivate String topic;public String getType() {return type;}public void setType(String type) {this.type = type;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public String getTopic() {return topic;}public void setTopic(String topic) {this.topic = topic;}@Overridepublic int compareTo(Business o) {if (type.compareTo(o.type) == 0 || topic.compareTo(o.topic) == 0) {return 0;}return Objects.hash(type, topic);}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Business business = (Business) o;return Objects.equals(type, business.type) ||Objects.equals(topic, business.topic);}@Overridepublic int hashCode() {return Objects.hash(type, topic);}@Overridepublic String toString() {return "Business{" +"type='" + type + '\'' +", desc='" + desc + '\'' +", topic='" + topic + '\'' +'}';}}public static class Channel implements Comparable<Channel> {//渠道类型private String type;//渠道描述private String desc;public String getType() {return type;}public void setType(String type) {this.type = type;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}@Overridepublic int compareTo(Channel o) {return this.type.compareTo(o.type);}@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Channel channel = (Channel) o;return Objects.equals(type, channel.type);}@Overridepublic int hashCode() {return Objects.hash(type);}@Overridepublic String toString() {return "Channel{" +"type='" + type + '\'' +", desc='" + desc + '\'' +'}';}}
}

属性刷新方案

@Bean
public MergedProperties kafkaMessageMergedProperties() {return ConfigCenterUtils.createToRefreshPropertiesBean(MergedProperties.class);
}public static class MergedProperties {private Map<String, MessageCenterConstants.Business> businesses;private Map<String, MessageCenterConstants.Channel> channels;//业务映射渠道private Map<String, String> businesses2Channels;//消息类型映射业务类型private Map<String, String> msgType2BizType;public MergedProperties() throws GeneralException {this.refreshProperties();}private void refreshProperties() throws GeneralException {
//获取到配置中心最新的propertySourceZookeeperPropertySource propertySource
= ConfigHelper.getZookeeperPropertySource();MessageCenterConstants messageCenterConstants = null;
     //判断属性是否刷新
if (ConfigCenterUtils.propertySourceRefresh(propertySource)) {
       //将属性binding到带有@ConfigurationProperties注解的类中messageCenterConstants
=RelaxedConfigurationBinder.with(MessageCenterConstants.class).setPropertySources(propertySource).doBind();}
     //以下是自定义处理,可忽略
if (!Objects.isNull(messageCenterConstants)) {//Business.type <-> Businessthis.setBusinesses(Maps.newHashMap(Maps.uniqueIndex(Sets.newHashSet(messageCenterConstants.getBusinesses()), business -> business.getType())));//Channel.type <-> Channelthis.setChannels(Maps.newHashMap(Maps.uniqueIndex(Sets.newHashSet(messageCenterConstants.getChannels()), channel -> channel.getType())));//business <-> channelsthis.setBusinesses2Channels(messageCenterConstants.getBusinesses2Channels());//消息类型映射业务类型this.setMsgType2BizType(messageCenterConstants.getBizTypeForMsgType().entrySet().stream().map(entry -> {Map<String, String> tmpMap = Maps.newHashMap();if (StringUtils.isBlank(entry.getValue())) {return tmpMap;}Arrays.stream(entry.getValue().split(",")).forEach(value -> tmpMap.put(value, entry.getKey()));return tmpMap;}).flatMap(map -> map.entrySet().stream()).collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())));}}
   //刷新方法
private void catchRefreshProperties() {try {this.refreshProperties();} catch (Exception e) {LOGGER.error("KafkaMessageConfig 配置中心属性刷新失败", e);}}
   //get方法上指定刷新属性@ToRefresh(method
= "catchRefreshProperties")public Map<String, MessageCenterConstants.Business> getBusinesses() {return businesses;}public void setBusinesses(Map<String, MessageCenterConstants.Business> businesses) {this.businesses = businesses;}@ToRefresh(method = "catchRefreshProperties")public Map<String, MessageCenterConstants.Channel> getChannels() {return channels;}public void setChannels(Map<String, MessageCenterConstants.Channel> channels) {this.channels = channels;}@ToRefresh(method = "catchRefreshProperties")public Map<String, String> getBusinesses2Channels() {return businesses2Channels;}public void setBusinesses2Channels(Map<String, String> businesses2Channels) {this.businesses2Channels = businesses2Channels;}@ToRefresh(method = "catchRefreshProperties")public Map<String, String> getMsgType2BizType() {return msgType2BizType;}public void setMsgType2BizType(Map<String, String> msgType2BizType) {this.msgType2BizType = msgType2BizType;} }

工具类

ConfigCenterUtils

import com.cmos.cfg.core.ConfigHelper;
import com.cmos.cfg.zookeeper.ZookeeperPropertySource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ReflectionUtils;import java.lang.reflect.Method;
import java.util.Objects;/*** @author hujunzheng* @create 2018-07-04 15:45**/
public class ConfigCenterUtils {private static ZookeeperPropertySource propertySource = ConfigHelper.getZookeeperPropertySource();

  //判断配置中心属性是否刷新
public synchronized static boolean propertySourceRefresh(ZookeeperPropertySource newPropertySource) {if (propertySource.equals(newPropertySource)) {return false;}if (propertySource.hashCode() == newPropertySource.hashCode()) {return false;}propertySource = newPropertySource;return true;}
   //创建代理类,代理@ToRefresh注解的方法,调用相应的刷新方法
public static <T> T createToRefreshPropertiesBean(Class<T> clazz) {Enhancer enhancer = new Enhancer();// 设置代理对象父类 enhancer.setSuperclass(clazz);// 设置增强enhancer.setCallback(new MethodInterceptor() {@Overridepublic Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {ToRefresh toRefresh = AnnotationUtils.findAnnotation(method, ToRefresh.class);if (Objects.isNull(toRefresh) || StringUtils.isBlank(toRefresh.method())) {return methodProxy.invokeSuper(target, args);}Method refreshMethod = ReflectionUtils.findMethod(target.getClass(), toRefresh.method());if (Objects.isNull(refreshMethod)) {return methodProxy.invokeSuper(target, args);}refreshMethod = BridgeMethodResolver.findBridgedMethod(refreshMethod);refreshMethod.setAccessible(true);refreshMethod.invoke(target, null);return methodProxy.invokeSuper(target, args);}});return (T) enhancer.create();// 创建代理对象 } }
import org.apache.commons.lang3.StringUtils;import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;/*** @author hujunzheng* @create 2018-07-06 9:59**/
@Target({METHOD})
@Retention(RUNTIME)
@Documented
public @interface ToRefresh {//刷新方法String method() default StringUtils.EMPTY;
}

RelaxedConfigurationBinder

  动态将propertysource绑定到带有@ConfigurationProperties注解的bean中

  参考:org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor

import com.cmos.common.exception.GeneralException;
import org.springframework.boot.bind.PropertiesConfigurationFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.env.*;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.SpringValidatorAdapter;import javax.validation.Validation;import static org.springframework.core.annotation.AnnotatedElementUtils.getMergedAnnotation;/*** @author hujunzheng* @create 2018-07-03 18:01** 不强依赖ConfigurationProperties,进行配置注入**/
public class RelaxedConfigurationBinder<T> {private final PropertiesConfigurationFactory<T> factory;public RelaxedConfigurationBinder(T object) {this(new PropertiesConfigurationFactory<>(object));}public RelaxedConfigurationBinder(Class<T> type) {this(new PropertiesConfigurationFactory<>(type));}public static <T> RelaxedConfigurationBinder<T> with(T object) {return new RelaxedConfigurationBinder<>(object);}public static <T> RelaxedConfigurationBinder<T> with(Class<T> type) {return new RelaxedConfigurationBinder<>(type);}public RelaxedConfigurationBinder(PropertiesConfigurationFactory<T> factory) {this.factory = factory;ConfigurationProperties properties = getMergedAnnotation(factory.getObjectType(), ConfigurationProperties.class);javax.validation.Validator validator = Validation.buildDefaultValidatorFactory().getValidator();factory.setValidator(new SpringValidatorAdapter(validator));factory.setConversionService(new DefaultConversionService());if (null != properties) {factory.setIgnoreNestedProperties(properties.ignoreNestedProperties());factory.setIgnoreInvalidFields(properties.ignoreInvalidFields());factory.setIgnoreUnknownFields(properties.ignoreUnknownFields());factory.setTargetName(properties.prefix());factory.setExceptionIfInvalid(properties.exceptionIfInvalid());}}public RelaxedConfigurationBinder<T> setTargetName(String targetName) {factory.setTargetName(targetName);return this;}public RelaxedConfigurationBinder<T> setPropertySources(PropertySource<?>... propertySources) {MutablePropertySources sources = new MutablePropertySources();for (PropertySource<?> propertySource : propertySources) {sources.addLast(propertySource);}factory.setPropertySources(sources);return this;}public RelaxedConfigurationBinder<T> setPropertySources(Environment environment) {factory.setPropertySources(((ConfigurableEnvironment) environment).getPropertySources());return this;}public RelaxedConfigurationBinder<T> setPropertySources(PropertySources propertySources) {factory.setPropertySources(propertySources);return this;}public RelaxedConfigurationBinder<T> setConversionService(ConversionService conversionService) {factory.setConversionService(conversionService);return this;}public RelaxedConfigurationBinder<T> setValidator(Validator validator) {factory.setValidator(validator);return this;}public RelaxedConfigurationBinder<T> setResolvePlaceholders(boolean resolvePlaceholders) {factory.setResolvePlaceholders(resolvePlaceholders);return this;}public T doBind() throws GeneralException {try {return factory.getObject();} catch (Exception ex) {throw new GeneralException("配置绑定失败!", ex);}}
}

 

转载于:https://www.cnblogs.com/hujunzheng/p/9272866.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/531226.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

简单封装kafka相关的api

一、针对于kafka版本 <dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId><version>0.8.2.2</version></dependency><dependency><groupId>org.apache.kafka</groupId>…

springmvc controller动态设置content-type

springmvc RequestMappingHandlerAdapter#invokeHandlerMethod 通过ServletInvocableHandlerMethod#invokeAndHandle调用目标方法&#xff0c;并处理返回值。 如果return value &#xff01; null&#xff0c;则通过returnvalueHandlers处理&#xff0c;内部会调用MessageConv…

springboot2.0 redis EnableCaching的配置和使用

一、前言 关于EnableCaching最简单使用&#xff0c;个人感觉只需提供一个CacheManager的一个实例就好了。springboot为我们提供了cache相关的自动配置。引入cache模块&#xff0c;如下。 二、maven依赖 <dependency><groupId>org.springframework.boot</groupId…

依赖配置中心实现注有@ConfigurationProperties的bean相关属性刷新

配置中心是什么 配置中心&#xff0c;通过keyvalue的形式存储环境变量。配置中心的属性做了修改&#xff0c;项目中可以通过配置中心的依赖&#xff08;sdk&#xff09;立即感知到。需要做的就是如何在属性发生变化时&#xff0c;改变带有ConfigurationProperties的bean的相关属…

java接口签名(Signature)实现方案

预祝大家国庆节快乐&#xff0c;赶快迎接美丽而快乐的假期吧&#xff01;&#xff01;&#xff01; 前言 在为第三方系统提供接口的时候&#xff0c;肯定要考虑接口数据的安全问题&#xff0c;比如数据是否被篡改&#xff0c;数据是否已经过时&#xff0c;数据是否可以重复提交…

Git rebase命令实战

一、前言 一句话&#xff0c;git rebase 可以帮助项目中的提交历史干净整洁&#xff01;&#xff01;&#xff01; 二、避免合并出现分叉现象 git merge操作 1、新建一个 develop 分支 2、在develop分支上新建两个文件 3、然后分别执行 add、commit、push 4、接着切换到master分…

windows系统nexus3安装和配置

一、前言 为什么要在本地开发机器上安装nexus&#xff1f;首先声明公司内部是有自己的nexus仓库&#xff0c;但是对上传jar包做了限制&#xff0c;不能畅快的上传自己测试包依赖。于是就自己在本地搭建了一个nexus私服&#xff0c;即可以使用公司nexus私服仓库中的依赖&#xf…

Springmvc借助SimpleUrlHandlerMapping实现接口开关功能

一、接口开关功能 1、可配置化&#xff0c;依赖配置中心 2、接口访问权限可控 3、springmvc不会扫描到&#xff0c;即不会直接的将接口暴露出去 二、接口开关使用场景 和业务没什么关系&#xff0c;主要方便查询系统中的一些状态信息。比如系统的配置信息&#xff0c;中间件的状…

log4j平稳升级到log4j2

一、前言 公司中的项目虽然已经用了很多的新技术了&#xff0c;但是日志的底层框架还是log4j&#xff0c;个人还是不喜欢用这个的。最近项目再生产环境上由于log4j引起了一场血案&#xff0c;于是决定升级到log4j2。 二、现象 虽然生产环境有多个结点分散高并发带来的压力&…

Springboot集成ES启动报错

报错内容 None of the configured nodes are available elasticsearch.yml配置 cluster.name: ftest node.name: node-72 node.master: true node.data: true network.host: 112.122.245.212 http.port: 39200 transport.tcp.port: 39300 discovery.zen.ping.unicast.hosts: [&…

kafka-manager配置和使用

kafka-manager配置 最主要配置就是用于kafka管理器状态的zookeeper主机。这可以在conf目录中的application.conf文件中找到。 kafka-manager.zkhosts"my.zookeeper.host.com:2181" 当然也可以声明为zookeeper集群。 kafka-manager.zkhosts"my.zookeeper.host.co…

kafka告警简单方案

一、前言 为什么要设计kafka告警方案&#xff1f;现成的监控项目百度一下一大堆&#xff0c;KafkaOffsetMonitor、KafkaManager、 Burrow等&#xff0c;具体参考&#xff1a;kafka的消息挤压监控。由于本小组的项目使用的kafka集群并没有被公司的kafka-manager管理&#xff0c;…

RedisCacheManager设置Value序列化器技巧

CacheManager基本配置 请参考博文&#xff1a;springboot2.0 redis EnableCaching的配置和使用 RedisCacheManager构造函数 /*** Construct a {link RedisCacheManager}.* * param redisOperations*/ SuppressWarnings("rawtypes") public RedisCacheManager(RedisOp…

HashMap 源码阅读

前言 之前读过一些类的源码&#xff0c;近来发现都忘了&#xff0c;再读一遍整理记录一下。这次读的是 JDK 11 的代码&#xff0c;贴上来的源码会去掉大部分的注释, 也会加上一些自己的理解。 Map 接口 这里提一下 Map 接口与1.8相比 Map接口又新增了几个方法&#xff1a;   …

SpringMvc接口中转设计(策略+模板方法)

一、前言 最近带着两个兄弟做支付宝小程序后端相关的开发&#xff0c;小程序首页涉及到很多查询的服务。小程序后端服务在我司属于互联网域&#xff0c;相关的查询服务已经在核心域存在了&#xff0c;查询这块所要做的工作就是做接口中转。参考了微信小程序的代码&#xff0c;发…

SpringSecurity整合JWT

一、前言 最近负责支付宝小程序后端项目设计&#xff0c;这里主要分享一下用户会话、接口鉴权的设计。参考过微信小程序后端的设计&#xff0c;会话需要依靠redis。相关的开发人员和我说依靠Redis并不是很靠谱&#xff0c;redis在业务高峰期不稳定&#xff0c;容易出现问题&…

Springboot定时任务原理及如何动态创建定时任务

一、前言 上周工作遇到了一个需求&#xff0c;同步多个省份销号数据&#xff0c;解绑微信粉丝。分省定时将销号数据放到SFTP服务器上&#xff0c;我需要开发定时任务去解析文件。因为是多省份&#xff0c;服务器、文件名规则、数据规则都不一定&#xff0c;所以要做成可配置是有…

转载:ThreadPoolExecutor 源码阅读

前言 之前研究了一下如何使用ScheduledThreadPoolExecutor动态创建定时任务(Springboot定时任务原理及如何动态创建定时任务)&#xff0c;简单了解了ScheduledThreadPoolExecutor相关源码。今天看了同学写的ThreadPoolExecutor 的源码解读&#xff0c;甚是NB&#xff0c;必须转…

使用pdfBox实现pdf转图片,解决中文方块乱码等问题

一、引入依赖 <dependency><groupId>org.apache.pdfbox</groupId><artifactId>fontbox</artifactId><version>2.0.13</version> </dependency> <dependency><groupId>org.apache.pdfbox</groupId><artif…

Spring异步调用原理及SpringAop拦截器链原理

一、Spring异步调用底层原理 开启异步调用只需一个注解EnableAsync Target(ElementType.TYPE) Retention(RetentionPolicy.RUNTIME) Documented Import(AsyncConfigurationSelector.class) public interface EnableAsync {/*** Indicate the async annotation type to be detec…