Spring Cloud客户端配置,某些应用程序可能需要更改配置属性,开发人员可能需要关闭它们或重新启动应用程序才能执行此操作。但是,这可能会导致生产停机并需要重新启动应用程序。Spring Cloud 服务端配置允许开发人员加载新的配置属性,而无需重新启动应用程序,也无需任何停机时间。

使用 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 注解用于从配置服务器加载配置属性值。

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/欢迎消息从配置服务器加载。

spring_cloud_config_server

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

Spring Cloud客户端配置 推荐

Node.js中的module.exports和exports简介

影视中心