前提:构建一个服务注册中心,可参考:Spring Cloud (一)、搭建服务注册中心
构建一个配置中心Config Server,可参考:Spring Cloud(十六)、通过Spring Cloud Config构建配置中心
构建一个客户端映射Config Client,可参考:Spring Cloud (十七)、在微服务中获取配置中心的配置——客户端配置映射
将Config Server注册到服务中心,并通过服务发现来访问Config Server并获取Git仓库中的配置信息。
服务端配置:我们在已有的Config Server项目中进行改造。
1、在config-server的pom.xml中增加spring-cloud-starter-netflix-eureka-client依赖,以实现将分布式配置中心加入Eureka的服务治理体系中。
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
2、在application.properties中配置参数eureka.client.service-url.defaultZone以指定服务注册中心的位置,内容如下:
spring.application.name=config-server
server.port=7001
#配置服务注册中心
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/
#Git仓库的位置
spring.cloud.config.server.git.uri=https://github.com/hedanning/SpringCloudConfigLearn
#仓库路径下的相对搜索位置
spring.cloud.config.server.git.search-paths=spring_cloud_in_action/config-repo
#访问Git仓库的用户名
spring.cloud.config.server.git.username=username
#访问Git仓库的密码
spring.cloud.config.server.git.password=password
3、在应用主类上新增@EnableDiscoveryClient注解,将config-server注册到服务中心。
@EnableDiscoveryClient
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
客户端配置:我们在已有的Config Client项目中进行改造。
1、在config-client的pom.xml中新增spring-cloud-starter-netflix-eureka-client依赖,以实现客户端发现config-server服务:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
2、在bootstrap.properties中配置以下内容:
#对应配置文件规则中的{application}部分
spring.application.name=hdnspace
#对应配置文件规则中的{propfile}部分
spring.cloud.config.profile=dev
#对应配置文件规则中的{label}部分
spring.cloud.config.label=master
#配置中心config-server的地址
#spring.cloud.config.uri=http://localhost:7001/server.port=7002
#配置服务注册中心
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/
#开启通过服务来访问Config Sever的功能
spring.cloud.config.discovery.enabled=true
#指定Config Server注册的服务名
spring.cloud.config.discovery.service-id=config-server
3、在应用主类上添加@EnableDiscoveryClient注解,用来发现config-server服务,用来加载应用配置:
@EnableDiscoveryClient
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
--------------------------------------测试验证-----------------------------------
分别启动注册中心eureka-server、配置中心config-server、客户端映射config-client;访问http://localhost:1111/eureka/,如下:
访问我们config-client项目中/from接口:http://localhost:7002/from,得到以下内容:
返回了Git仓库中hdnspace-dev.properties文件中配置的from属性内容。