← 返回首页
⚙️

配置中心详解:Spring Cloud Config与Nacos

📂 java ⏱ 2 min 205 words

配置中心详解:Spring Cloud Config与Nacos

概述

配置中心是微服务架构的重要组件。本教程介绍Spring Cloud Config和Nacos Config的使用。

1. Spring Cloud Config

// Config Server
import org.springframework.cloud.config.server.EnableConfigServer;

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

// 配置
# application.yml
server:
  port: 8888
spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/user/config-repo
          search-paths: '{application}'
          username: ${GIT_USERNAME}
          password: ${GIT_PASSWORD}

2. Nacos Config

// Nacos Config
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

@Component
@RefreshScope
public class NacosConfig {
    @Value("${app.config.value:default}")
    private String configValue;
    
    public String getConfigValue() {
        return configValue;
    }
}

// 配置
# application.yml
spring:
  cloud:
    nacos:
      config:
        server-addr: localhost:8848
        file-extension: yaml
        group: DEFAULT_GROUP
        namespace: public

3. 实际应用示例

动态配置刷新

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RefreshScope
public class ConfigController {
    @Value("${app.feature.enabled:false}")
    private boolean featureEnabled;
    
    @GetMapping("/config")
    public Map<String, Object> getConfig() {
        Map<String, Object> config = new HashMap<>();
        config.put("featureEnabled", featureEnabled);
        config.put("timestamp", System.currentTimeMillis());
        return config;
    }
    
    @GetMapping("/feature")
    public String feature() {
        if (featureEnabled) {
            return "新功能已启用";
        }
        return "新功能未启用";
    }
}

配置加密

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class EncryptedConfig {
    @Value("${app.database.password}")
    private String encryptedPassword;
    
    public String getPassword() {
        // 解密配置
        return decrypt(encryptedPassword);
    }
    
    private String decrypt(String encrypted) {
        // 解密逻辑
        return encrypted;
    }
}

4. 最佳实践

  1. 集中管理配置:使用配置中心统一管理
  2. 环境隔离:区分开发、测试、生产环境
  3. 配置加密:敏感配置需要加密
  4. 动态刷新:支持配置动态更新
  5. 版本管理:配置版本控制

总结

配置中心是微服务架构的重要组件。掌握Spring Cloud Config和Nacos Config的使用,可以实现配置的集中管理和动态刷新。