server: port: 8091 spring: cloud: config: uri: http://localhost:8090/ #config-server的服务地址 profile: dev label: master application: name: config-server management: security: enabled: false
<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>
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); } }
启动项目,访问地址http://localhost:8091/config即可以找到配置文件中对应id的值。为1。
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; } }
client的spring.application.name和profile与server一致,并且在配置文件中有该属性(Key)
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接口,就会更新所有客户端的配置
springcloud demo---config-client
原文:https://www.cnblogs.com/rainsakura/p/10407171.html