Spring Boot雲組態用戶端


某些應用程式可能需要更改組態屬性,開發人員可能需要將其關閉或重新啟動應用程式才能執行此操作。 但是,這可能會導致生產停機並需要重新啟動應用程式。 Spring Cloud Configuration Server允許開發人員載入新的組態屬性,而無需重新啟動應用程式,不需要任何停機。

使用Spring Cloud組態服務

首先,從 https://start.spring.io/ 下載Spring Boot專案,然後選擇Spring Cloud Config Client依賴項。 現在,在構建組態檔案中新增Spring Cloud Starter Config依賴項。

Maven使用者可以將以下依賴項新增到pom.xml 檔案中。

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

Gradle使用者可以將以下依賴項新增到build.gradle 檔案中。

compile('org.springframework.cloud:spring-cloud-starter-config')

現在,需要將@RefreshScope批注新增到主Spring Boot應用程式中。 @RefreshScope注釋用於從Config伺服器載入組態屬性值。

package com.example.configclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;

@SpringBootApplication
@RefreshScope
public class ConfigclientApplication {
   public static void main(String[] args) {
      SpringApplication.run(ConfigclientApplication.class, args);
   }
}

現在,在application.properties 檔案中新增組態伺服器URL並提供應用程式名稱。

- 在啟動config用戶端應用程式之前,應執行http://localhost:8888組態伺服器。

spring.application.name = config-client
spring.cloud.config.uri = http://localhost:8888

編寫簡單REST端點以從組態伺服器讀取歡迎訊息的程式碼如下 -

package com.example.configclient;

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;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RefreshScope
@RestController
public class ConfigclientApplication {
   @Value("${welcome.message}")
   String welcomeText;

   public static void main(String[] args) {
      SpringApplication.run(ConfigclientApplication.class, args);
   }
   @RequestMapping(value = "/")
   public String welcomeText() {
      return welcomeText;
   }
}

建立可執行的JAR檔案,並使用以下Maven或Gradle命令執行Spring Boot應用程式 -

對於Maven,可以使用下面命令 -

mvn clean install

在「BUILD SUCCESS」之後,可以在target目錄下找到JAR檔案。

對於Gradle,可以使用下面命令 -

gradle clean build

在構建顯示「BUILD SUCCESSFUL」之後,可在build/libs目錄下找到JAR檔案。

現在,使用此處顯示的命令執行JAR檔案:

java –jar <JARFILE>

現在,應用程式已在Tomcat埠8080上啟動。

在登入控制台視窗中看到; config-client應用程式從https://localhost:8888獲取組態:

2017-12-08 12:41:57.682  INFO 1104 --- [           
   main] c.c.c.ConfigServicePropertySourceLocator : 
   Fetching config from server at: http://localhost:8888

現在存取URL:http://localhost:8080/ ,程式將從組態伺服器載入歡迎訊息。

現在,轉到組態伺服器上的屬性值並點選執行器端點 POST URL => http://localhost:8080/refresh並在URL=> http://localhost:8080/中檢視新組態屬性值。