Nacos 服务注册与发现
TIP
Nacos(Dynamic Naming and Configuration Service)是阿里巴巴开源的服务发现和配置管理平台,是替代 Eureka 的主流选择。
Nacos 特点
- 服务发现:支持 DNS 和 RPC 方式的健康检查
- 动态配置:配置变更实时推送,支持版本管理
- 水平扩展:支持 AP 和 CP 模式切换
- 易于运维:自带可视化控制台
部署 Nacos
bash
# Docker 快速部署
docker run -d --name nacos -p 8848:8848 -p 9848:9848 -e MODE=standalone nacos/nacos-server:2.2.3
# 访问控制台 http://localhost:8848/nacos
# 默认账号密码: nacos/nacos服务提供者配置
yaml
spring:
application:
name: user-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
namespace: public
group: DEFAULT_GROUP
server:
port: 8081java
@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
@RestController
@RequestMapping("/user")
public class UserController {
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "张三", 25);
}
}服务消费者配置
yaml
spring:
application:
name: order-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848java
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}
// Feign 客户端调用 user-service
@FeignClient(name = "user-service")
public interface UserFeignClient {
@GetMapping("/user/{id}")
User getUser(@PathVariable("id") Long id);
}健康检查机制
yaml
spring:
cloud:
nacos:
discovery:
heart-beat-interval: 5000 # 心跳间隔
heart-beat-timeout: 15000 # 心跳超时
ip-delete-timeout: 30000 # 实例删除超时