原文地址
前言
之前我们使用了Consul作为注册中心,一般注册中心会兼任配置中心,如果没有特别完整的配置需求没有必要特别上apollo这种专门做配置的
配置
键值对读取
先引入consul的config包
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
<version>4.0.2</version>
</dependency>
这里我们自底向上来看,先看spring项目在接入时候的配置,这里贴下源码
@ConfigurationProperties(PREFIX)
@Validated
public class ConsulConfigProperties {
/**
* Prefix for configuration properties.
*/
public static final String PREFIX = "spring.cloud.consul.config";
private boolean enabled = true;
private List<String> prefixes = new ArrayList<>(Collections.singletonList("config"));
@NotEmpty
private String defaultContext = "application";
@NotEmpty
private String profileSeparator = ",";
@NotNull
private Format format = Format.KEY_VALUE;
/**
* If format is Format.PROPERTIES or Format.YAML then the following field is used as
* key to look up consul for configuration.
*/
@NotEmpty
private String dataKey = "data";
@Value("${consul.token:${CONSUL_TOKEN:${spring.cloud.consul.token:${SPRING_CLOUD_CONSUL_TOKEN:}}}}")
private String aclToken;
private Watch watch = new Watch();
/**
* Throw exceptions during config lookup if true, otherwise, log warnings.
*/
private boolean failFast = true;
/**
* Alternative to spring.application.name to use in looking up values in consul KV.
*/
private String name;
public ConsulConfigProperties() {
}
@PostConstruct
public void init() {
if (this.format == Format.FILES) {
this.profileSeparator = "-";
}
}
}
我们可以看到,有几个关键参数:
- prefixes:配置文件夹前缀
- defaultContext:配置文件夹名,一般为服务名称
- profileSeparator:环境分割符号
- format:配置文件格式
- dataKey:配置文件名
- acl-token:可以获取配置文件的token,具体配置方法参考使用Consul作为微服务的注册中心
同样,watch的源码
public static class Watch {
/**
* The number of seconds to wait (or block) for watch query, defaults to 55. Needs
* to be less than default ConsulClient (defaults to 60). To increase ConsulClient
* timeout create a ConsulClient bean with a custom ConsulRawClient with a custom
* HttpClient.
*/
private int waitTime = 55;
/** If the watch is enabled. Defaults to true. */
private boolean enabled = true;
/** The value of the fixed delay for the watch in millis. Defaults to 1000. */
private int delay = 1000;
public Watch() {
}
}
这里都有介绍就不赘述了
也就是说我们真正实际需要配置的有:default-context,profile-separator,format,data-key,acl-token(可选),格式我们这里选择YAML,profile-separator使用常用的 “-” ,配置为下,当前环境(prod/test/dev)不用特殊配置会默认取profiles.active
spring:
cloud:
consul:
config:
default-context: house
profile-separator: '-'
format: YAML
data-key: houseCoreConfig
acl-token: your_token
最后我们只需要在consul中配置相关的参数即可
键值对配置
进入后台Key/Value的选项卡,点击创建,刚才我们看到源码前缀是config,我们这里方便起见就创建一个config的文件夹
然后我们这里假设当前服务为hosue配置组名称为houseCoreConfig配置环境为test,所以我们需要创建一个default-context + profile-separator + profileActive的文件夹
最后创建配置组文件即可
此时可在test环境通过@Value(“${myConfigNum}”)获取到123,如果需要动态刷新再加上@RefreshScope注解即可
@Configuration
@RefreshScope
@Getter
public class HouseConfig {
@Value("${myConfigNum}")
private Integer myConfigNum;
}