SpringCloud中的Consul详解

目录
  • 1. Consul 简介
  • 2. 专业名词
  • 3. Consul 的优势
  • 4. 特性
  • 5. Consul与Eureka的区别
  • 6. Consul 安装
    • 6.1 docker-compose安装
  • 7. Quick Start
    • 7.1 启动consul服务
    • 7.2 创建客户端-provider
      • 7.2.1 引入依赖坐标
      • 7.2.2 配置application.yml
      • 7.2.3 添加测试方法
    • 7.3 创建客户端-comsumer
      • 7.3.1 配置application.yml
      • 7.3.2 添加支持负载均衡的RestTemplate
      • 7.3.3 添加测试方法
    • 7.4 启动

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的文章就介绍到这了,更多相关SpringCloud Consul内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • SpringCloud整合Consul的实现

    下载安装Consul 访问Consul 官网 下载 Consul 的最新版本,我这里是 consul_1.9.1. 这里以 Windows 为例,下载下来是一个 consul_1.9.1_windows_amd64.zip 的压缩包,解压是是一个 consul.exe 的执行文件. 启动Consul cd 到对应的目录下,使用 cmd 启动 Consul cd E:\迅雷下载\consul_1.9.1_windows_amd64 #cmd启动: consul agent -dev # -dev表

  • Springcloud服务注册consul客户端过程解析

    1.版本说明 springboot 2.2.5.RELEASE springcloud Hoxton.SR6 2.依赖 <!--引入consul client依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependen

  • 详解SpringCloud使用Consul做注册中心

    简介: Consul 是一套开源的分布式服务发现和配置管理系统,由 HashiCorp 公司用 Go 语言开发. Consul 支持健康检查,并允许 HTTP 和 DNS 协议调用 API 存储键值对. 命令行超级好用的虚拟机管理软件 vgrant 也是 HashiCorp 公司开发的产品. 一致性协议采用 Raft 算法,用来保证服务的高可用. 使用 GOSSIP 协议管理成员和广播消息, 并且支持 , Consul 提供了微服务中服务注册发现注册,微服务中的分布式配置中心,可以单独使用,也可

  • SpringCloud中的Consul详解

    目录 1. Consul 简介 2. 专业名词 3. Consul 的优势 4. 特性 5. Consul与Eureka的区别 6. Consul 安装 6.1 docker-compose安装 7. Quick Start 7.1 启动consul服务 7.2 创建客户端-provider 7.2.1 引入依赖坐标 7.2.2 配置application.yml 7.2.3 添加测试方法 7.3 创建客户端-comsumer 7.3.1 配置application.yml 7.3.2 添加支持

  • SpringCloud应用骨架开发详解

    我们每做一个新项目,通常都是从另一个项目把代码拷贝过来,然后在其上做开发.但是这种模式的一个比较大的问题就是会有很多上个项目的遗留代码.因此,开发一个公共的应用骨架系统,在开始其他新项目时,从这个骨架系统开始开发,是一个很好的选择. 我们首先需要创建一个SpringBoot工程,我们可以使用:https://start.spring.io/ 如下所所: 上图中比较关键的是从页面右侧"Add Dependencies"按钮弹出的列表中选择"Spring Web".网站

  • Golang使用Consul详解

    目录 常用指令 常用功能 定义服务 服务管理 服务健康检查 go使用官方api包来定义服务\查询服务 常用指令 agent指令 -bind=0.0.0.0 指定consul所在机器的ip地址 -http-port 指定web接口服务端口 -client 指定哪些机器可以访问consul, 0.0.0.0表示所有机器 -data-dir=path 指定服务数据文件存储位置 -dev 开发者模式,直接以默认模式启动consul -node=hostname 服务发现的名字 -rejoin consu

  • SpringCloud Feign高级配置详解

    目录 1.Feign对负载均衡的支持 2.Feign对熔断器的支持 3.Feign对请求压缩和响应压缩的支持 4.Feign的日志级别配置 1.Feign对负载均衡的支持 Feign 本身已经集成了Ribbon依赖和自动配置,因此我们不需要额外引入依赖,可以通过 ribbon.xx 来进行全局配置,也可以通过服务名.ribbon.xx 来对指定服务进行细节配置配置(参考之前,此处略) Feign默认的请求处理超时时长1s,有时候我们的业务确实执行的需要一定时间,那么这个时候,我们就需要调整请求处

  • SpringCloud Ribbon与OpenFeign详解如何实现服务调用

    目录 Ribbon 初识Ribbon Ribbon是什么 Ribbon能干什么 使用Ribbon实现负载均衡 RestTemplate三步走 负载均衡算法 轮询算法 OpenFeign 初识OpenFeign 什么是OpenFeign 如何使用OpenFeign OpenFeign超时控制 OpenFeign日志打印 Ribbon 初识Ribbon Ribbon是什么   Ribbon是Netflix发布的开源项目,主要功能是提供对客户端进行负载均衡算法的一套工具,将Netflix的中间层服务连

  • SpringCloud Gateway路由组件详解

    目录 简介 核心概念 具体示例 GlobalFilter 简介   Gateway是SpringCloud Alibaba中的路由组件(前身是Zuul),作为浏览器端请求的统一入口.当项目采用微服务模式时,若包含了路由模块,浏览器端的请求都不会直接请求含有业务逻辑的各个业务模块,而是请求这个路由模块,然后再由它来转发到各个业务模块去. 核心概念   Gateway中的三个核心概念:路由.断言(Predicate).过滤器.   路由:由唯一id.目的url.断言和过滤组成   断言:即路由规则,

  • 微服务之注册中心和配置中心Consul详解

    目录 概述 注册中心 注册中心选型 CAP原理 Consul介绍 Consul Raft算法 Consul 基本使用 注册服务 概述 上篇说到构建良好的架构,依托于基础设施建设(自动化测试.自动化部署.服务监控,服务发现.配置中心等等),决定成败的往往是基础设施建设,所以从搭建一个注册中心和配置中心开始我们新一阶段的启程. 注册中心 注册中心选型 你有没有思考过这样一个问题,为什么会有这么多的注册中心(etcd/ZooKeeper/Consul),选用那个最适合自己,是不是在选用的时候会眼花缭乱

  • Java中的静态内部类详解及代码示例

    1. 什么是静态内部类 在Java中有静态代码块.静态变量.静态方法,当然也有静态类,但Java中的静态类只能是Java的内部类,也称为静态嵌套类.静态内部类的定义如下: public class OuterClass { static class StaticInnerClass { ... } } 在介绍静态内部类之前,首先要弄清楚静态内部类与Java其它内部类的区别. 2. 内部类 什么是内部类?将一个类的定义放在另一个类的内部,就是内部类.Java的内部类主要分为成员内部类.局部内部类.

  • Mysql中explain作用详解

    一.MYSQL的索引 索引(Index):帮助Mysql高效获取数据的一种数据结构.用于提高查找效率,可以比作字典.可以简单理解为排好序的快速查找的数据结构. 索引的作用:便于查询和排序(所以添加索引会影响where 语句与 order by 排序语句). 在数据之外,数据库还维护着满足特定查找算法的数据结构,这些数据结构以某种方式引用数据.这样就可以在这些数据结构上实现高级查找算法.这些数据结构就是索引. 索引本身也很大,不可能全部存储在内存中,所以索引往往以索引文件的形式存储在磁盘上. 我们

  • linux中 pmap 命令详解

    通过查看帮助,返回了如下信息: Usage: pmap [options] pid [pid ...] Options: -x, --extended show details -X show even more details WARNING: format changes according to /proc/PID/smaps -XX show everything the kernel provides -c, --read-rc read the default rc -C, --re

随机推荐