Spring Cloud Nacos配置中心案例

wen java案例 1

本文目录导读:

Spring Cloud Nacos配置中心案例

  1. 环境准备
  2. 服务端配置
  3. 客户端集成
  4. 配置文件多环境支持
  5. 测试接口
  6. 常用注解说明
  7. 生产环境最佳实践
  8. 常见问题处理

我将为您提供一个完整的Spring Cloud Nacos配置中心案例,包括服务端配置、客户端集成和动态刷新。

环境准备

1 启动Nacos Server

# 下载Nacos并启动(默认端口8848)
# 单机模式启动
startup.cmd -m standalone  # Windows
sh startup.sh -m standalone  # Linux/Mac

2 访问Nacos控制台

http://localhost:8848/nacos
默认账号密码:nacos/nacos

服务端配置

1 在Nacos控制台创建配置文件

Data ID: config-demo.yaml Group: DEFAULT_GROUP 配置格式: YAML

# 基础配置
app:
  name: nacos-config-demo
  version: 1.0.0
  description: Spring Cloud Nacos配置中心示例
# 数据库配置
database:
  url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8
  username: root
  password: 123456
  driver-class-name: com.mysql.cj.jdbc.Driver
# Redis配置
redis:
  host: localhost
  port: 6379
  password: 
  database: 0
# 业务配置
business:
  timeout: 5000
  retry-count: 3
  enabled: true
  thresholds:
    warning: 80
    critical: 95
# 日志级别
logging:
  level:
    root: INFO
    com.example: DEBUG

客户端集成

1 Maven依赖 (pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.10</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>nacos-config-demo</artifactId>
    <version>1.0.0</version>
    <name>nacos-config-demo</name>
    <description>Nacos配置中心示例</description>
    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>2021.0.6</spring-cloud.version>
        <spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
    </properties>
    <dependencies>
        <!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Cloud Alibaba Nacos Config -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <!-- Spring Boot Actuator -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- 测试依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2 应用配置

bootstrap.yml

spring:
  application:
    name: config-demo
  cloud:
    nacos:
      config:
        # Nacos服务地址
        server-addr: localhost:8848
        # 配置文件格式
        file-extension: yaml
        # 命名空间(默认public)
        namespace: 
        # 分组
        group: DEFAULT_GROUP
        # 共享配置
        shared-configs:
          - data-id: common.yaml
            group: DEFAULT_GROUP
            refresh: true
        # 扩展配置
        ext-configs:
          - data-id: redis.yaml
            group: DEFAULT_GROUP
            refresh: true
        # 超时配置
        timeout: 5000
        # 是否开启配置管理
        enabled: true
        # 自动刷新
        refresh-enabled: true

application.yml(本地配置)

server:
  port: 8080
spring:
  profiles:
    active: dev
management:
  endpoints:
    web:
      exposure:
        include: "*"

3 主启动类

package com.example.nacosconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableDiscoveryClient
@EnableScheduling
public class NacosConfigApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosConfigApplication.class, args);
        System.out.println("Nacos配置中心示例启动成功!");
    }
}

4 配置属性类

package com.example.nacosconfig.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.Map;
@Data
@Component
@RefreshScope
@ConfigurationProperties(prefix = "business")
public class BusinessConfig {
    private Integer timeout;
    private Integer retryCount;
    private Boolean enabled;
    private Map<String, Integer> thresholds;
    // getters and setters 由Lombok生成
}

5 动态刷新控制器

package com.example.nacosconfig.controller;
import com.example.nacosconfig.config.BusinessConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {
    @Autowired
    private BusinessConfig businessConfig;
    @Value("${app.name:default}")
    private String appName;
    @Value("${app.version:1.0.0}")
    private String appVersion;
    @Value("${database.url:jdbc:mysql://localhost:3306/demo}")
    private String databaseUrl;
    /**
     * 获取所有配置信息
     */
    @GetMapping("/info")
    public Map<String, Object> getConfigInfo() {
        Map<String, Object> result = new HashMap<>();
        result.put("appName", appName);
        result.put("appVersion", appVersion);
        result.put("databaseUrl", databaseUrl);
        result.put("businessConfig", businessConfig);
        log.info("获取配置信息: {}", result);
        return result;
    }
    /**
     * 检查配置是否自动刷新
     */
    @GetMapping("/check")
    public String checkConfigRefresh() {
        return "配置已自动刷新!";
    }
}

6 配置监听器(可选)

package com.example.nacosconfig.listener;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.Listener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.concurrent.Executor;
@Slf4j
@Component
public class NacosConfigListener {
    @Autowired
    private NacosConfigManager nacosConfigManager;
    @PostConstruct
    public void init() {
        try {
            String dataId = "config-demo.yaml";
            String group = "DEFAULT_GROUP";
            // 添加配置监听器
            nacosConfigManager.getConfigService().addListener(dataId, group, new Listener() {
                @Override
                public Executor getExecutor() {
                    return null; // 使用默认执行器
                }
                @Override
                public void receiveConfigInfo(String configInfo) {
                    log.info("配置发生变化: {}", configInfo);
                    // 处理配置变化逻辑
                }
            });
            log.info("Nacos配置监听器初始化完成");
        } catch (Exception e) {
            log.error("初始化Nacos配置监听器失败", e);
        }
    }
}

7 定时任务示例(使用动态配置)

package com.example.nacosconfig.task;
import com.example.nacosconfig.config.BusinessConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ConfigCheckTask {
    @Autowired
    private BusinessConfig businessConfig;
    /**
     * 每30秒检查一次配置
     */
    @Scheduled(fixedDelay = 30000)
    public void checkConfig() {
        log.info("当前业务配置 - timeout: {}, retryCount: {}, enabled: {}, thresholds: {}", 
                businessConfig.getTimeout(),
                businessConfig.getRetryCount(),
                businessConfig.getEnabled(),
                businessConfig.getThresholds());
        if (businessConfig.getEnabled()) {
            log.info("业务功能已启用");
        }
    }
}

配置文件多环境支持

1 Nacos配置文件命名规则

${spring.application.name}-${spring.profiles.active}.${file-extension}

config-demo-dev.yaml     # 开发环境
config-demo-prod.yaml    # 生产环境
config-demo-test.yaml    # 测试环境

2 多环境切换

# 启动时指定环境
java -jar nacos-config-demo.jar --spring.profiles.active=prod
# 或者通过环境变量
export SPRING_PROFILES_ACTIVE=dev
java -jar nacos-config-demo.jar

测试接口

启动应用后,访问以下接口测试:

  1. 获取配置信息

    GET http://localhost:8080/config/info
  2. 测试动态刷新

    • 修改Nacos控制台中的配置
    • 观察应用日志和接口返回
  3. 检查刷新状态

    GET http://localhost:8080/config/check

常用注解说明

注解 说明
@RefreshScope 动态刷新配置,标注在需要刷新的类上
@ConfigurationProperties 绑定配置属性到Java对象
@Value 注入单个配置值
@NacosValue Nacos原生注解,支持自动刷新

生产环境最佳实践

1 配置管理建议

  1. 命名规范

    • Data ID:应用名-环境.格式
    • Group:按业务模块划分
    • Namespace:区分环境(dev/prod/test)
  2. 配置安全

    • 敏感信息加密(密码、密钥等)
    • 使用Nacos的权限管理功能
    • 定期审计配置变更
  3. 可靠性保证

    spring:
    cloud:
     nacos:
       config:
         # 启用配置缓存
         enabled-cache: true
         # 重试配置
         max-retry: 5
         # 重试间隔
         retry-interval: 3000

2 优化建议

// 批量配置绑定
@ConfigurationProperties(prefix = "business", ignoreUnknownFields = false)
public class BusinessProperties {
    // 配置校验
    @Validated
    public static class ValidatedConfig {
        @NotNull(message = "timeout不能为空")
        private Integer timeout;
        @Min(value = 1, message = "retryCount最小为1")
        private Integer retryCount;
    }
}

常见问题处理

1 配置不刷新

# 确保开启刷新
spring:
  cloud:
    nacos:
      config:
        refresh-enabled: true

2 配置加载顺序

  1. bootstrap.yml(最高优先级)
  2. Nacos中心配置
  3. application.yml(本地配置)
  4. application-{profile}.yml

3 故障排除

# 查看Nacos连接日志
curl http://localhost:8080/actuator/env
# 检查配置内容
curl http://localhost:8080/actuator/nacos-config

这样一个完整的Spring Cloud Nacos配置中心案例就完成了,包含了服务端配置、客户端集成、动态刷新、多环境支持等核心功能,您可以根据实际需求进行调整和扩展。

抱歉,评论功能暂时关闭!