springboot整合apollo配置中心
springboot整合apollo配置中心官网文档说明得比较清楚,但还是有一些坑注意的。 官网文档:https://www.apolloconfig.com/#/zh/deployment/quick-start
时间:2021年8月4日 23:49:09
1. 部署一个快速启动环境
我的环境是centos7.9,apollo版本应该1.7.0
useradd apollo
passwd apollo
groupadd apollogroup
gpasswd -a apollo apollogroup
cd /home/apollo
yum install git
git clone https://github.com/apolloconfig/apollo-build-scripts
cd apollo-build-scripts
mysql -u root -p
source ./sql/apolloportaldb.sql
source ./sql/apolloconfigdb.sql
修改启动脚本,库连接注意添加时区 和useSSL=false ,我的数据库是mysql5.7.34,不加useSSL=false 会连接异常。自行修改mysql的ip。
vi demo.sh
apollo_config_db_url="jdbc:mysql://localhost:3306/ApolloConfigDB?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false"
apollo_config_db_username=root
apollo_config_db_password=123456
apollo_portal_db_url="jdbc:mysql://localhost:3306/ApolloPortalDB?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false"
apollo_portal_db_username=root
apollo_portal_db_password=123456
启动脚本
chown -R apollo:apollogroup ./*
su apollo
./demo.sh start
启动完成
 访问管理服务:http://192.168.200.128:8070/ 账号密码:apollo/admin
2. 创建一个简单的springboot项目
引入依赖Maven:
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.7.0</version>
</dependency>
修改配置文件application.properties
app.id=my-app-id
apollo.meta=http://192.168.200.128:8080
apollo.cluster=default
apollo.bootstrap.enabled=true
apollo.bootstrap.namespaces=application
apollo.cacheDir=d:\\apollo
apollo.autoUpdateInjectedSpringProperties=true
apollo.bootstrap.eagerLoad.enabled=false
编写一个测试controller
@RestController
public class WebController {
@Value("${test:默认值}")
private String test;
@GetMapping("")
public Object get() {
return test;
}
}

添加apollo配置
访问管理服务:http://192.168.200.128:8070/ 账号密码:apollo/admin 在apollo管理中创建一个项目  添加一个key  再访问 
3. 添加一个配置监听
@Configuration
public class ApolloConfig {
@com.ctrip.framework.apollo.spring.annotation.ApolloConfig
private Config config;
@Bean
public void changeListener() {
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent configChangeEvent) {
System.out.println("Changes for namespace " + configChangeEvent.getNamespace());
for (String key : configChangeEvent.changedKeys()) {
ConfigChange change = configChangeEvent.getChange(key);
System.out.println(String.format("Found change - key: %s, oldValue: %s, newValue: %s, changeType: %s", change.getPropertyName(), change.getOldValue(), change.getNewValue(), change.getChangeType()));
}
}
});
}
}
触发  多个注解参考官网:https://www.apolloconfig.com/#/zh/usage/java-sdk-user-guide?id=_323-spring-annotation%e6%94%af%e6%8c%81
|