Spring Boot - 云配置客户端


某些应用程序可能需要可能需要更改的配置属性,开发人员可能需要将其关闭或重新启动应用程序才能执行此操作。但是,这可能会导致生产停机并需要重新启动应用程序。Spring Cloud Configuration Server允许开发人员加载新的配置属性,而无需重新启动应用程序,也不会出现任何停机。

使用Spring Cloud Configuration Server

首先,从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”之后,您可以在目标目录下找到JAR文件。

对于Gradle,您可以使用下面显示的命令

gradle clean build

在“BUILD SUCCESSFUL”之后,您可以在build/libs目录下找到JAR文件。

现在,使用此处显示的命令运行JAR文件:

java –jar <JARFILE>

现在,应用程序已在Tomcat端口8080上启动,如下所示

应用程序已在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/welcome消息。

从配置服务器加载

现在,转到配置服务器上的属性值并点击执行器Endpoint POST URL http://localhost:8080/refresh并在URL http://localhost:8080/中查看新配置属性值