1 簡單對象apollo配置熱更新
對于簡單對象(如String、Integer、Boolean等),只需要在配置類上增加@RefreshScope注解便可以實現(xiàn)配置熱更新,如下代碼:
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 復(fù)雜對象apollo配置熱更新
@Value注解無法對復(fù)雜對象(如List<Object>, Object, Map<String, Object>等)生效,我們需要監(jiān)聽apollo配置變化,編碼實現(xiàn)熱更新
2.1 配置內(nèi)容如下:
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 監(jiān)聽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配置動態(tài)刷新
*
* @author gongmin
* @date 2023/9/25 13:44
*/
@Slf4j
@Component
public class ApolloRefreshListener {
@Resource
private RefreshScope refreshScope;
/**
* 監(jiān)聽配置文件變化并刷新內(nèi)存配置
*/
@ApolloConfigChangeListener(value = {"application.yml", "application.properties"})
private void cacheRefresh(ConfigChangeEvent changeEvent) {
log.info("<cacheRefresh> {} 配置文件發(fā)生變化", changeEvent.getNamespace());
refreshScope.refresh("testConfig");
}
}
3 注意:不管是簡單對象還是復(fù)雜對象的配置熱更新,都需要在配置類上加@RefreshScope注解