apollo动态切换mysql数据源_apollo与springboot集成实现动态刷新配置

分布式apollo简介

Apollo(阿波罗)是携程框架部门研发的开源配置管理中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性。

本文主要介绍如何使用apollo与springboot实现动态刷新配置,如果之前不了解apollo可以查看如下文档

学习了解一下apollo,再来查看本文

正文

apollo与spring实现动态刷新配置本文主要演示2种刷新,一种基于普通字段刷新、一种基于bean上使用了@ConfigurationProperties刷新

1、普通字段刷新

a、pom.xml配置

com.ctrip.framework.apollo

apollo-client

1.6.0

b、客户端配置AppId,Apollo Meta Server

此配置有多种方法,本示例直接在application.yml配置,配置内容如下

app:

id: ${spring.application.name}

apollo:

meta: http://192.168.88.128:8080,http://192.168.88.129:8080

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要额外引入

org.springframework.cloud

spring-cloud-context

2.0.3.RELEASE

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.applicationCo

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值