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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章