1 什么是配置中心

1.1 配置中心概述

  • 对于传统的单体应用而言,常使用配置文件来管理所有配置,比如SpringBoot的application.yml文件,但是在微服务架构中全部手动修改的话很麻烦而且不易维护。
  • 微服务的配置管理一般有以下需求:
    • Spring Cloud Config(不推荐) - 图1集中配置管理,一个微服务架构中可能有成百上千个微服务,所以集中配置管理很重要。
    • Spring Cloud Config(不推荐) - 图2不同环境不同配置:比如数据源配置在不同环境(开发、测试、生产)中是不同的。
    • Spring Cloud Config(不推荐) - 图3运行期间可动态调整。比如可以根据各个微服务的负载情况,动态调整数据源连接池的大小等。
    • Spring Cloud Config(不推荐) - 图4配置修改后可以自动更新。比如配置内容发生改变,微服务可以自动更新配置。
  • 综上所述,对于微服务架构来说,一套统一的、通用的管理配置机制是不可缺少的重要组成部分。常见的做法就是通过配置服务器进行管理。

1.2 常见的配置中心

1.2.1 Spring Cloud Config

  • Spring Cloud Config是分布式系统中的外部配置提供服务器和客户端支持。

1.2.2 Apollo(阿波罗)

  • Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性,适用于微服务配置管理场景。

1.2.3 Nacos

  • Nacos 致力于帮助您发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据及流量管理。
  • Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。 Nacos 是构建以“服务”为中心的现代应用架构 (例如微服务范式、云原生范式) 的服务基础设施。

2 Spring Cloud Config简介

  • Spring Cloud Config项目是一个解决分布式系统的配置解决方案。它包含了Client和Server两个部分,Server提供配置文件的存储,以接口的形式将配置文件的内容提供出去;Client通过接口获取数据,并依据此数据初始化自己的应用。

Spring Cloud Config简介.png

  • Spring Cloud Config为分布式系统的外部配置提供服务器和客户端支持。使用Config Server,您可以为所有环境中的应用程序管理其外部属性。它非常适合Spring应用,也可以使用在其他语言的应用上。随着应用程序通过从开发到测试和生产的部署流程,您可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切。服务器存储后端的默认使用使用Git,因此他轻松的支持标签版本的配置环境以及可以访问用于管理内容的各种工具。
  • Spring Cloud Config服务端的特性:
    • Spring Cloud Config(不推荐) - 图6Http,为外部配置提供基于资源的API(键值对或者等价的YAML内容)。
    • Spring Cloud Config(不推荐) - 图7属性值的加密和解密(对称加密和非对称加密)。
    • Spring Cloud Config(不推荐) - 图8通过使用@EnableConfigServer在Spring Boot应用中非常简单的嵌入。
  • Spring Cloud Config客户端的 特性:
    • Spring Cloud Config(不推荐) - 图9绑定Config服务端,并使用远程的属性源初始化Spring环境。
    • Spring Cloud Config(不推荐) - 图10属性值的加密和解密(对称加密和非对称加密)。

3 Spring Cloud Config入门

3.1 准备工作

  • Config Server是一个可横向扩展、集中式的配置服务器,它用于集中管理应用程序各个环境下的配置,默认使用Git存储配置文件内容,也可以使用SVN存储(但是又有谁使用SVN呢?)或者是本地文件存储。
  • 在码云上创建仓库:

在码云上创建仓库.png

  • 创建product-dev.ymlproduct-prod.yml文件上传到创建的仓库上。
  • product-dev.yml:
  1. server:
  2. port: 9008 # 微服务的端口号
  3. spring:
  4. application:
  5. name: service-product # 微服务的名称
  6. datasource:
  7. url: jdbc:mysql://192.168.1.57:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. username: root
  10. password: 123456
  11. jpa:
  12. generate-ddl: true
  13. show-sql: true
  14. open-in-view: true
  15. database: mysql
  16. # 配置 eureka
  17. eureka:
  18. instance:
  19. # 主机名称:服务名称修改,其实就是向eureka server中注册的实例id
  20. instance-id: service-product-dev:${server.port}
  21. # 显示IP信息
  22. prefer-ip-address: true
  23. client:
  24. service-url: # 此处修改为 Eureka Server的集群地址
  25. defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  • product-prod.yml:
  1. server:
  2. port: 9009 # 微服务的端口号
  3. spring:
  4. application:
  5. name: service-product # 微服务的名称
  6. datasource:
  7. url: jdbc:mysql://192.168.1.57:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
  8. driver-class-name: com.mysql.cj.jdbc.Driver
  9. username: root
  10. password: 123456
  11. jpa:
  12. generate-ddl: true
  13. show-sql: true
  14. open-in-view: true
  15. database: mysql
  16. # 配置 eureka
  17. eureka:
  18. instance:
  19. # 主机名称:服务名称修改,其实就是向eureka server中注册的实例id
  20. instance-id: service-product-prod:${server.port}
  21. # 显示IP信息
  22. prefer-ip-address: true
  23. client:
  24. service-url: # 此处修改为 Eureka Server的集群地址
  25. defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

文件命名规则:

  • {application}-{profile}.yml
  • {application}-{profile}.properties
  • application为应用名称,profile指的是开发环境(用于区分开发环境、测试环境和生产环境等)

3.2 搭建服务端程序

3.2.1 新建模块并导入相关依赖

  • 修改部分:
  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-config-server</artifactId>
  4. </dependency>
  • 完整部分:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring_cloud_demo</artifactId>
  7. <groupId>org.sunxiaping</groupId>
  8. <version>1.0</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>config_server9010</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-config-server</artifactId>
  16. </dependency>
  17. <!-- 导入Eureka Client对应的坐标 -->
  18. <dependency>
  19. <groupId>org.springframework.cloud</groupId>
  20. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  21. </dependency>
  22. </dependencies>
  23. </project>

3.2.2 配置application.yml

  1. server:
  2. port: 9010
  3. spring:
  4. application:
  5. name: config-server
  6. cloud:
  7. config:
  8. server:
  9. git:
  10. # git服务地址
  11. uri: https://gitee.com/AncientFairy/config-repo.git
  12. # 配置git的用户名
  13. username:
  14. # 配置git的密码
  15. password:
  16. search-paths:
  17. - config-repo
  18. # 分支
  19. label: master
  20. # 配置 eureka
  21. eureka:
  22. instance:
  23. # 主机名称:服务名称修改,其实就是向eureka server中注册的实例id
  24. instance-id: config-server:${server.port}
  25. # 显示IP信息
  26. prefer-ip-address: true
  27. client:
  28. service-url: # 此处修改为 Eureka Server的集群地址
  29. defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

3.2.3 配置启动类

  1. package com.sunxiaping.config;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.config.server.EnableConfigServer;
  5. /**
  6. * @author 许大仙
  7. * @version 1.0
  8. * @since 2020-10-09 16:48
  9. */
  10. @SpringBootApplication
  11. @EnableConfigServer //开启配置中心功能
  12. public class ConfigServer9010Application {
  13. public static void main(String[] args) {
  14. SpringApplication.run(ConfigServer9010Application.class, args);
  15. }
  16. }

3.2.4 测试

服务器端程序测试.png

配置读取规则(label:分支,name:服务名,profile:环境): 配置读取规则.png

3.3 搭建客户端程序

3.3.1 新建模块并导入相关依赖

  • 修改部分:
  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-config</artifactId>
  4. </dependency>
  • 完整部分:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://maven.apache.org/POM/4.0.0"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>spring_cloud_demo</artifactId>
  7. <groupId>org.sunxiaping</groupId>
  8. <version>1.0</version>
  9. </parent>
  10. <modelVersion>4.0.0</modelVersion>
  11. <artifactId>config_client9011</artifactId>
  12. <dependencies>
  13. <dependency>
  14. <groupId>org.springframework.cloud</groupId>
  15. <artifactId>spring-cloud-starter-config</artifactId>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-data-jpa</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>mysql</groupId>
  31. <artifactId>mysql-connector-java</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-actuator</artifactId>
  36. </dependency>
  37. </dependencies>
  38. </project>

3.3.2 配置bootstrap.yml

  • bootstrap.yml是系统级别的资源配置项,application.yml是用户级别的资源配置项。
  • Spring Cloud会创建一个“Boostrap Context”,作为Spring应用的“Application Context”的父上下文。初始化的时候,“Boostrap Context”负载从外部源加载配置属性并解析配置。这两个上下文共享一个从外部获取的“Environment”。
  • “Boostrap”属性有高优先级,默认情况下,不会覆盖本地配置项。“Bootstrap Context”和“Application Context”有着不同的约定,所以新增了一个“bootstrap.yml”,保证“BootStrap Context”和“Application Context”配置的分离。
  • 要将Client模块下的application.yml改为bootstrap.yml,很关键。因为bootstrap.yml比application.yml优先加载。
  1. spring:
  2. cloud:
  3. config:
  4. name: product # 应用名称,需要对应git中配置文件名称的前半部分
  5. profile: prod # 开发环境,需要对应git中配置文件名称的后半部分
  6. label: master # 分支名称
  7. uri: http://localhost:9010 # config-server的请求地址

3.3.3 实体类

  1. package com.sunxiaping.product.domain;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Getter;
  4. import lombok.NoArgsConstructor;
  5. import lombok.Setter;
  6. import javax.persistence.*;
  7. import java.io.Serializable;
  8. import java.math.BigDecimal;
  9. @Setter
  10. @Getter
  11. @AllArgsConstructor
  12. @NoArgsConstructor
  13. @Entity
  14. @Table(name = "tb_product")
  15. public class Product implements Serializable {
  16. @Id
  17. @GeneratedValue(strategy = GenerationType.IDENTITY)
  18. private Long id;
  19. @Column(name = "product_name")
  20. private String productName;
  21. @Column(name = "status")
  22. private Integer status;
  23. @Column(name = "price")
  24. private BigDecimal price;
  25. @Column(name = "product_desc")
  26. private String productDesc;
  27. @Column(name = "caption")
  28. private String caption;
  29. @Column(name = "inventory")
  30. private String inventory;
  31. }

3.3.4 Dao层

  1. package com.sunxiaping.product.dao;
  2. import com.sunxiaping.product.domain.Product;
  3. import org.springframework.data.jpa.repository.JpaRepository;
  4. import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
  5. import org.springframework.stereotype.Repository;
  6. @Repository
  7. public interface ProductRepository extends JpaRepository<Product, Long>, JpaSpecificationExecutor<Product> {
  8. }

3.3.5 Service层

  • ProductService.java
  1. package com.sunxiaping.product.service;
  2. import com.sunxiaping.product.domain.Product;
  3. public interface ProductService {
  4. /**
  5. * 根据id查询
  6. *
  7. * @param id
  8. * @return
  9. */
  10. Product findById(Long id);
  11. /**
  12. * 保存
  13. *
  14. * @param product
  15. */
  16. void save(Product product);
  17. /**
  18. * 更新
  19. *
  20. * @param product
  21. */
  22. void update(Product product);
  23. /**
  24. * 删除
  25. *
  26. * @param id
  27. */
  28. void delete(Long id);
  29. }
  • ProductServiceImpl.java
  1. package com.sunxiaping.product.service.impl;
  2. import com.sunxiaping.product.dao.ProductRepository;
  3. import com.sunxiaping.product.domain.Product;
  4. import com.sunxiaping.product.service.ProductService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import javax.transaction.Transactional;
  8. @Service
  9. @Transactional
  10. public class ProductServiceImpl implements ProductService {
  11. @Autowired
  12. private ProductRepository productRepository;
  13. @Override
  14. public Product findById(Long id) {
  15. return this.productRepository.findById(id).orElse(new Product());
  16. }
  17. @Override
  18. public void save(Product product) {
  19. this.productRepository.save(product);
  20. }
  21. @Override
  22. public void update(Product product) {
  23. this.productRepository.save(product);
  24. }
  25. @Override
  26. public void delete(Long id) {
  27. this.productRepository.deleteById(id);
  28. }
  29. }

3.3.6 Controller层

  1. package com.sunxiaping.product.controller;
  2. import com.sunxiaping.product.domain.Product;
  3. import com.sunxiaping.product.service.ProductService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.web.bind.annotation.*;
  7. @RestController
  8. @RequestMapping(value = "/product")
  9. public class ProductController {
  10. @Value("${server.port}")
  11. private String port;
  12. @Value("${spring.cloud.client.ip-address}")
  13. private String ip;
  14. @Autowired
  15. private ProductService productService;
  16. @PostMapping(value = "/save")
  17. public String save(@RequestBody Product product) {
  18. this.productService.save(product);
  19. return "新增成功";
  20. }
  21. @GetMapping(value = "/findById/{id}")
  22. public Product findById(@PathVariable(value = "id") Long id) {
  23. Product product = this.productService.findById(id);
  24. product.setProductName("访问的地址是:" + this.ip + ":" + this.port);
  25. return product;
  26. }
  27. }

3.3.7 配置类

  1. package com.sunxiaping.product;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
  5. @SpringBootApplication
  6. @EnableEurekaClient //开启Eureka Client
  7. public class ProductApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(ProductApplication.class, args);
  10. }
  11. }

3.4 手动刷新

3.4.1 概述

  • 我们已经在客户端获取到了配置中心的值,但是当我们修改git中的值的时候,服务端(Config Server)能实时的获取到最新的值,但是客户端(Config Client)读取的是缓存,无法实时获取最新值。SpringCloud已经为我们解决了这个问题,那就是客户端使用POST去触发refresh,获取最新数据,需要依赖spring-boot-starter-actuator。

手动刷新.jpg

3.4.2 应用示例

  • 导入依赖:
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-actuator</artifactId>
  4. </dependency>
  • 在对应的Controller类中添加@RefreshScope注解:
  1. package com.sunxiaping.product.controller;
  2. import com.sunxiaping.product.domain.Product;
  3. import com.sunxiaping.product.service.ProductService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.beans.factory.annotation.Value;
  6. import org.springframework.cloud.context.config.annotation.RefreshScope;
  7. import org.springframework.web.bind.annotation.*;
  8. @RestController
  9. @RequestMapping(value = "/product")
  10. @RefreshScope //开启动态刷新
  11. public class ProductController {
  12. @Value("${server.port}")
  13. private String port;
  14. @Value("${spring.cloud.client.ip-address}")
  15. private String ip;
  16. @Autowired
  17. private ProductService productService;
  18. @PostMapping(value = "/save")
  19. public String save(@RequestBody Product product) {
  20. this.productService.save(product);
  21. return "新增成功";
  22. }
  23. @GetMapping(value = "/findById/{id}")
  24. public Product findById(@PathVariable(value = "id") Long id) {
  25. Product product = this.productService.findById(id);
  26. product.setProductName("访问的地址是:" + this.ip + ":" + this.port);
  27. return product;
  28. }
  29. }
  • 在application.yml中开放端点配置:
  1. spring:
  2. cloud:
  3. config:
  4. name: product # 应用名称,需要对应git中配置文件名称的前半部分
  5. profile: dev # 开发环境,需要对应git中配置文件名称的后半部分
  6. label: master # 分支名称
  7. uri: http://localhost:9010 # config-server的请求地址
  8. # 暴露监控端点
  9. management:
  10. endpoints:
  11. web:
  12. exposure:
  13. include: '*'
  • 测试:在Git服务器上修改配置之后,需要使用curl -X POST "http://localhost:9008/actuator/refresh"发送请求。

4 配置中心的高可用

4.1 概述

  • 在之前的代码中,客户端都是直接调用配置中心的Server端来获取配置信息。这样就存在了一个问题,客户端和服务端的耦合性太高,如果Server要做集群,客户端只能通过原始的方式来路由,Server端改变IP地址的时候,客户端也需要修改配置,不符合Spring Cloud 服务治理的概念。
  • Spring Cloud提供了这样的解决方案,我们只需要将Server端当做一个服务注册到Eureka中,Client端去Eureka中去获取配置中心Server端的服务即可。

4.2 服务端改造

  • 导入Eureka Client的依赖:
  1. <!-- 导入Eureka Client对应的坐标 -->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  5. </dependency>
  • application.yml
  1. server:
  2. port: 9010
  3. spring:
  4. application:
  5. name: config-server
  6. cloud:
  7. config:
  8. server:
  9. git:
  10. # git服务地址
  11. uri: https://gitee.com/AncientFairy/config-repo.git
  12. # 配置git的用户名
  13. username:
  14. # 配置git的密码
  15. password:
  16. search-paths:
  17. - config-repo
  18. # 分支
  19. label: master
  20. # 配置 eureka
  21. eureka:
  22. instance:
  23. # 主机名称:服务名称修改,其实就是向eureka server中注册的实例id
  24. instance-id: config-server:${server.port}
  25. # 显示IP信息
  26. prefer-ip-address: true
  27. client:
  28. service-url: # 此处修改为 Eureka Server的集群地址
  29. defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

4.3 客户端改造

  • bootstrap.yml:
  1. spring:
  2. cloud:
  3. config:
  4. name: product # 应用名称,需要对应git中配置文件名称的前半部分
  5. profile: dev # 开发环境,需要对应git中配置文件名称的后半部分
  6. label: master # 分支名称
  7. # uri: http://localhost:9010 # config-server的请求地址
  8. discovery: # 服务发现
  9. service-id: config-server
  10. enabled: true # 从Eureka中获取配置信息
  11. # 配置 eureka
  12. eureka:
  13. instance:
  14. # 主机名称:服务名称修改,其实就是向eureka server中注册的实例id
  15. instance-id: service-product-dev:${server.port}
  16. # 显示IP信息
  17. prefer-ip-address: true
  18. client:
  19. service-url: # 此处修改为 Eureka Server的集群地址
  20. defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  21. # 暴露监控端点
  22. management:
  23. endpoints:
  24. web:
  25. exposure:
  26. include: '*'