为了账号安全,请及时绑定邮箱和手机立即绑定

Spring Cloud + Consul 服务注册与发现入门实战笔记

适用人群:Java 开发工程师,熟悉 Spring Boot,正在学习 Spring Cloud 微服务
技术栈:Spring Boot 3.2 + Spring Cloud 2023.x + Consul 1.16+ + JDK 17
目标:5 分钟上手 Consul 作为注册中心,实现服务注册、发现与配置动态刷新!

一、Consul 是什么?

Consul 是由 HashiCorp 推出的开源工具,用于实现 服务发现、健康检查、KV 配置存储、多数据中心支持 等功能。在微服务架构中,它常被用作 服务注册中心(Service Registry) 和 配置中心(Configuration Center)。

✅ 为什么选择 Consul?

  • 轻量级、单二进制部署,无外部依赖
  • 内置 Web UI,可视化服务状态
  • 支持健康检查(自动剔除故障实例)
  • 提供 Key/Value 存储,可用于动态配置
  • 与 Spring Cloud 深度集成(spring-cloud-starter-consul-discovery)

💡 对比:Nacos = 注册中心 + 配置中心 + 控制台;Consul = 注册中心 + KV 配置 + 健康检查(更偏向基础设施层)

二、安装与启动 Consul

  1. 下载 Consul

访问官方下载页:https://www.consul.io/downloads

选择你的操作系统(Windows / macOS / Linux),例如 macOS:

bash
使用 Homebrew(推荐)
brew install consul

或手动下载(以 Linux 为例)
wget https://releases.hashicorp.com/consul/1.16.2/consul_1.16.2_linux_amd64.zip
unzip consul_1.16.2_linux_amd64.zip
sudo mv consul /usr/local/bin/

  1. 启动 Consul(开发模式)

bash
consul agent -dev -ui -client=0.0.0.0

参数说明:

  • -dev:开发模式(数据不持久化)
  • -ui:启用 Web 控制台
  • -client=0.0.0.0:允许外部访问 UI(默认只监听 127.0.0.1)
  1. 访问 Consul UI

打开浏览器:http://localhost:8500

你会看到 Consul 的管理界面,初始状态下 Services 列表为空。

三、Spring Cloud + Consul 快速入门案例

我们将构建两个服务:

  • user-service:用户服务(Provider)
  • order-service:订单服务(Consumer,调用 user-service)

项目结构

consul-demo/
├── user-service/ # 服务提供者
└── order-service/ # 服务消费者

步骤 1:创建公共依赖(可选)

确保两个服务使用相同的 Spring Cloud 版本。在父 POM 中定义:

xml

17
3.2.0
2023.0.0


    
        org.springframework.cloud
        spring-cloud-dependencies
        {spring-cloud.version}
        pom
        import

步骤 2:搭建 user-service(服务提供者)

Maven 依赖

xml

    org.springframework.boot
    spring-boot-starter-web




    org.springframework.cloud
    spring-cloud-starter-consul-discovery

application.yml 配置

yaml
server:
port: 8081

spring:
application:
name: user-service # 服务名称(必须!)
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: {spring.application.name}
instance-id: {spring.application.name}-{random.value} # 避免冲突
health-check-path: /actuator/health # 健康检查路径
health-check-interval: 15s

⚠️ 注意:Consul 默认通过 /actuator/health 检查服务健康状态,需引入 spring-boot-starter-actuator

添加 Actuator(健康检查必需)

xml

org.springframework.boot
spring-boot-starter-actuator

编写一个简单接口

java
@RestController
public class UserController {
@GetMapping("/user/{id}")
public String getUser(@PathVariable String id) {
return “User " + id + " from user-service”;
}
}

启动类(无需额外注解!)

java
@SpringBootApplication
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}

✅ 启动后,访问 http://localhost:8500,你会在 Services 中看到 user-service!

步骤 3:搭建 order-service(服务消费者)

Maven 依赖(同 user-service)

xml

application.yml

yaml
server:
port: 8082

spring:
application:
name: order-service
cloud:
consul:
host: localhost
port: 8500
discovery:
service-name: {spring.application.name}
instance-id: {spring.application.name}-{random.value}
health-check-path: /actuator/health
health-check-interval: 15s

使用 RestTemplate + 服务发现

java
@Configuration
public class RestConfig {
@Bean
@LoadBalanced // 启用负载均衡(基于 Consul 服务列表)
public RestTemplate restTemplate() {
return new RestTemplate();
}
}

Controller 调用远程服务

java
@RestController
public class OrderController {

@Autowired
private RestTemplate restTemplate;

@GetMapping("/order/{userId}")
public String createOrder(@PathVariable String userId) {
    // 使用服务名 "user-service" 代替 IP:PORT
    String url = "http://user-service/user/" + userId;
    String userInfo = restTemplate.getForObject(url, String.class);
    return "Order created for " + userInfo;
}

}

✅ 启动 order-service,访问:
http://localhost:8082/order/123
返回:Order created for User 123 from user-service

🎉 成功!服务通过 Consul 自动发现并调用!

四、配置动态刷新(使用 Consul KV)

Consul 不仅是注册中心,还提供 Key/Value 存储,可用于动态配置。

  1. 启用 Consul Config

在 order-service 的 pom.xml 中添加:

xml

org.springframework.cloud
spring-cloud-starter-consul-config
  1. 配置 Consul Config

在 bootstrap.yml(注意:不是 application.yml!)中:

yaml
spring:
application:
name: order-service
cloud:
consul:
host: localhost
port: 8500
config:
enabled: true
format: YAML # 支持 PROPERTIES / YAML / FILES
prefix: config # KV 路径前缀
data-key: data # 存储配置的 key 名

⚠️ 注意:Spring Cloud 2022+ 默认禁用 bootstrap.yml,需手动启用:
properties

在 application.properties 中添加

spring.cloud.bootstrap.enabled=true
或者,在 application.yml 中直接配置(推荐方式,避免 bootstrap):

yaml
spring:
cloud:
consul:
config:
enabled: true
format: YAML
prefix: config
default-context: order-service # 对应 KV 路径: config/order-service

  1. 在 Consul UI 中添加配置

  2. 打开 http://localhost:8500/ui/dc1/kv

  3. 点击 Create,输入 Key:config/order-service/data

  4. Value 内容(YAML 格式):

yaml
app:
welcome-message: “Hello from Consul KV!”

  1. 在代码中读取并动态刷新

java
@RestController
@RefreshScope // 关键!支持配置动态刷新
public class ConfigController {

@Value("{app.welcome-message:Default Message}")
private String welcomeMessage;

@GetMapping("/config")
public String getConfig() {
    return welcomeMessage;
}

}

  1. 触发刷新

修改 Consul 中的 KV 值后,调用 /actuator/refresh(需暴露端点):

在 application.yml 中添加:

yaml
management:
endpoints:
web:
exposure:
include: refresh,health,info

然后 POST 请求:

再次访问 /config,即可看到新值!

✅ 实现了 配置动态刷新,无需重启服务!

五、常见问题排查
问题 解决方案
服务未注册到 Consul 检查 spring.application.name 是否设置;确认 Consul 地址正确;查看日志是否有连接错误

调用时报 UnknownHostException 确保 RestTemplate 加了 @LoadBalanced

配置不生效 检查是否使用 @RefreshScope;确认 KV 路径是否为 config/{service-name}/data

Consul UI 无法访问 启动时加 -client=0.0.0.0;检查防火墙

六、总结

通过本笔记,你已掌握:

✅ Consul 安装与启动
✅ Spring Cloud 服务注册与发现
✅ 使用 RestTemplate + @LoadBalanced 实现服务调用
✅ 利用 Consul KV 实现配置动态刷新
✅ 常见问题快速定位

📌 最佳实践建议:

  • 生产环境使用 Consul 集群(非 -dev 模式)
  • 配置健康检查路径,确保故障实例自动剔除
  • 敏感配置不要明文存 KV,可结合 Vault
  • 结合 Spring Cloud Gateway 实现统一入口

附录:完整代码参考

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
27
获赞与收藏
81

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消