Spring Cloud Config 与 Bus 的基本使用

1. Spring Config 配置

Spring Boot: 2.2.6.RELEASE
Spring Cloud: Hoxton.SR4

1.1 服务端

导包

<!-- Config 集中配置中 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

application.yml 配置文件

# 端口号
server:
  port: 12000
spring:
  application:
    name: springCloud-bus
  # 码云上传配置文件的 URI
  cloud:
    config:
      server:
        git:
          # 指定是否开启启动时直接从 git 获取配置.
          clone-on-start: true
          # 指定是否强制从远程仓库拉取.
          force-pull: true
          uri: https://gitee.com/xxx/xxx.git
          username: username
          password: password
          basedir: D:/a/b/c
    bus:
      enabled: true
      #开启跟踪总线
      trace:
        enabled: true
      ack:
        enabled: true
  rabbitmq:
    host: localhost
    username: guest
    password: guest
# 暴露出发总线的地址
management:
  server:
    port: 12200
  endpoints:
    web:
      exposure:
        # actuator 监控对外暴露 bus-refresh 端点, 默认情况下, 只会暴露 health 和 info 端点
        include: "*"

配置类中添加 @EnableConfigServer 注解

package com.springCloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@EnableConfigServer
@SpringBootApplication
public class BusApplication {

    public static void main(String[] args) {
        SpringApplication.run(BusApplication.class, args);
    }

}

1.2 客户端

导包

<!-- Config 配置中心的客户端 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

bootstrap.yml 配置文件

spring:
  cloud:
    config:
      name: user
      profile: dev
      label: master
      uri: http://localhost:12000

1.3 访问

RabbitMQ 用于传递文件信息. 访问 RabbitMQ 可以看见 Queues 会发现多出来两个.

访问 http://localhost:12000/user-dev.yml 会显示 客户端 的配置文件里的内容.
12000 端口号在 服务端 配置的.

http://localhost:12000/user-dev.yml

2. Spring Bus 配置

客户端 添加内容

<!-- 监听配置文件是否改变 -->
<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>

在配置文件内添加 注释

@EnableFeignClients
@EnableDiscoveryClient

3. 远程配置文件

改变远程配置文件后, 在不重新启动项目的情况下, 使其配置文件生效.

运用 post 方法访问 http://localhost:12200/actuator/bus-refresh 路径.
12200 端口号在 服务端 配置的.

http://localhost:12200/actuator/bus-refresh

猜你喜欢

转载自blog.csdn.net/YKenan/article/details/106216109