1 简单对象apollo配置热更新
对于简单对象(如String、Integer、Boolean等),只需要在配置类上增加@RefreshScope注解便可以实现配置热更新,如下代码:
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
/**
* TestConfig 配置
*
* @author gongmin
* @date 2023/9/25 12:00
*/
@Configuration
@RefreshScope
@Getter
@Setter
public class TestConfig {
@Value("${test.app-id}")
private String appId;
@Value("${test.secret}")
private String secret;
}
2 复杂对象apollo配置热更新
@Value注解无法对复杂对象(如List<Object>, Object, Map<String, Object>等)生效,我们需要监听apollo配置变化,编码实现热更新
2.1 配置内容如下:
test-config:
list:
- name: gongmin
address: 长沙
phone: 123456789
- name: xiaoli
address: 北京
phone: 987654321
map:
"gongmin": {"name": "gongmin", "address": "长沙", "phone": "123456789"}
"xiaoli": {"name": "xiaoli", "address": "北京", "phone": "987654321"}
obj:
name: gongmin
address: 长沙
phone: 123456789
2.2 配置类如下:
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import java.util.*;
/**
* TestConfig
*
* @author gongmin
* @date 2023/9/25 14:43
*/
@Configuration
@Getter
@Setter
@ConfigurationProperties(prefix = "test-config")
@RefreshScope
public class TestConfig {
private List<UserInfo> list = Collections.emptyList();
private Map<String, UserInfo> map = new HashMap<>(0);
private UserInfo obj = new UserInfo();
@Getter
@Setter
public static class UserInfo {
private String name;
private String address;
private String phone;
}
}
2.3 监听apollo配置变化
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
* apollo配置动态刷新
*
* @author gongmin
* @date 2023/9/25 13:44
*/
@Slf4j
@Component
public class ApolloRefreshListener {
@Resource
private RefreshScope refreshScope;
/**
* 监听配置文件变化并刷新内存配置
*/
@ApolloConfigChangeListener(value = {"application.yml", "application.properties"})
private void cacheRefresh(ConfigChangeEvent changeEvent) {
log.info("<cacheRefresh> {} 配置文件发生变化", changeEvent.getNamespace());
refreshScope.refresh("testConfig");
}
}
3 注意:不管是简单对象还是复杂对象的配置热更新,都需要在配置类上加@RefreshScope注解