SpringCloud Config分布式配置中心
是什么?
- Config Service是一个支持横向扩展集中式管理的分布式配置中心的服务器,管理分布式下各个服务的相关配置,默认使用git存储,也可以使用SVN,本地存储管理
- Config Client是Config Service的客户端,用来拉取Config Service中对应的配置文件信息,提供给
作用
- 同一配置的管理
入门案例实现
- 创建本地文件夹,存放3个环境userservice-dev.yml,userservice-pro.yml,userservice-test.yml文件,分别放入测试内容
server: port: 8081 spring: application: name: user-service datasource: url: jdbc:mysql://192.168.200.129:3306/cloud_user username: root password: root driver-class-name: com.mysql.jdbc.Driver mybatis: type-aliases-package: com.dlw.sh.user.pojo configuration: map-underscore-to-camel-case: true logging: level: cn.dlw: debug eureka: client: service-url: # EurekaServer地址 defaultZone: http://127.0.0.1:10086/eureka/ instance: ip-address: 127.0.0.1 # ip地址 prefer-ip-address: true # 更倾向于使用ip,而不是host名 instance-id: ${eureka.instance.ip-address}:${server.port} # 自定义实例的id test: redis: host: localhost port: 6379
- 在gitee中创建一个仓库:config-test
- 将yml文件push到远程仓库
cd config-test git init git add . git commit -m "add userservice-dev.yml,gatewayservice-pro.yml,conusmerservice-test.yml" git remote add origin https://gitee.com/dlw/config-test.git git pull git pull origin master git pull origin master --allow-unrelated-histories git push -u origin master
- 搭建ConfigService-导入依赖
<dependencies> <!--eureka依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!--config-server依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> eureka-client依赖:因为ConfigServer也是一个微服务,需要注册到eureka config-serverr依赖:包含ConfigServer的全部功能
- 搭建ConfigService-添加配置文件
server: port: 12580 spring: application: name: config-server cloud: config: server: git: uri: https://gitee.com/chuanshuo/config-test.git # 需要拉取配置的Git仓库地址 # username: # password: eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka/ # eureka地址
- 启动类
@SpringBootApplication @EnableConfigServer //开启ConfigServer的功能。 @EnableDiscoveryClient public class ConfigServerApplication { public static void main(String[] args) { SpringApplication.run(ConfigServerApplication.class, args); } }
- 测试
- 访问eureka注册中心页面,查看config-service服务注册情况
- http://127.0.0.1:12580/userservice-dev.yml查看配置信息
eureka: client: service-url: defaultZone: http://127.0.0.1:10086/eureka/ instance: instance-id: 127.0.0.1:8081 ip-address: 127.0.0.1 prefer-ip-address: true logging: level: cn: dlw: debug mybatis: configuration: map-underscore-to-camel-case: true type-aliases-package: com.dlw.sh.user.pojo server: port: 8081 spring: application: name: user-service datasource: driver-class-name: com.mysql.jdbc.Driver password: root url: jdbc:mysql://192.168.200.129:3306/cloud_user username: root test: redis: host: localhost port: 6379