配置中心:Spring Cloud Config

来源:互联网 发布:java web文件上传组件 编辑:程序博客网 时间:2024/05/01 04:53

1.Spring Cloud Config 服务端(基于git)

1.1添加依赖

<dependency>   <groupId>org.springframework.cloud</groupId>   <artifactId>spring-cloud-config-server</artifactId></dependency>

1.2配置

#spring.cloud.config.server.git.uri=file:///${user.home}/config-repo 本地调试用spring.cloud.config.server.git.uri=https://github.com/xxx/xxx/spring.cloud.config.server.git.search-paths={application}spring.cloud.config.server.git.username=xxx@qq.comspring.cloud.config.server.git.password=xxxspring.application.name=config-serverserver.port=6789eureka.client.service-url.defaultZone=http://localhost:1111/eureka/,http://localhost:1112/eureka/
我们看search-paths设置成动态参数,这个参数是客户端传过来的,就是客户端的服务名称,这样我们就可以分多个
目录,将不同的应用配置文件放到git下不同的目录,而目录名就是客户端的服务名。

1.3配置中心访问规则

仓库中的配置文件会被转换成web接口,访问可以参照以下的规则:

/{application}/{profile}[/{label}]

/{application}-{profile}.yml

/{label}/{application}-{profile}.yml

/{application}-{profile}.properties

/{label}/{application}-{profile}.properties

 lable分支默认是master profile代表的环境,比如dev,beta,online等。

2.Spring Cloud Config 客户端

2.1添加依赖

<dependency>    <groupId>org.springframework.cloud</groupId>    <artifactId>spring-cloud-starter-config</artifactId></dependency>

2.2配置文件

spring:  cloud:    config:       name: mem-web       profile: dev       #uri: http://localhost:6789/       label: master       discovery:         service-id: config-server         enabled: true       fail-fast: trueeureka:  client:    service-url:     defaultZone: http://localhost:1111/eureka/,http://localhost:1111/eureka/

我们可以使用服务发现,实现高可用。

2.3使用配置文件数据

1.通过@Value注解
@RestController@RefreshScopepublic class TestRestController {    @Value("${name}")    private String name;    @RequestMapping("/getVersion")    public Object home() {        return name;    }}
2.通过Environment对象
@RestController@RefreshScopepublic class TestRestController {    @Autowired    private Environment environment;    @RequestMapping("/getVersion")    public Object home() {        return environment.getProperty("name", "undefined");    }}

3.最佳实践



其中配置变动时,请求服务中心 /bus/refresh 接口可以基于配置git 的hook实现。

我们通过向服务实例请求SpringCloud Bus的/bus/refresh接口,从而触发总线上其他服务实例的/refresh。但是有些特殊场景下(比如:灰度发布),我们希望可以刷新微服务中某个具体实例的配置。

Spring Cloud Bus对这种场景也有很好的支持:/bus/refresh接口还提供了destination参数,用来定位具体要刷新的应用程序。比如,我们可以请求/bus/refresh?destination=customers:9000,此时总线上的各应用实例会根据destination属性的值来判断是否为自己的实例名,若符合才进行配置刷新,若不符合就忽略该消息。

destination参数除了可以定位具体的实例之外,还可以用来定位具体的服务。定位服务的原理是通过使用Spring的PathMatecher(路径匹配)来实现,比如:/bus/refresh?destination=customers:**,该请求会触发customers服务的所有实例进行刷新。



阅读全文
0 0
原创粉丝点击