微服务搭建Spring Cloud配置中心【客户端】

深藏阁楼爱情的钟 2023-07-03 02:42 16阅读 0赞

spring boot版本:2.1.10.RELEASE
spring cloud版本:Greenwich.SR4

微服务搭建Spring Cloud配置中心【服务端】

添加依赖

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>
  9. <!--配置中心客户端依赖-->
  10. <dependency>
  11. <groupId>org.springframework.cloud</groupId>
  12. <artifactId>spring-cloud-starter-config</artifactId>
  13. </dependency>

修改启动类

相较于 配置中心服务端,少了 @EnableConfigServer 注解

  1. package com.ebook.config;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  5. /**
  6. * @author:JZo
  7. * @date:2020/1/11
  8. */
  9. @SpringBootApplication
  10. //配置中心需客户端添加 @EnableEurekaClient
  11. @EnableEurekaClient
  12. public class ConfigClientApplication {
  13. public static void main(String[] args) {
  14. SpringApplication.run(ConfigClientApplication.class, args);
  15. }
  16. }

配置文件

配置中心服务端的配置是在application.properties中修改的,而客户端的配置是在 bootstrap.properties 中修改的。

  1. spring.application.name=config-client
  2. server.port=9101
  3. #配置注册中心,此配置在配置中心服务端中也需要配置
  4. eureka.client.service-url.defaultZone=http://192.168.xxx.xxx:1000/eureka/,http://192.168.xxx.xxx:1001/eureka/
  5. eureka.instance.prefer-ip-address=true
  6. eureka.instance.hostname=ebook-config-client
  7. #默认false,这里设置true,表示开启读取配置中心的配置
  8. spring.cloud.config.discovery.enabled=true
  9. #对应eureka中的配置中心serviceId,默认是configserver
  10. spring.cloud.config.discovery.serviceId=ebook-config-server
  11. #指定应用名,即配置文件的{application}部分,若客户端的spring.application.name与配置文件的{application}部分相同则可不配置此项
  12. #spring.cloud.config.name=config-client
  13. #指定环境
  14. spring.cloud.config.profile=dev
  15. #git标签
  16. spring.cloud.config.label=master

其中需要注意的配置是 spring.cloud.config.name,若客户端的spring.application.name 与配置文件的 {application} 部分相同,则此配置可以省略,否则需要配置。

之后在客户端中就可以使用 @Value 注解注入配置了。

刷新配置

当配置中心的服务端和客户端都启动后,修改git仓库中的配置文件后,访问 http://127.0.0.1:9100/config-client/dev 查看服务端的配置文件是修改后的,但是客户端的却没有。

要想客户端配置动态改变需要以下4步:

(1)添加依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>

(2)添加配置

  1. #开启和暴露所有端点
  2. management.endpoints.web.exposure.include=*

在spring boot 1.x中用 management.security.enabled=false 来关闭权限拦截,不过在spring boot 2.x中已经被废弃。

(3)添加注解

配置一般都是使用 @Value 注解注入配置,因此也被注入到bean中了,所以需要在类上添加 @RefreshScope 注解来动态刷新bean。

所在包

  1. org.springframework.cloud.context.config.annotation.RefreshScope

(4)发送POST请求

用POST请求 http://127.0.0.1:9101/actuator/refresh 刷新即可。

在spring boot 1.x 中 访问 http://127.0.0.1:9101/refresh

发表评论

表情:
评论列表 (有 0 条评论,16人围观)

还没有评论,来说两句吧...

相关阅读