Spring Cloud Consul使用指南
Consul 是 Spring Cloud 生态中用于服务发现和分布式配置管理的核心工具,以下是详细的使用指南:
一、Consul的核心功能
- 服务发现:微服务自动注册与发现,解决硬编码IP的问题
- 健康检查:定期检查服务状态,自动剔除故障节点
- KV存储:集中管理分布式配置,支持动态更新
- 多数据中心:支持跨数据中心的集群管理
二、入门使用步骤
1. 安装Consul
- Docker方式(推荐):
Web界面访问:docker run -d -p 8500:8500 --name=consul consul agent -server -bootstrap -ui -client=0.0.0.0
http://localhost:8500
2. 创建Spring Boot项目
- Maven依赖:
<!-- Consul 服务发现 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <!-- Consul 配置管理(可选) --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> </dependency> <!-- Actuator健康检查 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
3. 配置服务注册
-
启动类开启发现功能:
@SpringBootApplication @EnableDiscoveryClient // 关键注解 public class UserServiceApplication { public static void main(String[] args) { SpringApplication.run(UserServiceApplication.class, args); } }
-
application.yml配置:
spring: application: name: user-service # 服务名称 cloud: consul: host: localhost port: 8500 discovery: service-name: ${spring.application.name} health-check-path: /actuator/health health-check-interval: 15s
4. 实现服务调用
-
使用RestTemplate:
@Bean @LoadBalanced // 开启负载均衡 public RestTemplate restTemplate() { return new RestTemplate(); } @Autowired private RestTemplate restTemplate; public String callOtherService() { // 直接使用服务名代替IP return restTemplate.getForObject("http://order-service/api/data", String.class); }
-
或使用Feign Client:
@FeignClient(name = "order-service") public interface OrderServiceClient { @GetMapping("/api/data") String getData(); }
5. 配置中心使用
-
创建bootstrap.yml(优先级高于application.yml):
spring: cloud: consul: config: enabled: true format: YAML # 配置格式 data-key: config/user-service # Consul中的键路径
-
在Consul中添加配置:
- 访问Consul UI → Key/Value
- 创建键:
config/user-service/data
- 值示例:
logging: level: org.springframework: DEBUG custom: property: dynamic_value
-
代码中读取配置:
@Value("${custom.property}") private String myProperty;
6. 动态配置刷新
-
添加刷新注解:
@RefreshScope // 在需要动态刷新的Bean上添加 @RestController public class DemoController { @Value("${custom.property}") private String dynamicProp; @GetMapping("/value") public String getValue() { return dynamicProp; } }
-
手动触发刷新:
POST http://localhost:8080/actuator/refresh
三、高级技巧
- 多环境配置:使用
config/user-service,dev/data
和config/user-service,prod/data
区分环境 - 安全加固:启用Consul ACL,配置访问令牌
- 集群部署:通过
-join
参数组建多节点集群提升可用性 - 与Gateway整合:在Spring Cloud Gateway中通过Consul实现动态路由
验证步骤:
- 启动Consul和多个服务实例
- 访问
http://localhost:8500
查看服务注册状态 - 调用服务接口验证通信是否正常
- 修改Consul中的KV配置,观察应用是否动态响应
遇到问题时,重点检查:网络连通性、依赖版本(建议使用Spring Cloud 2021.x + Consul 1.11.x)、Consul权限配置。