本文共 4056 字,大约阅读时间需要 13 分钟。
Nacos 注册中心是一个基于服务发现与负载均衡的动态注册系统,主要服务于分布式系统中的微服务架构。其核心交互流程涉及两类角色:服务提供者(生产者)和服务消费者(消费者)。
生产者通常是提供核心服务的微服务实例,其主要职责是向注册中心注册自身信息,以便其他服务能够发现并调用它。具体实现步骤如下:
spring-cloud-starter-alibaba-nacos-discovery
实现服务注册与发现功能。消费者则是依赖其他服务的应用程序,它需要通过注册中心发现所需服务并进行远程调用。实现步骤如下:
spring-cloud-starter-alibaba-nacos-discovery
、spring-cloud-starter-loadbalancer
和 spring-cloud-starter-openfeign
等相关组件。@EnableFeignClients
开启 OpenFeign 功能,实现基于声明式的 RESTful 调用。@FeignClient
注解定义需要调用的服务接口,并配置必要的负载均衡策略。为实现模块化管理,建议采用 Spring Boot 多模块项目结构。具体操作如下:
pom.xml
中添加必要的依赖项,并删除其他模块的相关文件。pom.xml
文件,声明其依赖项目。pom.xml
中添加子模块的依赖声明,并指定打包顺序。在应用程序的配置文件中,添加以下 Nacos 配置:
spring: application: name: nacos-discovery-demo cloud: nacos: discovery: server-addr: localhost:8848 username: nacos password: nacos group: SIT_GROUP ephemeral: falseserver: port: 0
此外,还需设置注册保护阈值、服务路由类型等高级参数。
在生产者模块中,开发以下接口:
@RestController@RequestMapping("/user")public class UserController { @Autowired private ServletWebServerApplicationContext context; @RequestMapping("/getnamebyid") public String getUserByID(@RequestParam("id") int id) { return "provider-name:" + id + " | server-port:" + context.getWebServer().getPort(); }}
此接口主要用于向外暴露服务信息,供消费者调用。
在消费者模块中,除了父模块已经配置的依赖外,子模块需要额外添加以下依赖:
com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery org.springframework.cloud spring-cloud-starter-loadbalancer org.springframework.cloud spring-cloud-starter-openfeign
在消费者模块的配置文件中,添加以下内容:
spring: application: name: nacos-consumer-demo cloud: nacos: discovery: username: nacos password: nacos server-addr: localhost:8848 register-enabled: falseserver: port: 58080
在消费者主类中,添加以下注解:
@SpringBootApplication@EnableFeignClientspublic class ConsumerApplication { public static void main(String[] args) { SpringApplication.run(ConsumerApplication.class, args); }}
定义服务接口:
@Service@FeignClient("nacos-discovery-demo")public interface UserService { @RequestMapping("/user/getnamebyid") public String getNameById(@RequestParam("id") int id);}
在业务控制器中实现具体的调用逻辑:
@RestControllerpublic class BusinessController { @Autowired private UserService userService; @RequestMapping("/getnamebyid") public String getNameById(@RequestParam("id") Integer id) { return userService.getNameById(id); }}
服务名由应用程序在配置文件中设置,如:
spring: application: name: nacos-discovery-demo
默认分组为 DEFAULT_GROUP
,可自定义为其他组名:
spring: cloud: nacos: discovery: group: prod-test
保护阈值用于防止流量集中到少量健康实例,设置范围为 0 到 1:
spring: cloud: nacos: discovery: protect-threshold: 0.8
支持多种路由策略,如 none
(默认路由)和 label
(标签路由):
spring: cloud: nacos: discovery: routing-type: label
配置为临时实例时,服务停止后会自动下线:
spring: cloud: nacos: discovery: ephemeral: true
用于负载均衡,数值越大,权重越高:
spring: cloud: nacos: discovery: weight: 8000
标签路由通过服务标签进行流量分配,确保不同标签之间的服务实例互不影响。
临时实例通过心跳机制维持在线状态,服务器端和客户端均有健康检测机制。
Nacos 配置中心采用长轮询+事件驱动模式实现配置自动刷新:
注册中心主要包含服务注册和服务发现两个核心组件:
通过异步任务和内存队列实现高效处理:
这种设计使得注册中心能够支持百万级别的服务注册和发现,具备高并发处理能力。
转载地址:http://ordfk.baihongyu.com/