某些應用程式可能需要更改配置屬性,開發人員可能需要將其關閉或重新啟動應用程式才能執行此操作。 但是,這可能會導致生產停機並需要重新啟動應用程式。 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/
中查看新配置屬性值。