1.创建一个config-server服务
1.1 bootstrap.yml(优先加载权)
server: port: 8091 spring: cloud: config: uri: http://localhost:8090/ #config-server的服务地址 profile: dev label: master application: name: config-server management: security: enabled: false
1.2 依赖
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
<!--当git/svn中的配置文件改变时,动态的刷新获取数据--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies>
1.3 启动类
package com.transsion; import jdk.nashorn.internal.ir.annotations.Reference; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; @SpringBootApplication public class ConfigClientApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); } }
1.4 增加controller类访问配置文件的数据
package com.transsion; import org.springframework.beans.factory.annotation.Value; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RefreshScope public class ClientController { @Value("${id}") //用于获取在git仓库中的配置文件的属性。 private String id; @RequestMapping("/config") public String getConfig() { return this.id; } }
1.5 常见错误:Could not resolve placeholder
client的spring.application.name和profile与server一致,并且在配置文件中有该属性(Key)
1.6配置中心的动态刷新
a.单个客户端刷新
1.在config-client工程中增加依赖:spring-boot-starter-actuator
2. 在需要刷新配置的类上,使用注解:@RefreshScope
3. 在config-client的配置文件中,加入:management.security.enabled=false
4.调用http://localhost:8881/refresh接口
关闭鉴权,这样才能post请求访问 当前项目/refresh 接口的时候更新配置文件,否则需要Authorization头
b.使用spring cloud bus + rabbitmq 实现多个客户端刷新
1.在config-client 和 config-client2中增加依赖:spring-cloud-starter-bus-amqp
2.安装rabbitmq并运行:https://www.rabbitmq.com/download.html
执行$RABBITMQ_HOME/sbin/rabbitmq-server来启动rabbitmq,rabbitmq的默认用户和密码都是guest,而默认端口是5672
3.配置文件:rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
4.使用post方式请求任一客户端的/bus/refresh接口,就会更新所有客户端的配置