Spring Cloud Consul 从入门到实战:服务注册发现 + 配置中心一站式搞定

在微服务架构中,服务注册发现配置管理是两大核心基石。除了我们熟悉的 Eureka、Nacos 外,Consul 凭借强一致性、开箱即用的特性,成为企业微服务组件的热门选择。

本文基于 Spring Cloud 生态,从零带你掌握 Consul 安装、服务注册发现、配置中心、动态刷新、数据持久化全流程,小白也能直接上手实战~


一、Consul 是什么?核心功能一览

Consul 是 HashiCorp 开源的分布式组件,一站式提供服务注册发现、健康检查、Key/Value 配置存储、多环境隔离,天生适配 Spring Cloud 微服务体系。

核心能力:

  1. 服务注册 / 发现:服务启动自动注册,支持 HTTP/DNS 方式查询服务实例

  2. 健康检查:自动剔除异常服务,保证流量只转发到健康实例

  3. 配置管理:基于 KV 存储,支持配置共享、动态刷新

  4. 环境隔离:通过服务分段区分开发 / 测试 / 生产环境


二、Consul vs Nacos:怎么选更合适?

很多同学纠结 Consul 和 Nacos 怎么选,直接看核心差异:

功能 Consul Nacos
服务发现 DNS + HTTP API DNS + HTTP API
健康检查 服务端主动探测 客户端心跳 + 服务端探测
配置中心 KV 基础存储 专业配置中心,支持版本 / 灰度
一致性 Raft 强一致(CP) 默认 AP,可切换 CP
性能 强一致下更稳,吞吐量一般 高吞吐,海量实例更友好

选型建议

  • 追求强一致性、数据安全 → 选 Consul

  • 追求高可用、高性能、配置功能丰富 → 选 Nacos


三、Windows + Linux 双系统安装 Consul

1. Windows 安装

  1. 官网下载:developer\.hashicorp\.com

  2. 解压得到 consul\.exe,CMD 进入目录执行:

# 查看版本
.\consul.exe --version
# 开发模式启动(测试用)
.\consul.exe agent -dev
  1. 访问控制台:http://127\.0\.0\.1:8500,出现界面即成功

2. Linux(Ubuntu)安装

# 导入密钥
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
# 添加源
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
# 安装
sudo apt update && sudo apt install consul
# 后台启动
nohup consul agent -dev -client 0.0.0.0 -ui &

四、Spring Cloud 整合 Consul:服务注册发现

1. 引入依赖

必须搭配 actuator 做健康检查:

<!-- Consul 服务发现 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!-- 健康检查 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2. 配置 application.yml

spring:
  application:
    name: product-service
  cloud:
    consul:
      host: 127.0.0.1
      port: 8500
      discovery:
        service-name: product-service # 可不写,默认取 application-name

3. 启动类加注解

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

启动服务,打开 Consul 控制台即可看到服务已注册成功!


五、Consul 做配置中心:动态刷新一步到位

Consul 自带 KV 存储,可直接替代 Spring Cloud Config,支持配置共享、环境隔离、动态刷新

1. Consul 控制台创建配置

  1. 进入 Key/Value → 新建 config/ 根目录

  2. 按服务名创建:config/product\-service/

  3. 新建 Key:data,Value 写 YAML 配置:

service-name: product-service-default
output:
  info: "bite-default"

2. 项目添加配置依赖

<!-- Consul 配置 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>
<!-- 启动 bootstrap 上下文 -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

3. 新建 bootstrap.yml(优先级最高)

spring:
  application:
    name: product-service
  cloud:
    consul:
      host: 127.0.0.1
      port: 8500
      config:
        format: YAML # 配置格式

4. 读取配置 + 动态刷新

  1. 控制器添加 @RefreshScope

  2. 使用 @Value 读取配置

@RestController
@RequestMapping("/consul")
@RefreshScope // 开启动态刷新
public class ConsulController {
    @Value("${service-name}")
    private String serviceName;
    @Value("${output.info}")
    private String outputInfo;

    @GetMapping("/getConfigByConsul")
    public String getConfig() {
        return "serviceName:" + serviceName + ", info:" + outputInfo;
    }
}

修改 Consul 配置后,无需重启服务,自动刷新生效!

5. 配置优先级(多环境必备)

config/product-service,dev/ > config/product-service/ > config/application,dev/ > config/application/
  • 精准匹配 &gt; 全局匹配

  • 环境配置 &gt; 默认配置


六、生产关键:Consul 数据持久化

开发模式(\-dev)重启后数据会丢失,生产必须用服务器模式 + 数据目录

consul agent -server -bootstrap-expect 1 -ui -data-dir=D:\consul_data
  • \-server:服务节点

  • \-bootstrap\-expect 1:单节点集群

  • \-data\-dir:数据持久化目录


七、总结

Spring Cloud Consul 是一套轻量、稳定、强一致的微服务解决方案:

  • 一键实现服务注册发现 + 健康检查

  • 自带KV 配置中心,支持动态刷新

  • 安装简单、适配 Spring Cloud 生态

  • 生产可持久化、支持集群部署

适合对数据一致性要求高、希望组件轻量化的微服务场景。

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐