快速搭建微服务-配置中心
配置中心是用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,分为服务端和客户端两个部分。配置中心的服务端是一个独立的微服务应用,用来连接配置仓库并为客户端提供获取配置信息的接口。配置中心的客户端可以是微服务架构中的各个微服务应用或基础服务,客户端在启动的时候调用服务端接口获取并加载配置信息。Spring Cloud Config实现的配置中心默认采用Git仓库来存储配置信息。本文简单介绍如何在微服务架构中使用Spring Cloud Config作为配置中心。
配置仓库
在Git代码托管平台上创建一个新的仓库/项目,并将配置文件上传至Git仓库的根目录下。
配置文件的命名格式为:[serviceId]-[profile].yml
当profile为 “default” 默认配置时,可以忽略。
配置文件的格式可以是yml,也可以是properties,推荐可读性更好的yml格式。配置文件的内容填写相应的微服务的外部配置信息,例如 api-gateway 网关服务的配置文件 api-gateway.yml 中配置了jwt的相关参数和不同客户端的jwt过期及刷新时间,限流的开关、开启限流的内存阈值、需要限流的服务名及每秒限制的请求数,跨域相关配置。具体配置信息如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
   | jwt:   secret: yupaits   auth-header-name: Authorization   expired-config:     PC_WEB:       expired-in-seconds: 1800       refresh-ttl-seconds: 864000     MOBILE_H5:       expired-in-seconds:       refresh-ttl-seconds:     MOBILE_APP:       expired-in-seconds:       refresh-ttl-seconds:     MOBILE_WECHAT:       expired-in-seconds:       refresh-ttl-seconds:     TEST:       expired-in-seconds: 10       refresh-ttl-seconds: 30
  rate-limit:   enabled: true   memory-size-kb: 300000   limits:     service-order: 300
  cors:   origins: "*"   methods: GET, POST, PUT, DELETE, PATCH   max-age: 600   allowed-headers: Origin, X-Requested-With, Content-Type, Accept, Authorization   exposed-headers: Authorization
   | 
 
服务端
1 2 3 4
   | <dependency>     <groupId>org.springframework.cloud</groupId>     <artifactId>spring-cloud-config-server</artifactId> </dependency>
   | 
 
1 2 3 4 5 6 7 8
   | spring:   cloud:     config:       server:         git:           uri: https://gitee.com/[git仓库路径]           username: [git仓库访问用户名]           password: [git仓库访问密码]
   | 
 
客户端
1 2 3 4
   | <dependency>     <groupId>org.springframework.cloud</groupId>     <artifactId>spring-cloud-starter-config</artifactId> </dependency>
   | 
 
1 2 3 4 5 6
   | spring:   cloud:     config:       uri: http://localhost:9000           profile: default                     label: master                 
   | 
 
 因为从配置中心加载的配置要先于 application.yml 并且 bootstrap.yml 的配置加载会先于 application.yml,所以客户端中的配置中心的相关配置需要写在 bootstrap.yml 文件中。