某些应用程序可能需要可能需要更改的配置属性,开发人员可能需要将其关闭或重新启动应用程序才能执行此操作.但是,这可能会导致生产停机并需要重新启动应用程序. Spring Cloud Configuration Server允许开发人员加载新的配置属性,而无需重新启动应用程序,也不会出现任何停机.
首先,从 https://start.spring.io/下载Spring Boot项目并选择Spring云配置客户端依赖项.现在,在构建配置文件中添加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并提供应用程序名称.
注意 : 在启动配置客户端应用程序之前,应该运行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上启动,如下所示 :
您可以在控制台窗口中看到日志; 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/
中查看新配置属性值