Spring Cloud Consul 服务发现和配置工具(Github源代码)

什么是Consul?

Spring Cloud Consul 服务发现和配置工具(Github源代码)

Consul 是一个支持多数据中心、分布式、高可用的服务发现和配置共享的服务软件,由 HashiCorp 公司用 Go 语言开发,基于 Mozilla Public License 2.0 的协议进行开源。Consul 支持健康检查,并允许 HTTP 和 DNS 协议调用 API 存储键值对。

一致性协议采用 Raft 算法,用来保证服务的高可用。使用 GOSSIP 协议管理成员和广播消息,并且支持 ACL 访问控制。

做服务发现的框架常用的有:

  • zookeeper
  • eureka
  • etcd
  • consul

Consul 下载URL:

https://www.consul.io/downloads.html

Consul 能做什么?

  • 使用 Raft 算法来保证一致性,比复杂的 Paxos 算法更直接。相比较而言,zookeeper 采用的是 Paxos,而 etcd 使用的则是 Raft。
  • 支持多数据中心,内外网的服务采用不同的端口进行监听。 多数据中心集群可以避免单数据中心的单点故障,而其部署则需要考虑网络延迟,分片等情况等。zookeeper 和 etcd 均不提供多数据中心功能的支持。
  • 支持健康检查。etcd 不提供此功能。
  • 支持 http 和 dns 协议接口。zookeeper 的集成较为复杂,etcd 只支持 http 协议。
  • 官方提供web管理界面,etcd 无此功能。

综合比较,Consul 作为服务注册和配置管理的新星,比较值得关注和研究。

Consul 安装和启动

这里以windows 平台为示例。

下载完成,解压,执行如下命令,启动Consul。

consul agent -dev -ui

Spring Cloud Consul 服务发现和配置工具(Github源代码)

加上-ui 参数,是为了页面展示。访问 http://localhost:8500,默认进入 ui 界面,如下图所示。

Spring Cloud Consul 服务发现和配置工具(Github源代码)

Consul 还提供了命令行功能。

  • 查看成员: consul members
  • 查看节点: curl 127.0.0.1:8500/v1/catalog/nodes

Spring Cloud Consul 服务发现和配置工具(Github源代码)

Spring Cloud Consul 能做什么?

Spring Cloud Consul作为Spring Cloud 与 Consul之间的桥梁,对两者都有良好的支持。

  • 服务发现,实例可以向Consul 注册服务。
  • 支持Ribbon,客户端负载均衡。
  • 支持Zuul,服务网关。
  • 分布式配置中心,使用Consul的K/V存储。
  • 控制总线,使用 Consul events。

Spring Cloud Consul 实际项目

下面演示的项目,包括3个子项目(modules):

1. ch13-1-consul-provider 服务提供方

2. ch13-1-consul-consumer 服务消费方

3. ch13-1-consul-consumer 使用consul的配置功能

Spring Cloud Consul 服务发现和配置工具(Github源代码)

启动顺序:

(1)先在本地启动consul 服务,之前已经启动过了;

(2)启动consol-provider和consul-consumer;

Spring Cloud Consul 服务发现和配置工具(Github源代码)

(3)然后访问 consul 管理页面,http://localhost:8500

如果Node Health 显示绿色勾选,表示服务注册发布成功。

Spring Cloud Consul 服务发现和配置工具(Github源代码)

(4) 在postman 中,访问http://localhost:8082/hello?name=rickie,返回hello,rickie,表示成功运行。

Spring Cloud Consul 服务发现和配置工具(Github源代码)

项目源代码github:

https://github.com/rickiechina/spring-cloud-code/tree/master/ch13-1

相关推荐