当前位置: 首页 > news >正文

Spring Cloud Alibaba 实战:轻松实现 Nacos 服务发现与动态配置管理

1. Nacos 介绍

1.1 什么是 Nacos?

Nacos(Naming and Configuration Service)是阿里巴巴开源的一个服务注册中心配置管理中心。它支持动态服务发现、配置管理和服务治理,适用于微服务架构,尤其是基于 Spring Cloud 和 Kubernetes 的应用。

1.2 Nacos 主要功能

  • 服务发现与注册:提供类似 Eureka 的服务注册与发现功能。

  • 动态配置管理:可替代 Spring Cloud Config,实现配置的集中管理。

  • 服务健康检查:通过心跳检测服务健康状态。

  • DNS 解析:支持基于 DNS 的服务发现方式。

  • 多环境、多租户管理

2. 环境准备

  • JDK:确保你安装了 JDK 8 或以上版本。
  • Spring Boot:版本建议使用 2.3 或以上。
  • Nacos 服务:确保你已经下载并启动了 Nacos 服务器,可以使用 Nacos GitHub 或官方网站来下载和启动。

2.1 下载并启动 Nacos

  1. 访问 Nacos 官网(Nacos 官方下载页面)下载最新版本的 Nacos。

  2. 解压文件后,进入解压目录,使用以下命令启动 Nacos 服务(默认启动 Nacos 在单机模式下):

    sh startup.sh -m standalone
    
  3. 这时,Nacos 服务将会启动,并在 http://localhost:8848/nacos 上提供访问。

  4. 访问控制台: 打开浏览器访问 http://localhost:8848/nacos,使用默认的账号密码登录:

    • 用户名:nacos
    • 密码:nacos

3. Spring Cloud Alibaba Nacos 配置

3.1 引入依赖

在 Spring Boot 项目中添加必要的依赖。确保你的 pom.xml 文件中包含以下内容:

<dependencies><!-- Spring Boot Web Starter --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring Cloud Alibaba Nacos Discovery --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency><!-- Spring Cloud Alibaba Nacos Config --><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId></dependency><!-- Spring Cloud OpenFeign (Optional, for service consumer) --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency><!-- Spring Boot Actuator (Optional, for monitoring) --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
</dependencies>

这里:

  • spring-cloud-starter-alibaba-nacos-discovery 是 Spring Cloud Nacos 服务注册与发现模块。
  • spring-cloud-starter-alibaba-nacos-config 用于配置管理。
  • spring-cloud-starter-openfeign 用于服务消费者时的 Feign 客户端调用(可选)。

3.2 配置 Nacos 地址

application.propertiesapplication.yml 中配置 Nacos 的地址和应用信息:

# 应用名称,用于服务注册
spring.application.name=demo-service# Nacos 服务注册中心的地址
spring.cloud.nacos.discovery.server-addr=localhost:8848# 配置管理服务的地址
spring.cloud.nacos.config.server-addr=localhost:8848# 配置的文件类型
spring.cloud.nacos.config.file-extension=properties

这些配置项的解释:

  • spring.application.name:Spring Boot 应用的名称,用于在 Nacos 注册。
  • spring.cloud.nacos.discovery.server-addr:Nacos 服务发现模块的地址。
  • spring.cloud.nacos.config.server-addr:Nacos 配置中心的地址,用于配置管理。

4. 服务注册与发现

4.1 创建服务提供者

我们首先创建一个服务提供者,这个服务会在启动时注册到 Nacos 服务注册中心。

服务消费者可以通过 Nacos 来发现并调用服务提供者。

当你启动 DemoServiceApplication 应用时,服务会自动注册到 Nacos,您可以通过访问 http://localhost:8080/hello 来测试服务。

4.2 创建服务消费者

  1. 创建 Spring Boot 应用 DemoServiceApplication
    package com.example.demo;import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;@SpringBootApplication
    @EnableDiscoveryClient  // 启用服务发现
    public class DemoServiceApplication {public static void main(String[] args) {SpringApplication.run(DemoServiceApplication.class, args);}
    }
    

    创建一个简单的控制器 HelloController

    package com.example.demo;import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;@RestController
    public class HelloController {@GetMapping("/hello")public String sayHello() {return "Hello, Nacos!";}
    }
    

在上述代码中:

  • @EnableDiscoveryClient 注解使得 Spring Boot 应用能注册到 Nacos 注册中心。
  • /hello 接口用于向消费者提供服务。

当你启动 DemoServiceApplication 应用时,服务会自动注册到 Nacos,您可以通过访问 http://localhost:8080/hello 来测试服务。

服务消费者可以通过 Nacos 来发现并调用服务提供者。

  1. 创建服务消费者应用 DemoConsumerApplication
    package com.example.consumer;import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.openfeign.EnableFeignClients;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;@SpringBootApplication
    @EnableDiscoveryClient  // 启用服务发现
    @EnableFeignClients      // 启用 Feign 客户端
    public class DemoConsumerApplication {public static void main(String[] args) {SpringApplication.run(DemoConsumerApplication.class, args);}
    }
    

  2. 创建 Feign 客户端接口 HelloFeignClient 
package com.example.consumer;import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;@FeignClient(name = "demo-service")  // 与服务提供者的应用名匹配
public interface HelloFeignClient {@GetMapping("/hello")String sayHello();
}

 3.创建控制器 HelloController 用于消费服务:

package com.example.consumer;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@Autowiredprivate HelloFeignClient helloFeignClient;@GetMapping("/consume")public String consumeService() {return helloFeignClient.sayHello();  // 使用 Feign 调用服务提供者}
}
  • @FeignClient(name = "demo-service")name 是服务提供者的应用名称。Fein 会自动从 Nacos 获取服务实例并进行调用。
  • /consume 接口通过 Feign 客户端调用服务提供者的 /hello 接口。

5. 配置管理

Nacos 还可以作为配置中心,动态管理应用配置。

5.1 上传配置到 Nacos

  1. 打开 Nacos 控制台,选择左侧的 "配置管理" -> "配置列表" -> "新增配置"。
  2. 配置文件内容如下(假设文件类型为 .properties):
    # application.properties
    demo.property=HelloFromNacos
    
  3. 在 "Data ID" 中填写 application.properties,选择 GroupDEFAULT_GROUP,点击发布
  4. 在 Spring Boot 中,可以通过 @Value 注解直接获取配置项:

    package com.example.demo;import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;@RestController
    public class ConfigController {@Value("${demo.property}")private String demoProperty;@GetMapping("/config")public String getConfig() {return demoProperty;  // 返回从 Nacos 获取的配置}
    }
    

这里:

  • @Value("${demo.property}") 读取 Nacos 中配置的 demo.property 属性。

5.2动态刷新配置

当 Nacos 中的配置发生变化时,Spring Cloud Alibaba Nacos 支持动态刷新配置。为了实现这个功能,我们可以使用 @RefreshScope 注解。

ConfigController 中:

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;@RefreshScope
@RestController
public class ConfigController {@Value("${demo.property}")private String demoProperty;@GetMapping("/config")public String getConfig() {return demoProperty;}
}
  • @RefreshScope 会使得当配置变化时,Spring 会自动刷新配置的值,而不需要重启应用。

6. 总结

通过 Spring Cloud Alibaba Nacos,你可以:

  • 实现服务注册与发现,利用 Nacos 注册中心进行服务管理。
  • 使用 Feign 客户端轻松实现服务间通信。
  • 动态管理配置,并通过 Nacos 配置中心实现配置的动态更新。

这套方案非常适合用于构建微服务架构,尤其是需要服务注册与发现、配置管理以及动态刷新功能的场景。

http://www.lryc.cn/news/547304.html

相关文章:

  • 【数据结构】LRUCache|并查集
  • 智能合约中权限管理不当
  • MariaDB Galera 原理及用例说明
  • 【RAG 篇】万字长文:向量数据库选型指南 —— Milvus 与 FAISS/Pinecone/Weaviate 等工具深度对比
  • 关于服务器cpu过高的问题排查
  • Gpt翻译完整版
  • 雷池WAF的为什么选择基于Docker
  • 美股回测:历史高频分钟数据的分享下载与策略解析20250305
  • 【文生图】windows 部署stable-diffusion-webui
  • [Python入门学习记录(小甲鱼)]第3章 Python基础知识
  • 某系统webpack接口泄露引发的一系列漏洞
  • 【计算机网络入门】初学计算机网络(十一)重要
  • 决策树(Decision Tree)基础知识
  • Nat Mach Intell | AI分子对接算法评测
  • 【自学笔记】Hadoop基础知识点总览-持续更新
  • 【Linux】使用问题汇总
  • (二 十 二)趣学设计模式 之 备忘录模式!
  • 交叉编译openssl及curl
  • 【每日八股】计算机网络篇(三):IP
  • Gartner:数据安全平台DSP提升数据流转及使用安全
  • 从vue源码解析Vue.set()和this.$set()
  • 深入浅出:UniApp 从入门到精通全指南
  • DeepSeek未来发展趋势:开创智能时代的新风口
  • 阻塞队列的实现(线程案例)
  • http status是什么?常见的http状态码指的是什么意思?
  • react组件分离,降低耦合
  • 【AI】AI白日梦+ChatGPT 三分钟生成爆款短视频
  • MYSQL的安装教程
  • 深入解析 C# 中的泛型:概念、用法与最佳实践
  • NUMA架构介绍