<返回目录     Powered by claud/xia兄

第6课: 配置中心

Spring Cloud Config、Nacos Config、Apollo 统一配置管理

为什么需要配置中心

在微服务架构中,配置管理面临以下挑战:

配置中心核心功能

Spring Cloud Config 实战

Spring Cloud Config 是 Spring Cloud 官方的配置中心解决方案,支持 Git、SVN、本地文件等多种存储方式。

1. Config Server 配置

// pom.xml 依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

// 启动类
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

# application.yml 配置
server:
  port: 8888

spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-org/config-repo
          # 搜索路径
          search-paths: '{application}'
          # 默认分支
          default-label: master
          # 认证信息
          username: your-username
          password: your-password
          # 克隆超时时间
          timeout: 10

2. Config Client 配置

// pom.xml 依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

# bootstrap.yml 配置(优先级高于 application.yml)
spring:
  application:
    name: user-service
  cloud:
    config:
      # Config Server 地址
      uri: http://localhost:8888
      # 环境
      profile: dev
      # 分支
      label: master
      # 快速失败
      fail-fast: true
      # 重试配置
      retry:
        initial-interval: 1000
        max-attempts: 6
        max-interval: 2000

3. Git 仓库配置文件结构

config-repo/
├── application.yml              # 所有服务共享配置
├── application-dev.yml          # 开发环境共享配置
├── application-prod.yml         # 生产环境共享配置
├── user-service.yml             # 用户服务配置
├── user-service-dev.yml         # 用户服务开发环境配置
├── user-service-prod.yml        # 用户服务生产环境配置
├── order-service.yml
└── order-service-dev.yml

# application.yml 示例
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    
logging:
  level:
    root: INFO

# user-service-dev.yml 示例
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/user_db_dev
    username: dev_user
    password: dev_password
    
server:
  port: 8081

4. 动态刷新配置

// pom.xml 添加 actuator 依赖
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

# application.yml 暴露刷新端点
management:
  endpoints:
    web:
      exposure:
        include: refresh,health,info

// 使用 @RefreshScope 注解
@RestController
@RefreshScope  // 支持动态刷新
public class ConfigController {

    @Value("${app.message:默认消息}")
    private String message;

    @Value("${app.version:1.0}")
    private String version;

    @GetMapping("/config")
    public Map<String, String> getConfig() {
        Map<String, String> config = new HashMap<>();
        config.put("message", message);
        config.put("version", version);
        return config;
    }
}

// 刷新配置(POST 请求)
curl -X POST http://localhost:8081/actuator/refresh

Nacos Config 实战

Nacos 是阿里巴巴开源的配置中心,提供了更友好的 Web 界面和更强大的功能。

5. Nacos Config 配置

// pom.xml 依赖
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>2.2.9.RELEASE</version>
</dependency>

# bootstrap.yml 配置
spring:
  application:
    name: user-service
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        # 配置文件格式
        file-extension: yaml
        # 命名空间(环境隔离)
        namespace: dev
        # 分组
        group: DEFAULT_GROUP
        # 共享配置
        shared-configs:
          - data-id: common.yaml
            group: DEFAULT_GROUP
            refresh: true
        # 扩展配置
        extension-configs:
          - data-id: redis.yaml
            group: DEFAULT_GROUP
            refresh: true
          - data-id: mysql.yaml
            group: DEFAULT_GROUP
            refresh: true

6. Nacos 配置管理

// 在 Nacos 控制台创建配置
Data ID: user-service.yaml
Group: DEFAULT_GROUP
配置格式: YAML

配置内容:
server:
  port: 8081

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/user_db
    username: root
    password: password

app:
  message: "Hello from Nacos Config"
  version: "2.0"

// 监听配置变化
@Component
public class ConfigListener {

    @NacosValue(value = "${app.message:默认消息}", autoRefreshed = true)
    private String message;

    @NacosConfigListener(dataId = "user-service.yaml", groupId = "DEFAULT_GROUP")
    public void onConfigChange(String newConfig) {
        System.out.println("配置已更新: " + newConfig);
    }
}

7. 配置加密

// 使用 Jasypt 加密敏感配置
<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot-starter</artifactId>
    <version>3.0.4</version>
</dependency>

# application.yml 配置
jasypt:
  encryptor:
    password: ${JASYPT_PASSWORD}  # 从环境变量获取
    algorithm: PBEWithMD5AndDES

spring:
  datasource:
    # 使用 ENC() 包裹加密内容
    password: ENC(encrypted_password_here)

// 加密工具类
public class EncryptUtil {
    public static void main(String[] args) {
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setPassword("your-secret-key");
        encryptor.setAlgorithm("PBEWithMD5AndDES");
        
        String encrypted = encryptor.encrypt("your-password");
        System.out.println("加密后: " + encrypted);
        
        String decrypted = encryptor.decrypt(encrypted);
        System.out.println("解密后: " + decrypted);
    }
}

8. Apollo 配置中心

// Apollo 是携程开源的配置中心,功能强大
// pom.xml 依赖
<dependency>
    <groupId>com.ctrip.framework.apollo</groupId>
    <artifactId>apollo-client</artifactId>
    <version>1.9.2</version>
</dependency>

# application.properties 配置
app.id=user-service
apollo.meta=http://localhost:8080
apollo.bootstrap.enabled=true
apollo.bootstrap.namespaces=application,database,redis

// 启动类
@SpringBootApplication
@EnableApolloConfig
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

// 使用配置
@Component
public class AppConfig {

    @Value("${app.message:默认消息}")
    private String message;

    @ApolloConfig
    private Config config;

    @ApolloConfigChangeListener
    private void onChange(ConfigChangeEvent changeEvent) {
        for (String key : changeEvent.changedKeys()) {
            ConfigChange change = changeEvent.getChange(key);
            System.out.println(String.format(
                "配置变更 - Key: %s, Old: %s, New: %s",
                key, change.getOldValue(), change.getNewValue()
            ));
        }
    }
}

9. 配置中心高可用

# Config Server 集群配置
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-org/config-repo
          # 多个 Config Server 实例
          clone-on-start: true
          force-pull: true

# Client 配置多个 Config Server
spring:
  cloud:
    config:
      uri: http://config-server1:8888,http://config-server2:8888,http://config-server3:8888
      fail-fast: true
      retry:
        max-attempts: 6

# Nacos 集群配置
spring:
  cloud:
    nacos:
      config:
        server-addr: nacos1:8848,nacos2:8848,nacos3:8848

10. 配置最佳实践

// 1. 配置分层管理
application.yml          # 全局默认配置
application-{env}.yml    # 环境特定配置
{service}.yml            # 服务特定配置
{service}-{env}.yml      # 服务环境配置

// 2. 配置优先级(从高到低)
1. 命令行参数
2. 系统环境变量
3. bootstrap.yml
4. application.yml
5. Config Server 配置

// 3. 配置命名规范
# 使用小写字母和连字符
app.service-name=user-service
app.max-connections=100

# 避免使用驼峰命名
# 错误: app.serviceName
# 正确: app.service-name

// 4. 敏感配置处理
- 使用加密存储
- 使用环境变量
- 使用密钥管理服务(如 Vault)
- 限制配置访问权限
最佳实践:

实践练习

练习任务:
  1. 搭建 Config Server:创建 Git 仓库,配置 Config Server
  2. 多环境配置:为开发、测试、生产环境创建不同配置
  3. 动态刷新:修改配置后,使用 /actuator/refresh 刷新
  4. 集成 Nacos:使用 Nacos 管理配置,体验 Web 界面
  5. 配置加密:使用 Jasypt 加密数据库密码
  6. 共享配置:配置多个服务共享的公共配置
  7. 配置监听:实现配置变更监听器,记录变更日志
  8. 高可用部署:部署 Config Server 集群,测试故障转移

常见问题

Q: Config Server、Nacos、Apollo 如何选择?

A: Config Server 适合 Spring Cloud 生态,Nacos 功能全面且易用(推荐),Apollo 功能最强大但较重。

Q: 配置修改后如何通知所有服务实例?

A: 使用 Spring Cloud Bus + RabbitMQ/Kafka 实现配置广播刷新,或使用 Nacos 的自动推送功能。

总结

配置中心是微服务架构的基础设施。通过本课学习,你应该掌握: