Spring Boot Apollo监听namespace并更新配置Bean(附源码)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

这里是weihubeats,觉得文章不错可以关注公众号小奏技术文章首发。拒绝营销号拒绝标题党

背景

如果我们使用的配置中心是apollo的话我们经常会遇到这样的问题就是动态更新配置Bean

动态更新配置bean

动态更新配置bean其实是很简单的但是单纯依赖spring boot是不行的我们还需要添加额外的依赖就是spring cloud相关依赖
具体一个简单的实例如下

依赖

<dependencies>
		
		<dependency>
			<groupId>com.ctrip.framework.apollo</groupId>
			<artifactId>apollo-client</artifactId>
			<version>2.0.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-context</artifactId>
		</dependency>
		
	</dependencies>

spring boot 和 spring cloud版本使用统一依赖管理具体可以看后面的源码

配置bean

  • TestProperties
@ConfigurationProperties("spring.cloud.test")
@ToString
@Data
public class TestProperties {
	
	private String name;
}

动态刷新

  • ApolloPropertiesChangedListener
@Configuration
@Slf4j
public class ApolloPropertiesChangedListener implements ApplicationEventPublisherAware {

	public static final String NAMESPACE = "test.yml";


	private ApplicationEventPublisher publisher;

	@ApolloConfigChangeListener(value = NAMESPACE)
	public void onChange(ConfigChangeEvent changeEvent) {
		publisher.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
	}

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.publisher = applicationEventPublisher;
	}
}

我们也可以通过注解的其他属性刷新指定的key前缀或指定的key
在这里插入图片描述

测试controller

@RestController
@RequestMapping
@EnableConfigurationProperties(TestProperties.class)
@RequiredArgsConstructor
public class TestController {

	private final TestProperties testProperties;
	
	@GetMapping("/test")
	public void test() {
		System.out.println(testProperties);
		
	}
}

测试

http://localhost:8090/test

我们调用接口然后修改apollo的数据
在这里插入图片描述

可以发读取到的配置修改成功了

源码

githu: https://github.com/weihubeats/weihubeats_demos/tree/master/spring-boot-demos/spring-boot-apollo

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring