服务配置新姿势之consul
Consul不仅能用来服务注册和发现,Consul而且支持Key/Value键值对的存储,可以用来做配置中心。Spring Cloud 提供了Spring Cloud Consul Config依赖去和Consul相集成,用来做配置中心。
现在以案例的形式来讲解如何使用Consul作为配置中心,本案例在上一个案例的consul-provider基础上进行改造。首先在工程的pom文件加上consul-config的起步依赖,代码如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
然后在consul-provider工程配置文件application.yml加上以下的以下的配置,配置如下:
spring:
profiles:
active: dev
关于spring.cloud.consul.config的配置项描述如下:
enabled 设置config是否启用,默认为true
format 设置配置的值的格式,可以yaml和properties
prefix 设置配的基本目录,比如config
defaultContext 设置默认的配置,被所有的应用读取,本例子没用的
profileSeparator profiles配置分隔符,默认为‘,’
date-key为应用配置的key名字,值为整个应用配置的字符串。
网页上访问consul的KV存储的管理界面,即http://localhost:8500/ui/dc1/kv,创建一条记录,
key值为:config/consul-provider:dev/data
value值如下:
foo:
bar: bar1
server:
port: 8081
在consul-provider工程新建一个API,该API返回从consul 配置中心读取foo.bar的值,代码如下:
package com.lyh.consulproducer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class HelloController {
@Value("${server.port}")
String port;
@Value("${foo.bar}")
String foo;
@GetMapping("/hi")
public String hi(@RequestParam String name) {
return "hi "+name+",i am from port:" +foo;
}
}
启动工程,可以看到程序的启动端口为8081,即是consul的配置中心配置的server.port端口。
工程启动完成后,在浏览器上访问http://localhost:8081/foo,页面显示bar1。由此可知,应用consul-provider已经成功从consul的配置中心读取了配置foo.bar的配置。
动态刷新配置
当使用spring cloud config作为配置中心的时候,可以使用spring cloud config bus支持动态刷新配置。Spring Cloud Comsul Config默认就支持动态刷新,只需要在需要动态刷新的类上加上@RefreshScope注解即可,修改代码如下:
加上注解@RefreshScope
启动consul-provider工程,在浏览器上访问http://localhost:8081/foo,页面显示bar1。然后
在网页上访问consul的KV存储的管理界面,即http://localhost:8500/ui/dc1/kv,修改config/consul-provider:dev/data的值,修改后的值如下:
foo:
bar: bar2
server:
port: 8081
此时不重新启动consul-provider,在浏览器上访问http://localhost:8081/foo,页面显示bar2。可见foo.bar的最新配置在应用不重启的情况下已经生效。
注意事项
consul支持的KV存储的Value值不能超过512KB
Consul的dev模式,所有数据都存储在内存中,重启Consul的时候会导致所有数据丢失,在正式的环境中,Consul的数据会持久化,数据不会丢失。