spring-cloud-config client 配置客户端

本贴最后更新于 2045 天前,其中的信息可能已经时异事殊

Maven 导入

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

1.增加 bootstrap.properties

# 配置服务器url
spring.cloud.config.uri = http://localhost:9090/
# 远程地址properties 前缀 [ws.properties]
spring.cloud.config.name = ws
# 远程地址properties -后缀 [ws-dev.properties]
spring.cloud.config.profile = default
# git仓局分支
spring.cloud.config.label = master

2.修改 application.properties

spring.application.name = client
#springcloud-Finchley.SR1版本中,意思是:使用包含暴露的服务端口
management.endpoints.web.exposure.include = env,refresh 

3.修改 Application.java

package com.gupao.springcloudclientconfig;

import org.omg.CORBA.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SpringCloudClientConfigApplication {

	@Value("${my.name}")
	public String name;
	public static void main(String[] args) {
		SpringApplication.run(SpringCloudClientConfigApplication.class, args);
	}

	@GetMapping("/config")
	public String getConfig(){
		return name;
	}
}

4.测试

http://localhost:8080/config,成功显示 default.

5.修改配置生效

http://localhost:8080/actuator/env -> search ws.properties -> 通过 POST 方法请求 localhost:8080/actuator/refresh 刷新配置文件 , 发现已变更则成功!

6.修改后刷新 bean

在需要修改的类中增加 @RefreshScope 注解,就会开启刷新 @Value 的值

  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    940 引用 • 1458 回帖 • 156 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...