一、概述

consul是google开源的一个使用go语言开发的服务发现、配置管理中心服务。内置了服务注册与发现框 架、分布一致性协议实现、健康检查、Key/Value存储、多数据中心方案,不再需要依赖其他工具(比如ZooKeeper等)。服务部署简单,只有一个可运行的二进制的包。每个节点都需要运行agent,他有两种运行模式server和client。每个数据中心官方建议需要3或5个server节点以保证数据安全,同时保证server-leader的选举能够正确的进行。

@client

CLIENT表示consul的client模式,就是客户端模式。是consul节点的一种模式,这种模式下,所有注册到当前节点的服务会被转发到SERVER,本身是不持久化这些信息。

@server

SERVER表示consul的server模式,表明这个consul是个server,这种模式下,功能和CLIENT都一样,唯一不同的是,它会把所有的信息持久化的本地,这样遇到故障,信息是可以被保留的。

@server-leader

中间那个SERVER下面有LEADER的字眼,表明这个SERVER是它们的老大,它和其它SERVER不一样的一点是,它需要负责同步注册的信息给其它的SERVER,同时也要负责各个节点的健康监测。

@raft

server节点之间的数据一致性保证,一致性协议使用的是raft,而zookeeper用的paxos,etcd采用的也是taft。

@服务发现协议

consul采用http和dns协议,etcd只支持http

@服务注册

consul支持两种方式实现服务注册,一种是通过consul的服务注册http API,由服务自己调用API实现注册,另一种方式是通过json个是的配置文件实现注册,将需要注册的服务以json格式的配置文件给出。consul官方建议使用第二种方式。

@服务发现

consul支持两种方式实现服务发现,一种是通过http API来查询有哪些服务,另外一种是通过consul agent 自带的DNS(8600端口),域名是以NAME.service.consul的形式给出,NAME即在定义的服务配置文件中,服务的名称。DNS方式可以通过check的方式检查服务。

@服务间的通信协议

Consul使用gossip协议管理成员关系、广播消息到整个集群,他有两个gossip  pool(LAN pool和WAN pool),LAN pool是同一个数据中心内部通信的,WAN pool是多个数据中心通信的,LAN pool有多个,WAN pool只有一个。

二、consul集群搭建

1)安装

首先去官网现在合适的consul包:https://www.consul.io/downloads.html

安装直接下载zip包,解压后只有一个可执行的文件consul,将consul添加到系统的环境变量里面。

#unzip consul_1.2.3_linux_amd64.zip

#cp -a consul  /usr/bin

#consul

Usage: consul [--version] [--help] <command> [<args>]Available commands are:agent          Runs a Consul agentcatalog        Interact with the catalogconnect        Interact with Consul Connectevent          Fire a new eventexec           Executes a command on Consul nodesforce-leave    Forces a member of the cluster to enter the "left" stateinfo           Provides debugging information for operators.intention      Interact with Connect service intentionsjoin           Tell Consul agent to join clusterkeygen         Generates a new encryption keykeyring        Manages gossip layer encryption keyskv             Interact with the key-value storeleave          Gracefully leaves the Consul cluster and shuts downlock           Execute a command holding a lockmaint          Controls node or service maintenance modemembers        Lists the members of a Consul clustermonitor        Stream logs from a Consul agentoperator       Provides cluster-level tools for Consul operatorsreload         Triggers the agent to reload configuration filesrtt            Estimates network round trip time between nodessnapshot       Saves, restores and inspects snapshots of Consul server statevalidate       Validate config files/directoriesversion        Prints the Consul versionwatch          Watch for changes in Consul

输入consul,出现上面的内容证明安装成功。

2)启动

consul必须启动agent才能使用,有两种启动模式server和client,还有一个官方自带的ui。server用与持久化服务信息,集群官方建议3或5个节点。client只用与于server交互。ui可以查看集群情况的。

server:cn1:#consul agent  -bootstrap-expect 2  -server   -data-dir /data/consul0 -node=cn1 -bind=192.168.1.202 -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1 cn2:#consul agent    -server  -data-dir /data/consul0 -node=cn2 -bind=192.168.1.201 -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1  -join 192.168.1.202cn3:#consul agent  -server  -data-dir /data/consul0 -node=cn3 -bind=192.168.1.200 -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1  -join 192.168.1.202

参数解释:

-bootstrap-expect:集群期望的节点数,只有节点数量达到这个值才会选举leader。

-server: 运行在server模式

-data-dir:指定数据目录,其他的节点对于这个目录必须有读的权限

-node:指定节点的名称

-bind:为该节点绑定一个地址

-config-dir:指定配置文件,定义服务的,默认所有一.json结尾的文件都会读

-enable-script-checks=true:设置检查服务为可用

-datacenter: 数据中心没名称,

-join:加入到已有的集群中

client:#consul agent   -data-dir /data/consul0 -node=cn4 -bind=192.168.1.199 -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1  -join 192.168.1.202

client节点可以有多个,自己根据服务指定即可。

ui:#consul agent  -ui  -data-dir /data/consul0 -node=cn4 -bind=192.168.1.198  -client 192.168.1.198   -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1  -join 192.168.1.202

-ui:使用自带的ui,

-ui-dir:指定ui的目录,使用自己定义的ui

-client:指定web  ui、的监听地址,默认127.0.0.1只能本机访问。

集群创建完成后:

使用一些常用的命令检查集群的状态:

#consul  info

可以在raft:stat看到此节点的状态是Fllower或者leader

#consul membersNode Address Status Type Build Protocol DC Segment
cn1 192.168.1.202:8301 alive server 1.0.2 2 dc1 <all>
cn2 192.168.1.201:8301 alive server 1.0.2 2 dc1 <all>
cn3 192.168.1.200:8301 alive client 1.0.2 2 dc1 <default>

新加入一个节点有几种方式;

1、这种方式,重启后不会自动加入集群#consul  join  192.168.1.2022、#在启动的时候使用-join指定一个集群#consul agent  -ui  -data-dir /data/consul0 -node=cn4 -bind=192.168.1.198 -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1  -join 192.168.1.2023、使用-startjoin或-rejoin#consul agent  -ui  -data-dir /data/consul0 -node=cn4 -bind=192.168.1.198 -config-dir /etc/consul.d -enable-script-checks=true  -datacenter=dc1  -rejoin

访问ui:

http://192.168.1.198:8500/ui

端口:

8300:consul agent服务relplaction、rpc(client-server)

8301:lan gossip

8302:wan gossip

8500:http api端口

8600:DNS服务端口

3)服务注册

采用的是配置文件的方式,(官方推荐)首先创建一个目录用于存放定义服务的配置文件

#mkdir /etc/consul.d/

启动服务的时候要使用-config-dir 参数指定。

下面给出一个服务定义:

#cat web.json

{"service":{"name":"web","tags":["rails"],"port":80,"check":{"name":"ping","script":"curl -s localhost:80","interval":"3s"}}
}

如果这样启动consul后,会发现consul的日志里面一直报错,因为我们没有启动80端口的服务,下面给出我写的一个go程序:

#cat  web.go

package main
import ("io""log""net/http""strconv""fmt"
)
var iCnt  int = 0;func helloHandler(w http.ResponseWriter, r*http.request)  {iCnt++;str :="Hell eorld ! friend("+ strconv.Itoa(iCnt)+")"io.WriteString(w,str)fmt.Println(str)
}func main(){ht :=http.HanderFunc(helloHandler)if ht != nil {http.Handle("/hello",ht)}err := http.ListenAndServe(":80",nil)if err != nil{log.Fatal("ListenAndserve:",err.Error())}
}

#需要一个goalong的环境:#go  build -o  web  web.go#./web此时就可以在没有运行web服务的机器上面执行DNS查询:# dig @127.0.0.1 -p 8600 web.service.consul SRV;; ANSWER SECTION:
web.service.consul. 0 IN SRV 1 1 80 cn2.node.dc1.consul.
web.service.consul. 0 IN SRV 1 1 80 cn3.node.dc1.consul.;; ADDITIONAL SECTION:
cn2.node.dc1.consul. 0 IN A 192.168.1.201
cn2.node.dc1.consul. 0 IN TXT "consul-network-segment="
cn3.node.dc1.consul. 0 IN A 192.168.1.200
cn3.node.dc1.consul. 0 IN TXT "consul-network-segment=";; Query time: 17 msec
;; SERVER: 127.0.0.1#8600(127.0.0.1)
;; WHEN: 四 1月 04 14:39:32 CST 2018
;; MSG SIZE rcvd: 229

可以看到服务已经注册到集群里面了。

使用dns查询,默认域名格式NAME.service.consul,NAME就是web.json里面定义的service的name。可以自己指定域和端口:-domain、-dns-port 53

为了方便使用consul集群的注册使用,所以写了一个三节点client的注册脚本,方便统一注册服务和管理。还利用到了nfs,将服务文件共享到集群。

#!/usr/bin/env python
#encoding: utf8
#decription: registered a service to consul
from subprocess import call
import syshosts = {"b1":"10.10.1.01:8500","b2":"10.10.7.1:8500","b3":"10.10.8.21:8500"}def consul_relaod():if (len(sys.argv) != 2) or sys.argv[1] == '-h':print(("Usage: {0} [option] :{1} ,if you wang update all of them,you must use 'all'").format(sys.argv[0],hosts.keys()))sys.exit()elif(sys.argv[1] == 'all'):for i in hosts.keys():call(("consul reload -http-addr {}").format(hosts[i]),shell=True)else:call(("consul reload -http-addr {}").format(hosts[sys.argv[1]]),shell=True)if __name__ == '__main__':consul_relaod()

hosts是client节点列表。可以只注册其中的一个节点,输入hosts中对应的key,也可以输入all,注册到所有节点;nfs共享的是/etc/consul.d目录。

4)健康检查

check使用来做服务的健康检查的,可以拥有多个,也可以不使用支持多种方式检查。check必须是script或者TTL类型的,如果是script类型则script和interval变量必须被提供,如果是TTL类型则ttl变量必须被提供。script是consul主动去检查服务的健康状况,ttl是服务主动向consul报告自己的状况。

script check:{"check":{"id": mutil-memory,"name": "memory utilization","tags": ["system"],"script": "/etc/init.d/check_memory.py","interval": "10s","timeout": "1s"}}http check:{"check": {"id": "api","name": "HTTP API  500","http": "http://loclhost:500/health","interval": "10s","timeout": "1s"}}tcp  check:{"check": {"id": "ssh","name": "ssh TCP 26622","tcp": "localhost:26622","interval": "10s","timeout": "1s"}}ttl  check:{"check": {"id": "web-app","name": "Web APP status","notes": "Web APP does a curl  internally every 10 seconds","ttl": "30s"}}

三、更新consul版本为最新版本1.2.3.

版本更新特性:

https://github.com/hashicorp/consul/blob/v1.2.3/CHANGELOG.md

FEATURES:agent: New Cloud Auto-join provider: Kubernetes (K8S) [GH-4635]
http: Added support for "Authorization: Bearer" head in addition to the X-Consul-Token header. [GH-4483]
dns: Added a way to specify SRV weights for each service instance to allow weighted DNS load-balancing. [GH-4198]
dns: Include EDNS-ECS options in EDNS responses where appropriate: see RFC 7871 [GH-4647]
IMPROVEMENTS:ui: Switch to fullscreen layout for lists and detail, left aligned forms [GH-4435]
connect: TLS certificate readiness now performs x509 certificate verification to determine whether the cert is usable. [GH-4540]
ui: The syntax highlighting/code editor is now on by default [GH-4651]
ui: Fallback to showing Node.Address if Service.Address is not set [GH-4579]

ui较之前有很大改变:

微服务之consul(一)相关推荐

  1. 微服务之 consul

    标题 1. 微服务之 consul 1. 什么是 consul 1.1. About HashiCorp 1.2. Consul vs. ZooKeeper, doozerd, etcd 2. 基础概 ...

  2. 从零开始部署基于阿里容器云的微服务(consul+registrator+template)(一)

    长话短说,本文旨在记录基于阿里容器云的微服务部署过程,让大家对阿里容器云的使用,微服务的部署有一个整体认识.这个话题我会分几篇文章阐述,由浅入深,部署由笨拙到灵巧,大家一起学习,进步!今天我们说说来看 ...

  3. 微服务 - 搭建Consul集群服务,Consul配置中心

    传统配置文件的弊端 静态化配置,例如env文件 配置文件无法区分环境 配置文件过于分散 历史版本无法查看 配置中心如何解决的呢?配置中心的思路是把项目中的配置参数全部放在一个集中的地方来管理,并提供一 ...

  4. 微服务之consul(一) - 诗码者 - 博客园

    一.概述 consul是google开源的一个使用go语言开发的服务发现.配置管理中心服务.内置了服务注册与发现框 架.分布一致性协议实现.健康检查.Key/Value存储.多数据中心方案,不再需要依 ...

  5. (4).NET CORE微服务 Micro-Service ---- Consul服务发现和消费

    上一章说了  Consul服务注册  现在我要连接上Consul里面的服务 请求它们的API接口 应该怎么做呢? 1.找Consul要一台你需要的服务器 1.1 获取Consul下的所有注册的服务 u ...

  6. Java之 Spring Cloud 微服务的 SpringCloud Config 配置中心(第四个阶段)【二】【SpringBoot项目实现商品服务器端调用】

    SpringCloud学习目录点击跳转对应的文章 Java之 Spring Cloud 微服务搭建(第一个阶段)[一][SpringBoot项目实现商品服务器端是调用] Java之 Spring Cl ...

  7. 爱奇艺号基于Prometheus的微服务应用监控实践

    前 言 微服务架构是目前各大互联网公司普遍采用的软件架构方式.在微服务架构中,系统被拆分为多个小的.相互独立的服务,这些服务运行在自己的进程中,可以独立的开发和部署.在业务快速变化时,微服务单一职责. ...

  8. go语言微服务项目,高级篇--03go-mirco框架-gin框架-mvc-REST-Session

    go-Micro 框架 创建 micro 服务 命令:micro new --type srv test66 框架默认自带服务发现:mdns. 使用consul服务发现: 1. 初始consul服务发 ...

  9. 微服务架构:注册中心 ZooKeeper、Eureka、Consul 、Nacos 对比!

    点击上方蓝色"方志朋",选择"设为星标" 回复"666"获取独家整理的学习资料! 前言 服务注册中心本质上是为了解耦服务提供者和服务消费者. ...

最新文章

  1. java和php哪个运行更快,java和php哪个入门快?-php教程
  2. 设置让TortoiseGit记住账号和密码
  3. C++和Rust_【Rust水群夜话】盘点Rust 官方团队2019年进展
  4. 树形动规_(战略游戏)
  5. CSS3 渐变: 线性渐变 linear-gradient 和 径向渐变 radial-gradient
  6. Oracle 扩展sysaux,oracle 清理SYSAUX表空间
  7. Qt4_读取和写入文本
  8. [转载]常用正则表达式收集勘误
  9. python指数函数,幂函数
  10. opencv RGB 颜色 灰色图片显示
  11. sqlserver with ties
  12. currentlyFocusedField is deprecated and will be removed in a future release解决方法记录
  13. OKR还是集权制?750亿美金字节跳动的成长秘密
  14. java显示图片缩略图_java中生成图片的缩略图
  15. ILSpy反编译C#web程序
  16. 网络渗透试验一实验报告
  17. php自定义函数全局声明,thinkphp3.2自定义函数全局功能函数,模板自定义函数
  18. ChatGPT全球爆火,究竟有何特别之处?
  19. 吃掉棉花糖就等于吃掉未来
  20. 有赚一亿的欲望,却只有一天的耐心。

热门文章

  1. Linux下C程序的链接过程
  2. 天下会 - 搜索实战系列之视频
  3. 关于写博客的原因以及一点个人说明。
  4. 欧冠淘汰赛第二回合!我厂生死战!!
  5. CodeForces - 1579G Minimal Coverage(dp)
  6. CodeForces - 1567C Carrying Conundrum(思维/状压)
  7. Web开发-Django初识及实战
  8. JavaScript栈的实现
  9. HDU4302(map的用法)
  10. Floyd求传递闭包