spring cloud config提供一个服务端和客户端去提供可扩展的配置服务中心,我们可以将配置服务中心集中配置和管理各个模块环境的配置文件。配置服务中心采用Git/svn方式存储配置文件,因此我们很容易部署修改,有助于对环境配置版本进行管理。
创建一个demo微服务架构,在demo中创建一个demo-config模块作为configserver配置服务中心。demo-config的pom文件需要引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
配置服务中心注册到eureka需要eureka起步依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
demo-config配置application.yml文件如下:
server:
port: 8888 #端口号
spring:
application:
name: demo-config #模块名称
cloud:
config:
server:
git:
uri: https://github.com/forezp/SpringcloudConfig/ #配置文件存储地址(必须有)
username: wuzhengjun #账号
password: wuzhengjun #密码
search-paths: /** #存储文件配置路由
default-label: master #
#注册到eureka
eureka:
instance:
prefer-ip-address: true # 注册服务的时候使用服务的ip地址
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:7258/eureka/
DemoConfigApplication启动类添加@EnableConfigServer和@EnableEurekaClient注解,其他消费服务注册模块用@EnableDiscoverClient即可注册,这里如果@EnableDiscoverClient不能注册成功的话就用@EnableEurekaClient
到这里配置中心服务基本完成,下面再写一个客户端模块,config-client
引入依赖如下:
bootstrap.yml配置文件如下
server:
port: 8881
spring:
application:
name: config-client
cloud:
config:
label: master
profile: dev
discovery: #这里和用URI是一样的
enabled: true
service-id: demo-config
eureka:
instance:
prefer-ip-address: true # 注册服务的时候使用服务的ip地址
client:
service-url:
defaultZone: http://localhost:7258/eureka/
启动类配置成为controller来进行测试
测试结果: