配置中心

返回 Spring Cloud

Spring Cloud 配置中心将应用配置从代码中剥离,支持动态刷新,无需重启服务即可生效。主流方案:Nacos Config(推荐)和 Spring Cloud Config Server(独立部署)。

Nacos Config(推荐)

依赖

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

bootstrap.yml 配置

spring:
  application:
    name: order-service
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
        namespace: dev
        group: DEFAULT_GROUP
        # 默认 dataId = ${spring.application.name}.${file-extension}
        # = order-service.yaml

DataId 命名规则

${prefix}-${spring.profiles.active}.${file-extension}
DataId 示例优先级说明
order-service-dev.yaml环境专属配置
order-service.yaml服务默认配置
shared-db.yaml多服务共享配置

共享配置

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848
        file-extension: yaml
        shared-configs:
          - data-id: shared-db.yaml
            refresh: true
          - data-id: shared-redis.yaml
            refresh: true
        extension-configs:             # 优先级高于 shared-configs
          - data-id: order-special.yaml
            group: ORDER_GROUP
            refresh: true

动态刷新

@RefreshScope   // 配置变更后自动重新注入
@RestController
public class OrderController {
 
    @Value("${order.timeout:5000}")
    private int timeout;
 
    @Value("${order.max-retry:3}")
    private int maxRetry;
}

Spring Cloud Config Server

以 Git 仓库为后端存储的独立配置中心。

Server 端

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApp { ... }
server:
  port: 8888
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/example/config-repo
          default-label: main
          search-paths: '{application}'

Client 端

# bootstrap.yml
spring:
  application:
    name: order-service
  cloud:
    config:
      uri: http://localhost:8888
      label: main
      profile: dev

配置文件命名(Git 仓库中)

{application}-{profile}.yml
# 示例:order-service-dev.yml

手动刷新

# 触发单实例刷新
curl -X POST http://localhost:8080/actuator/refresh
 
# 配合 Spring Cloud Bus 批量刷新(需 RabbitMQ/Kafka)
curl -X POST http://localhost:8888/actuator/busrefresh

配置加密

encrypt:
  key: my-secret-key
# 加密值
curl http://localhost:8888/encrypt -d 'my-db-password'
# 返回:AQA...encrypted...
 
# 在配置文件中使用
spring.datasource.password: '{cipher}AQA...encrypted...'

两种方案对比

特性Nacos ConfigSpring Cloud Config
动态刷新长轮询自动推送需调用 /actuator/refresh
配置存储Nacos 内置Git / SVN / 本地文件
部署复杂度低(复用注册中心)高(需单独部署 + Bus)
版本管理历史版本可回滚Git 天然版本管理
推荐场景国内微服务项目已有 Git 配置管理规范

相关链接

Spring Cloud

架构与中间件