官网:https://cloud.spring.io/spring-cloud-config/reference/html/
访问方式:
/{application}/{profile}[/{label}] /{application}-{profile}.yml /{label}/{application}-{profile}.yml /{application}-{profile}.properties /{label}/{application}-{profile}.propertiesapplication 服务器名称 profile 环境名称,开发、测试、生产 lable 仓库分支、默认master分支
访问http://localhost:9010/config-dev.yml
把application.yml 改为 bootstrap.yml
# bootstrap.yml #指定注册中心地址 eureka: client: serviceUrl: defaultZone: http://localhost:7001/eureka/ #服务的名称 spring: application: name: order-service #指定从哪个配置中心读取 cloud: config: discovery: service-id: CONFIG-SERVER enabled: true profile: dev #建议用lable去区分环境,默认是lable是master分支 #label: test添加一个测试类
@RestController public class TestController { @Value("${test}") private String test; @GetMapping("test") public String test(){ return test; } }启动顺序:注册中心-> 配置中心->对应的服务
通过配置中心访问:http://localhost:9010/order-service-dev.yml
启动order-servcie:
访问:http://localhost:8090/test
现在有一个问题:在git上修改配置文件后,order-service必须重启才能读到修改的内容
配置中心读到的也是2
但是order-service的还是1
引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>增加配置:
management: endpoints: web: exposure: include: "*"需要刷新配置的地方,增加注解 @RefreshScope
@RefreshScope @RestController public class TestController { @Value("${test}") private String test; @GetMapping("test") public String test(){ return test; } }post 方式发送http://localhost:8090/actuator/refresh刷新
Spring Cloud Bus消息总线,支持RabbitMQ 和Kafka
引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>添加配置
spring: rabbitmq: host: 192.168.0.71 port: 5672 username: guest password: guest management: endpoints: web: exposure: include: "bus-refresh"依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-bus-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>配置文件
#指定注册中心地址 eureka: client: serviceUrl: defaultZone: http://localhost:7001/eureka/ #服务的名称 spring: rabbitmq: host: 192.168.0.71 port: 5672 username: guest password: guest application: name: order-service # 允许消息跟踪 cloud: bus: trace: enabled: true #指定从哪个配置中心读取 config: discovery: service-id: CONFIG-SERVER enabled: true profile: dev #建议用lable去区分环境,默认是lable是master分支 #label: test management: endpoints: web: exposure: include: "*"在需要刷新的类上加上@RefreshScope
@RefreshScope @RestController public class TestController { @Value("${test}") private String test; @GetMapping("test") public String test(){ return test; } }