java微服務的統一配置中心


為了更好的管理應用的配置,也為了不用每次更改配置都重啟應用,我們可以使用配置中心

關於eureka的服務注冊和rabbitMQ的安裝使用(自動更新配置需要用到rabbitMQ)這里不贅述,只關注配置中心的內容

我們需要引入關鍵的包是這三個

<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>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

需要在啟動類加上@EnableConfigServer注解,這里有個busRefresh2方法需要講下,其實這里有個坑,如果在github的webhook直接訪問/actuator/bus-refresh是有json轉換錯誤的,

因為github觸發webhook的時候會帶一大串字符,就是這段字符引發json轉換錯誤,所以我們在這里包裝下/actuator/bus-refresh

@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
@RestController
public class ConfigApplication {
    @PostMapping("/actuator/bus-refresh2")
    @ResponseBody
    public Object busRefresh2(HttpServletRequest request, @RequestBody(required = false) String s) {
        System.out.println(s);
        return new ModelAndView("/actuator/bus-refresh");
    }
    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class, args);
    }

}

然后在配置文件上加上這些內容,主要是配置github上的配置文件的路徑,配置rabbitMQ和啟用bus-refresh端點。

spring:
  application:
    name: config
  cloud:
    config:
      server:
        git:
          uri: https://github.com/skychmz/config.git
          username: skychmz
          password: xxxxxxx
  rabbitmq:
    host: localhost
    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.cloud</groupId>
            <artifactId>spring-cloud-config-client</artifactId>
</dependency>

在yml配置文件上加上如下配置,主要是開啟配置中心,我們的配置中心的服務名是CONFIG

spring:
  cloud:
    config:
      discovery:
        enabled: true
        service-id: CONFIG

把該服務的配置文件放到github,注意eureka的配置還是要放本地的,因為服務啟動的時候要先訪問eureka才會找到CONFIG服務

 

 

 配置github的webhooks,這里我用的是內網穿透的地址

 

在需要刷新配置的地方加上@RefreshScope注解,這樣就完成了。當我們更改github上的配置文件之后,GitHub就會觸發webhook從而自動刷新配置。

最后提一下如果zuul網關服務也需要自動刷新配置的話可以在啟動類加一個方法返回一個ZuulProperties(),當然還要加上@RefreshScope注解

@SpringBootApplication
@EnableZuulProxy
public class ApiGatewayApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
    
    @ConfigurationProperties("zuul")
    @RefreshScope
    public ZuulProperties zuulProperties() {
        return new ZuulProperties();
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM