SpringCloud-Consul
1. Consul 简介
Consul是 HashiCorp 公司推出的开源工具,用于实现分布式系统的服务发现与配置。与其它分布式服 务注册与发现的方案,Consul 的方案更“一站式”,内置了服务注册与发现框 架、分布一致性协议实 现、健康检查、Key/Value 存储、多数据中心方案,不再需要依赖其它工具(比如 ZooKeeper 等)。 使用起来也较为简单。Consul 使用 Go 语言编写,因此具有天然可移植性(支持Linux、windows和 Mac OS X);安装包仅包含一个可执行文件,方便部署,与 Docker 等轻量级容器可无缝配合。
2. 专业名词
agent
组成 consul 集群的每个成员上都要运行一个 agent,可以通过 consul agent 命令来启动。agent可以运行在 server 状态或者 client 状态。自然的, 运行在 server 状态的节点被称为 server 节点,运行在 client 状态的节点被称 为 client 节点。
server 节点
负责组成 cluster 的复杂工作(选举server 自行选举一个 leader、状态维 护、转发请求到 leader),以及 consul 提供的服务(响应RPC 请求),以及存放和复制数据。考虑到容错和可用性,一般部署 3 ~ 5 个比较合适。
client 节点
负责转发所有的 RPC 到 server 节点。本身无状态,且轻量级,因此,可以部署大量的client 节点。
数据中心
虽然数据中心的定义似乎很明显,但仍有一些细微的细节必须考虑。我们 将一个数据中心定义为一个私有、低延迟和高带宽的网络环境。这不包括通过公共互联网的通信,但是为了我们的目的,单个EC2 (aws云主机)区域内的多个可用区域将被视为单个数据中心的一部分。
3. Consul 的优势
使用 Raft 算法来保证一致性, 比复杂的 Paxos 算法更直接. 相比较而言, zookeeper 采用的是 Paxos, 而 etcd 使用的则是 Raft。
支持多数据中心,内外网的服务采用不同的端口进行监听。 多数据中心集群可以避免单数据中心 的单点故障,而其部署则需要考虑网络延迟, 分片等情况等。 zookeeper 和 etcd 均不提供多数据中 心功能的支持。
支持健康检查。 etcd 不提供此功能。
支持 http 和 dns 协议接口。 zookeeper 的集成较为复杂, etcd 只支持 http 协议。 官方提供 web 管理界面, etcd 无此功能。
综合比较, Consul 作为服务注册和配置管理的新星, 比较值得关注和研究。
4. 特性
- 服务发现
- 健康检查
- Key/Value 存储
- 多数据中心
5. Consul与Eureka的区别
一致性 Consul强一致性(CP)
- 服务注册相比Eureka会稍慢一些。因为Consul的raft协议要求必须过半数的节点都写入成功才认 为注册成功
- Leader挂掉时,重新选举期间整个consul不可用。保证了强一致性但牺牲了可用性。
Eureka保证高可用和最终一致性(AP)
服务注册相对要快,因为不需要等注册信息replicate到其他节点,也不保证注册信息是否 replicate成功
当数据出现不一致时,虽然A, B上的注册信息不完全相同,但每个Eureka节点依然能够正常对外提 供服务,这会出现查询服务信息时如果请求A查不到,但请求B就能查到。如此保证了可用性但牺牲了一致性。
6. Consul 安装
6.1 docker-compose安装
以dev模式启动 且 设置client=0.0.0.0为所有ip都可以连接此服务
version: '2'
services:
consul-container:
image: consul
container_name: consul-dev
environment:
- CONSUL_BIND_INTERFACE=eth0
ports:
- "8500:8500"
volumes:
- "./config:/consul/config/"
- "./data/:/consul/data/"
command: agent -dev -client=0.0.0.0
服务启动成功后,通过浏览器访问localhost:8500,显示如下页面即安装成功。

7. Quick Start
7.1 启动consul服务
本文使用的是docker-compose方式管理consul服务,直接启动即可
7.2 创建客户端-provider
7.2.1 引入依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
<!--actuator用于心跳检查-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
7.2.2 配置application.yml
server:
port: ${port:8082}
spring:
application:
name: provider
cloud:
consul:
#consul服务地址
host: 127.0.0.1
#consul服务端口
port: 8500
discovery:
#是否注册
register: true
#实例ID
# instance-id: ${spring.application.name}-${server.port}
instance-id: ${spring.application.name}:${random.value}
#服务实例名称
service-name: ${spring.application.name}
#服务实例端口
port: ${server.port}
#健康检查路径
healthCheckPath: /actuator/health
#健康检查时间间隔
healthCheckInterval: 15s
#开启ip地址注册
prefer-ip-address: true
#实例的请求ip
ip-address: ${spring.cloud.client.ip-address}
7.2.3 添加测试方法
package com.ldx.provider.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestController {
@Autowired
private DiscoveryClient discoveryClient;
@Value("${server.port}")
private String port;
@GetMapping("products")
public String products(){
List<ServiceInstance> list = discoveryClient.getInstances("consumer");
if(list != null && list.size() > 0 ) {
ServiceInstance serviceInstance = list.get(0);
System.out.println(serviceInstance);
}
return "Hello World:" + port;
}
}
7.3 创建客户端-comsumer
创建过程和provider一样 测试方法换一下,并且在启动类上添加RestTemplate Bean
7.3.1 配置application.yml
server:
port: ${port:8081}
spring:
application:
name: consumer
cloud:
consul:
#consul服务地址
host: 127.0.0.1
#consul服务端口
port: 8500
discovery:
#是否注册
register: true
#实例ID
# instance-id: ${spring.application.name}-${server.port}
instance-id: ${spring.application.name}:${random.value}
#服务实例名称
service-name: ${spring.application.name}
#服务实例端口
port: ${server.port}
#健康检查路径
healthCheckPath: /actuator/health
#健康检查时间间隔
healthCheckInterval: 15s
#开启ip地址注册
prefer-ip-address: true
#实例的请求ip
ip-address: ${spring.cloud.client.ip-address}
metadata:
#添加自定义元数据
my-name: zhangtieniu-consumer
7.3.2 添加支持负载均衡的RestTemplate
package com.ldx.consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate loadbalancedRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
}
7.3.3 添加测试方法
package com.ldx.consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping()
public String consumer(){
return this.restTemplate.getForObject("http://provider/products", String.class);
}
}
7.4 启动
启动了两个 provider 和一个 consumer

浏览器输入
localhost:8500查看consul控制台,显示服务注册成功

测试服务调用


其中provider 输出的 实例信息如下:
[ConsulServiceInstance@4c2b7437 instanceId = 'consumer-6cfd981c90545313155d1f43c3ed23a5', serviceId = 'consumer', host = '192.168.0.101', port = 8081, secure = false, metadata = map['my-name' -> 'zhangtieniu-consumer', 'secure' -> 'false'], uri = http://192.168.0.101:8081, healthService = HealthService{node=Node{id='3fe6ea9e-3846-ff8d-b01f-a6528caaa3fd', node='44a66c1caa9c', address='172.26.0.2', datacenter='dc1', taggedAddresses={lan=172.26.0.2, lan_ipv4=172.26.0.2, wan=172.26.0.2, wan_ipv4=172.26.0.2}, meta={consul-network-segment=}, createIndex=11, modifyIndex=13}, service=Service{id='consumer-6cfd981c90545313155d1f43c3ed23a5', service='consumer', tags=[], address='192.168.0.101', meta={my-name=zhangtieniu-consumer, secure=false}, port=8081, enableTagOverride=false, createIndex=275, modifyIndex=275}, checks=[Check{node='44a66c1caa9c', checkId='serfHealth', name='Serf Health Status', status=PASSING, notes='', output='Agent alive and reachable', serviceId='', serviceName='', serviceTags=[], createIndex=11, modifyIndex=11}, Check{node='44a66c1caa9c', checkId='service:consumer-6cfd981c90545313155d1f43c3ed23a5', name='Service 'consumer' check', status=PASSING, notes='', output='HTTP GET http://192.168.0.101:8081/actuator/health: 200 Output: {"status":"UP"}', serviceId='consumer-6cfd981c90545313155d1f43c3ed23a5', serviceName='consumer', serviceTags=[], createIndex=275, modifyIndex=278}]}]
SpringCloud-Consul的更多相关文章
- SpringCloud+Consul 服务注册与服务发现
SpringCloud+Consul 服务注册与服务发现 1. 服务注册: 在Spring.factories有一段: # Discovery Client Configuration org.spr ...
- SpringCloud + Consul服务注册中心 + gateway网关
1 启动Consul 2 创建springcloud-consul项目及三个子模块 2.1 数据模块consul-producer 2.2 数据消费模块consul-consumer 2.3 ga ...
- Spring Cloud Consul入门
1. Consul介绍 Consul是一套开源的分布式服务发现和配置管理系统,支持多数据中心分布式高可用.Consul是HashiCorp( Vagrant的创建者)开发的一个服务发现与配置项目,用G ...
- springcloud微服务实战:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin
相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展.会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新 ...
- consul 小結
Consul Config 使用Git做版本控制的实现 https://segmentfault.com/a/1190000013807641 服务发现 - consul 的介绍.部署和使用 http ...
- 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)
[原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...
- SOFARPC模式下的Consul注册中心
Consul大家不陌生,就是和Zookeeper.Nacos一伙的,能够作为微服务基础架构的注册中心,算是比较成熟的组件,和Springcloud集成顺滑, 考虑到Eureka已经停止更新,所以有必要 ...
- 集成Spring-Boot与gRPC,grpc-spring-boot-starter
项目地址:grpc-spring-boot-starter grpc是一个出身名门的RPC框架,性能高,灵活度高,支持多语言. 支持多语言,如果你的项目在使用多种语言做开发,非常推荐使用. 作为Jav ...
- SpringCloud-Consul开发环境配置
一.consul安装 1.下载:https://www.consul.io/downloads.html: 2.选择版本:本人开发环境是windows,所以选择win64: 3.安装:保存至D:/Sp ...
- 如何组织一场JAVA技能大练兵
近期,公司为了锻炼开发人员技能,举办了一场涵盖多个技术线的技能大练兵,我有幸受邀负责java技术方向的出题和评审工作.下面从以下几个方面回顾下整个过程: 题目设计 程序要求 测试方法 题目设计 题目设 ...
随机推荐
- LVS+Keepalived 高可用群集部署
LVS+Keepalived 高可用群集部署 1.LVS+Keepalived 高可用群集概述 2.LVS+Keepalived高可用群集部署 1.LVS+Keepalived 高可用群集概述: LV ...
- 网络层主要协议与arp欺骗
网络层主要协议与arp欺骗 目录 网络层主要协议与arp欺骗 一.网络层(Network Layer) 1.网络层的功能 2.IP数据报(IP Datagram) 二.网络层的主要协议 1.ICMP协 ...
- Java中继承时静态块,构造块,构造函数的执行顺序
public class Father { static { System.out.println("Father静态块"); } { System.out.println(&qu ...
- R数据分析:数据清洗的思路和核心函数介绍
好多同学把统计和数据清洗搞混,直接把原始数据发给我,做个统计吧,这个时候其实很大的工作量是在数据清洗和处理上,如果数据很杂乱,清洗起来是很费工夫的,反而清洗好的数据做统计分析常常就是一行代码的事情. ...
- Word 模板注入
要实现word模板注入,需要一个被注入的文档,以及一个注入用的模板. 1.创建一个启用宏的模板 打开word,alt+f8创建编辑宏,在Project->Microsoft Word对象 ...
- Linux编译安装升级bash5.1
线上服务器有次做漏洞扫描时,被扫描出有bash漏洞.平时还是比较少遇到有bash的漏洞,好在编译升级比较简单. 测试环境系统:CentOS.Ubuntu 一.下载官网最新bash版本 bash官网下载 ...
- .NET 云原生架构师训练营(权限系统 代码实现 WebApplication)--学习笔记
目录 开发任务 代码实现 开发任务 DotNetNB.Security.Core:定义 core,models,Istore:实现 default memory store DotNetNB.WebA ...
- PostgreSQL VACUUM 之深入浅出 (二)
AUTOVACUUM AUTOVACUUM 简介 PostgreSQL 提供了 AUTOVACUUM 的机制. autovacuum 不仅会自动进行 VACUUM,也会自动进行 ANALYZE,以分析 ...
- Ansible部署K8s集群
目录 检查网络:k8s-check.yaml 连接配置:k8s-conn-cfg.yaml 配置k8s集群dns解析: k8s-hosts-cfg.yaml 配置yum源:k8s-yum-cfg.ya ...
- flag_in_your_hand1
给了两个 文件 index.html 和 一个js文件 ,考察js代码审计能力首先借助浏览器来运行js 程序.用浏览器打开index.html,分析 js 代码: 首先无论在 token 输入框中输入 ...