微服务搭建Spring Cloud配置中心【客户端】
spring boot版本:2.1.10.RELEASE
spring cloud版本:Greenwich.SR4
微服务搭建Spring Cloud配置中心【服务端】
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</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>
修改启动类
相较于 配置中心服务端,少了 @EnableConfigServer
注解
package com.ebook.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @author:JZo
* @date:2020/1/11
*/
@SpringBootApplication
//配置中心需客户端添加 @EnableEurekaClient
@EnableEurekaClient
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
配置文件
配置中心服务端的配置是在application.properties
中修改的,而客户端的配置是在 bootstrap.properties
中修改的。
spring.application.name=config-client
server.port=9101
#配置注册中心,此配置在配置中心服务端中也需要配置
eureka.client.service-url.defaultZone=http://192.168.xxx.xxx:1000/eureka/,http://192.168.xxx.xxx:1001/eureka/
eureka.instance.prefer-ip-address=true
eureka.instance.hostname=ebook-config-client
#默认false,这里设置true,表示开启读取配置中心的配置
spring.cloud.config.discovery.enabled=true
#对应eureka中的配置中心serviceId,默认是configserver
spring.cloud.config.discovery.serviceId=ebook-config-server
#指定应用名,即配置文件的{application}部分,若客户端的spring.application.name与配置文件的{application}部分相同则可不配置此项
#spring.cloud.config.name=config-client
#指定环境
spring.cloud.config.profile=dev
#git标签
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)添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
(2)添加配置
#开启和暴露所有端点
management.endpoints.web.exposure.include=*
在spring boot 1.x中用
management.security.enabled=false
来关闭权限拦截,不过在spring boot 2.x中已经被废弃。
(3)添加注解
配置一般都是使用 @Value
注解注入配置,因此也被注入到bean中了,所以需要在类上添加 @RefreshScope
注解来动态刷新bean。
所在包
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
还没有评论,来说两句吧...