The World Best ST.

Apollo使用

字数统计: 358阅读时长: 1 min
2019/04/26 Share

Apollo使用

Apollo支持许多语言

本文举例Springboot整合apollo配置中心的使用

SpringBoot整合Apollo配置中心

1. pom.xml加入apollo依赖

1
2
3
4
5
6
<!-- apollo -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.1.0</version>
</dependency>

2. 修改配置文件

1
2
3
4
5
# apollo项目名
app:
id: SampleApp
apollo:
meta: http://127.0.0.1:8080

3. 启动时指定使用的apollo环境

虚拟机参数:

-Denv=YOUR-ENVIRONMENT

or

指定启动环境:
profiles:
active: dev

4. 配置的获取

1). 配置文件直接注入(Spring Placeholder)

1
2
3
4
5
6
7
8
@Data
@Configuration
@EnableAutoConfiguration
public class ApolloDemoConfig {
// st为默认值, 避免没有key的情况
@Value("${name:st}")
private String name;
}

使用时:

1
2
@Autowired
ApolloDemoConfig apolloDemoConfig;

如果注入的参数运行时动态更新,可增加如下配置:

1
2
apollo:
autoUpdateInjectedSpringProperties: false

2). 使用ConfigurationProperties注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Configuration
@ConfigurationProperties(prefix = "redis.cache")
public class SampleRedisConfig {
private int expireSeconds;
private int commandTimeout;

public void setExpireSeconds(int expireSeconds) {
this.expireSeconds = expireSeconds;
}

public void setCommandTimeout(int commandTimeout) {
this.commandTimeout = commandTimeout;
}

public int getExpireSeconds() {
return expireSeconds;
}

public int getCommandTimeout() {
return commandTimeout;
}
}

注: @ConfigurationProperties如果需要在Apollo配置变化时自动更新注入的值,需要配合使用EnvironmentChangeEvent或RefreshScope

3). @ApolloConfig注解的使用

1
2
3
4
5
6
7
8
9
10
11
@ApolloConfig
private Config config;

@RequestMapping("/index3")
public String hello3(){
Set <String> propertyNames = config.getPropertyNames();
propertyNames.forEach(key -> {
System.err.println(key+"="+config.getIntProperty(key,0));
});
return propertyNames.toString();
}

其他还有一些Apollo的注解

  • @ApolloConfigChangeListener用来自动注册ConfigChangeListener
  • @ApolloJsonValue用来把配置的json字符串自动注入为对象
CATALOG
  1. 1. Apollo使用
    1. 1.1. SpringBoot整合Apollo配置中心
      1. 1.1.0.1. 1. pom.xml加入apollo依赖
      2. 1.1.0.2. 2. 修改配置文件
      3. 1.1.0.3. 3. 启动时指定使用的apollo环境
      4. 1.1.0.4. 4. 配置的获取