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的区别

  1. 一致性 Consul强一致性(CP)

    • 服务注册相比Eureka会稍慢一些。因为Consul的raft协议要求必须过半数的节点都写入成功才认 为注册成功
    • Leader挂掉时,重新选举期间整个consul不可用。保证了强一致性但牺牲了可用性。
  2. Eureka保证高可用和最终一致性(AP)

    • 服务注册相对要快,因为不需要等注册信息replicate到其他节点,也不保证注册信息是否 replicate成功

    • 当数据出现不一致时,虽然A, B上的注册信息不完全相同,但每个Eureka节点依然能够正常对外提 供服务,这会出现查询服务信息时如果请求A查不到,但请求B就能查到。如此保证了可用性但牺牲了一致性。

6. Consul 安装

consul docker-hub

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的更多相关文章

  1. SpringCloud+Consul 服务注册与服务发现

    SpringCloud+Consul 服务注册与服务发现 1. 服务注册: 在Spring.factories有一段: # Discovery Client Configuration org.spr ...

  2. SpringCloud + Consul服务注册中心 + gateway网关

    1  启动Consul 2  创建springcloud-consul项目及三个子模块 2.1 数据模块consul-producer 2.2 数据消费模块consul-consumer 2.3 ga ...

  3. Spring Cloud Consul入门

    1. Consul介绍 Consul是一套开源的分布式服务发现和配置管理系统,支持多数据中心分布式高可用.Consul是HashiCorp( Vagrant的创建者)开发的一个服务发现与配置项目,用G ...

  4. springcloud微服务实战:Eureka+Zuul+Feign/Ribbon+Hystrix Turbine+SpringConfig+sleuth+zipkin

    相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展.会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新 ...

  5. consul 小結

    Consul Config 使用Git做版本控制的实现 https://segmentfault.com/a/1190000013807641 服务发现 - consul 的介绍.部署和使用 http ...

  6. 【原创】SpringBoot & SpringCloud 快速入门学习笔记(完整示例)

    [原创]SpringBoot & SpringCloud 快速入门学习笔记(完整示例) 1月前在系统的学习SpringBoot和SpringCloud,同时整理了快速入门示例,方便能针对每个知 ...

  7. SOFARPC模式下的Consul注册中心

    Consul大家不陌生,就是和Zookeeper.Nacos一伙的,能够作为微服务基础架构的注册中心,算是比较成熟的组件,和Springcloud集成顺滑, 考虑到Eureka已经停止更新,所以有必要 ...

  8. 集成Spring-Boot与gRPC,grpc-spring-boot-starter

    项目地址:grpc-spring-boot-starter grpc是一个出身名门的RPC框架,性能高,灵活度高,支持多语言. 支持多语言,如果你的项目在使用多种语言做开发,非常推荐使用. 作为Jav ...

  9. SpringCloud-Consul开发环境配置

    一.consul安装 1.下载:https://www.consul.io/downloads.html: 2.选择版本:本人开发环境是windows,所以选择win64: 3.安装:保存至D:/Sp ...

  10. 如何组织一场JAVA技能大练兵

    近期,公司为了锻炼开发人员技能,举办了一场涵盖多个技术线的技能大练兵,我有幸受邀负责java技术方向的出题和评审工作.下面从以下几个方面回顾下整个过程: 题目设计 程序要求 测试方法 题目设计 题目设 ...

随机推荐

  1. Java执行cmd命令、bat脚本、linux命令,shell脚本等

    1.Windows下执行cmd命令 如复制 D:\tmp\my.txt 到D:\tmp\my_by_only_cmd.txt 现文件如图示: 执行代码: private static void run ...

  2. Python语言编程基础

    Python 技能目标 理解编程基本原理和思想 掌握python语言的基础语法 能够使用python进行基本的开发工作 熟练使用项目开发IDE:eclipse,PyDev 能够使用Python开发简单 ...

  3. CopyOnWriteList揭秘

    List的并发容器-CopyOnWriteList Vector和SynchronizedList ArrayList是用来代替Vector,Vector是线程安全的容器,因为它在方法上都加上了syn ...

  4. 10、Linux基础--find、正则、文本过滤器grep

    笔记 1.晨考 1.每个月的3号.5号和15号,而且这天是星期六时执行 00 00 3,5,15 * 6 2.每天的3点到15点,每隔3分钟执行一次 */3 3-15 * * * 3.每周六早上2点半 ...

  5. Solution -「LOCAL」人口迁徙

    \(\mathcal{Description}\)   \(n\) 个点,第 \(i\) 个点能走向第 \(d_i\) 个点,但从一个点出发至多走 \(k\) 步.对于每个点,求有多少点能够走到它. ...

  6. 前端程序员初步认识 docker

    初步认识 docker 为什么要学习 docker 有同学说他开发工作中有两大神器,一个是 vim 编辑器,另一个就是 Docker. 什么是 docker Docker 是一个开源的应用容器引擎. ...

  7. uniapp上传图片转base64码案例

    uni.chooseImage({ count: 9, success: res => { this.imageList = this.imageList.concat(res.tempFile ...

  8. 北大博士生提出CAE,下游任务泛化能力优于何恺明MAE

    大家好,我是对白. 何恺明时隔两年发一作论文,提出了一种视觉自监督学习新范式-- 用掩蔽自编码器MAE,为视觉大模型开路. 这一次,北大博士生提出一个新方法CAE,在其下游任务中展现的泛化能力超过了M ...

  9. loadrunner查看并发产生的错误日志

    有些测试朋友在用lr的时候,遇到错误,不知道怎么从客户端看日志,下面我简单介绍下. 设置日志:仅错误的时候发送 压测过程中报错,点击放大镜 有170个虚拟用户报这个错 下面可以看到虚拟用户编号 在虚拟 ...

  10. AWVS漏洞扫描教程之扫描方式

    实验目的 掌握AWVS的基本用法. 实验原理 Acunetix Web Vulnerability Scanner是一个网站及服务器漏洞扫描软件. 实验内容 对Web站点进行安全测试. 实验环境描述 ...