Go 使用 consul 做服务发现



前言

前面一章讲了微服务的一些优点和缺点,那如何做到

一、目标

二、使用步骤

1. 安装 consul

我们可以直接使用官方提供的二进制文件来进行安装部署,其官网地址为 https://www.consul.io/downloads



下载后为可执行文件,在我们开发试验过程中,可以直接使用 consul agent -dev 命令来启动一个单节点的 consul

在启动的打印日志中可以看到 agent: Started HTTP server on 127.0.0.1:8500 (tcp), 我们可以在浏览器直接访问 127.0.0.1:8500 即可看到如下



这里我们的 consul 就启动成功了

2. 服务注册

在网络编程中,一般会提供项目的 IP、PORT、PROTOCOL,在服务治理中,我们还需要知道对应的服务名、实例名以及一些自定义的扩展信息

在这里使用 ServiceInstance 接口来规定注册服务时必须的一些信息,同时用 DefaultServiceInstance 实现

type ServiceInstance interface {

	// return The unique instance ID as registered.
GetInstanceId() string // return The service ID as registered.
GetServiceId() string // return The hostname of the registered service instance.
GetHost() string // return The port of the registered service instance.
GetPort() int // return Whether the port of the registered service instance uses HTTPS.
IsSecure() bool // return The key / value pair metadata associated with the service instance.
GetMetadata() map[string]string
} type DefaultServiceInstance struct {
InstanceId string
ServiceId string
Host string
Port int
Secure bool
Metadata map[string]string
} func NewDefaultServiceInstance(serviceId string, host string, port int, secure bool,
metadata map[string]string, instanceId string) (*DefaultServiceInstance, error) { // 如果没有传入 IP 则获取一下,这个方法在多网卡的情况下,并不好用
if len(host) == 0 {
localIP, err := util.GetLocalIP()
if err != nil {
return nil, err
}
host = localIP
} if len(instanceId) == 0 {
instanceId = serviceId + "-" + strconv.FormatInt(time.Now().Unix(), 10) + "-" + strconv.Itoa(rand.Intn(9000)+1000)
} return &DefaultServiceInstance{InstanceId: instanceId, ServiceId: serviceId, Host: host, Port: port, Secure: secure, Metadata: metadata}, nil
} func (serviceInstance DefaultServiceInstance) GetInstanceId() string {
return serviceInstance.InstanceId
} func (serviceInstance DefaultServiceInstance) GetServiceId() string {
return serviceInstance.ServiceId
} func (serviceInstance DefaultServiceInstance) GetHost() string {
return serviceInstance.Host
} func (serviceInstance DefaultServiceInstance) GetPort() int {
return serviceInstance.Port
} func (serviceInstance DefaultServiceInstance) IsSecure() bool {
return serviceInstance.Secure
} func (serviceInstance DefaultServiceInstance) GetMetadata() map[string]string {
return serviceInstance.Metadata
}

定义接口

在上面规定了需要注册的服务的必要信息,下面定义下服务注册和剔除的方法

type ServiceRegistry interface {
Register(serviceInstance cloud.ServiceInstance) bool Deregister()
}

具体实现

因为 consul 提供了 http 接口来对consul 进行操作,我们也可以使用 http 请求方式进行注册和剔除操作,具体 http 接口文档见 https://www.consul.io/api-docs, consul 默认提供了go 语言的实现,这里直接使用 github.com/hashicorp/consul/api

import (
"errors"
"fmt"
"github.com/hashicorp/consul/api"
"strconv"
"unsafe"
) type consulServiceRegistry struct {
serviceInstances map[string]map[string]cloud.ServiceInstance
client api.Client
localServiceInstance cloud.ServiceInstance
} func (c consulServiceRegistry) Register(serviceInstance cloud.ServiceInstance) bool {
// 创建注册到consul的服务到
registration := new(api.AgentServiceRegistration)
registration.ID = serviceInstance.GetInstanceId()
registration.Name = serviceInstance.GetServiceId()
registration.Port = serviceInstance.GetPort()
var tags []string
if serviceInstance.IsSecure() {
tags = append(tags, "secure=true")
} else {
tags = append(tags, "secure=false")
}
if serviceInstance.GetMetadata() != nil {
var tags []string
for key, value := range serviceInstance.GetMetadata() {
tags = append(tags, key+"="+value)
}
registration.Tags = tags
}
registration.Tags = tags registration.Address = serviceInstance.GetHost() // 增加consul健康检查回调函数
check := new(api.AgentServiceCheck) schema := "http"
if serviceInstance.IsSecure() {
schema = "https"
}
check.HTTP = fmt.Sprintf("%s://%s:%d/actuator/health", schema, registration.Address, registration.Port)
check.Timeout = "5s"
check.Interval = "5s"
check.DeregisterCriticalServiceAfter = "20s" // 故障检查失败30s后 consul自动将注册服务删除
registration.Check = check // 注册服务到consul
err := c.client.Agent().ServiceRegister(registration)
if err != nil {
fmt.Println(err)
return false
} if c.serviceInstances == nil {
c.serviceInstances = map[string]map[string]cloud.ServiceInstance{}
} services := c.serviceInstances[serviceInstance.GetServiceId()] if services == nil {
services = map[string]cloud.ServiceInstance{}
} services[serviceInstance.GetInstanceId()] = serviceInstance c.serviceInstances[serviceInstance.GetServiceId()] = services c.localServiceInstance = serviceInstance return true
} // deregister a service
func (c consulServiceRegistry) Deregister() {
if c.serviceInstances == nil {
return
} services := c.serviceInstances[c.localServiceInstance.GetServiceId()] if services == nil {
return
} delete(services, c.localServiceInstance.GetInstanceId()) if len(services) == 0 {
delete(c.serviceInstances, c.localServiceInstance.GetServiceId())
} _ = c.client.Agent().ServiceDeregister(c.localServiceInstance.GetInstanceId()) c.localServiceInstance = nil
} // new a consulServiceRegistry instance
// token is optional
func NewConsulServiceRegistry(host string, port int, token string) (*consulServiceRegistry, error) {
if len(host) < 3 {
return nil, errors.New("check host")
} if port <= 0 || port > 65535 {
return nil, errors.New("check port, port should between 1 and 65535")
} config := api.DefaultConfig()
config.Address = host + ":" + strconv.Itoa(port)
config.Token = token
client, err := api.NewClient(config)
if err != nil {
return nil, err
} return &consulServiceRegistry{client: *client}, nil
}

测试用例

注册服务的代码基本完成,来测试一下

func TestConsulServiceRegistry(t *testing.T) {
host := "127.0.0.1"
port := 8500
registryDiscoveryClient, _ := extension.NewConsulServiceRegistry(host, port, "") ip, err := util.GetLocalIP()
if err != nil {
t.Error(err)
} serviceInstanceInfo, _ := cloud.NewDefaultServiceInstance("go-user-server", "", 8090,
false, map[string]string{"user":"zyn"}, "") registryDiscoveryClient.Register(serviceInstanceInfo) r := gin.Default()
// 健康检测接口,其实只要是 200 就认为成功了
r.GET("/actuator/health", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
err = r.Run(":8090")
if err != nil{
registryDiscoveryClient.Deregister()
}
}

如果成功,则会在 consul 看到 go-user-server 这个服务

3. 服务发现

在服务发现中,一般会需要两个方法

  1. 获取所有的服务列表
  2. 获取指定的服务的所有实例信息

接口定义

type DiscoveryClient interface {

	/**
* Gets all ServiceInstances associated with a particular serviceId.
* @param serviceId The serviceId to query.
* @return A List of ServiceInstance.
*/
GetInstances(serviceId string) ([]cloud.ServiceInstance, error) /**
* @return All known service IDs.
*/
GetServices() ([]string, error)
}

具体实现

来实现一下

type consulServiceRegistry struct {
serviceInstances map[string]map[string]cloud.ServiceInstance
client api.Client
localServiceInstance cloud.ServiceInstance
} func (c consulServiceRegistry) GetInstances(serviceId string) ([]cloud.ServiceInstance, error) {
catalogService, _, _ := c.client.Catalog().Service(serviceId, "", nil)
if len(catalogService) > 0 {
result := make([]cloud.ServiceInstance, len(catalogService))
for index, sever := range catalogService {
s := cloud.DefaultServiceInstance{
InstanceId: sever.ServiceID,
ServiceId: sever.ServiceName,
Host: sever.Address,
Port: sever.ServicePort,
Metadata: sever.ServiceMeta,
}
result[index] = s
}
return result, nil
}
return nil, nil
} func (c consulServiceRegistry) GetServices() ([]string, error) {
services, _, _ := c.client.Catalog().Services(nil)
result := make([]string, unsafe.Sizeof(services))
index := 0
for serviceName, _ := range services {
result[index] = serviceName
index++
}
return result, nil
} // new a consulServiceRegistry instance
// token is optional
func NewConsulServiceRegistry(host string, port int, token string) (*consulServiceRegistry, error) {
if len(host) < 3 {
return nil, errors.New("check host")
} if port <= 0 || port > 65535 {
return nil, errors.New("check port, port should between 1 and 65535")
} config := api.DefaultConfig()
config.Address = host + ":" + strconv.Itoa(port)
config.Token = token
client, err := api.NewClient(config)
if err != nil {
return nil, err
} return &consulServiceRegistry{client: *client}, nil
}

测试用例

func TestConsulServiceDiscovery(t *testing.T) {
host := "127.0.0.1"
port := 8500
token := ""
registryDiscoveryClient, err := extension.NewConsulServiceRegistry(host, port, token)
if err != nil {
panic(err)
} t.Log(registryDiscoveryClient.GetServices()) t.Log(registryDiscoveryClient.GetInstances("go-user-server"))
}

结果

consul_service_registry_test.go:57: [consul go-user-server      ] <nil>

consul_service_registry_test.go:59: [{go-user-server-1602590661-56179 go-user-server 127.0.0.1 8090 false map[user:zyn]}] <nil>

总结

通过使用 consul api 我们可以简单的实现基于 consul 的服务发现,在通过结合 http rpc 就可简单的实现服务的调用,下面一章来简单讲下 go 如何发起 http 请求,为我们做 rpc 做个铺垫

具体代码见 https://github.com/zhangyunan1994/lemon

参考

Go | Go 使用 consul 做服务发现的更多相关文章

  1. 使用Consul做服务发现的若干姿势

    从2016年起就开始接触Consul,使用的主要目的就是做服务发现,后来逐步应用于生产环境,并总结了少许使用经验.最开始使用Consul的人不多,为了方便交流创建了一个QQ群,这两年微服务越来越火,使 ...

  2. Consul做服务发现

    使用Consul做服务发现的若干姿势 https://www.cnblogs.com/bossma/p/9756809.html 从2016年起就开始接触Consul,使用的主要目的就是做服务发现,后 ...

  3. Api网关Kong集成Consul做服务发现及在Asp.Net Core中的使用

    写在前面   Api网关我们之前是用 .netcore写的 Ocelot的,使用后并没有完全达到我们的预期,花了些时间了解后觉得kong可能是个更合适的选择. 简单说下kong对比ocelot打动我的 ...

  4. go-micro使用Consul做服务发现的方法和原理

    go-micro v4默认使用mdns做服务发现.不过也支持采用其它的服务发现中间件,因为多年来一直使用Consul做服务发现,为了方便和其它服务集成,所以还是选择了Consul.这篇文章将介绍go- ...

  5. .NET Core HttpClient+Consul实现服务发现

    简介 随着.NET Core的不断发展与成熟,基于.NET Core实现微服务的解决方案也越来越多.这其中必然需要注册中心,Consul成为了.NET Core实现服务注册与发现的首选.类似的解决方案 ...

  6. 阿里巴巴为什么不用 ZooKeeper 做服务发现?

    阿里巴巴为什么不用 ZooKeeper 做服务发现? http://jm.taobao.org/2018/06/13/%E5%81%9A%E6%9C%8D%E5%8A%A1%E5%8F%91%E7%8 ...

  7. .NET Core HttpClientFactory+Consul实现服务发现

    前言 上篇文章.NET Core HttpClient+Consul实现服务发现提到过,HttpClient存在套接字延迟释放的问题,高并发情况导致端口号被耗尽引起服务器拒绝服务的问题.好在微软意识到 ...

  8. etcd学习(3)-grpc使用etcd做服务发现

    grpc通过etcd实现服务发现 前言 服务注册 服务发现 负载均衡 集中式LB(Proxy Model) 进程内LB(Balancing-aware Client) 独立 LB 进程(Externa ...

  9. 一个故事,一段代码告诉你如何使用不同语言(Golang&C#)提供相同的能力基于Consul做服务注册与发现

    目录 引言 什么是微服务 传统服务 微服务 什么是服务注册与服务发现 为什么要使用不同的语言提供相同的服务能力 服务协调器 服务注册 Golang C#(.NetCore3.1) 服务发现 通过Htt ...

随机推荐

  1. Django 入门介绍

    Django介绍 Django框架是PythonWeb三大主流框架之一,以其功能强大全面而受到众多开发者追捧,现如今Django已经更新到3版本,但是并不推荐使用,更多建议使用1版本. Django版 ...

  2. 判断同名股票是否存在的MyBatis查询函数写法

    在A股中,除非股票退市,六位的股票代号是永不变化的,而名称则可能变化,比如更换主业,更换金主,因经营不善而戴帽等,这时名称都会改变. 因此,从网页上爬取的实时股票信息,需要常常与存在本地数据库里的信息 ...

  3. 11.redis cluster的hash slot算法和一致性 hash 算法、普通hash算法的介绍

    分布式寻址算法 hash 算法(大量缓存重建) 一致性 hash 算法(自动缓存迁移)+ 虚拟节点(自动负载均衡) redis cluster 的 hash slot 算法 一.hash 算法 来了一 ...

  4. Unity接入多个SDK的通用接口开发与资源管理(一)

    每一款游戏都有接入多个SDK的需求.当接入多个SDK时会面临两个问题: (1)代码层面:每个SDK都有调用各自功能的方法,我们需要统一管理每个SDK提供的方法,这样会使每个SDK调用方便,使代码整洁易 ...

  5. js-正则表达式的初步应用(一)

    一.正则表达式是使用单个字符串来描述.匹配一系列符合某个句法规则的字符串搜索模式.注:搜索模式也可用于文本替换 例子1 输出结果  注:(我为了方便在控制台输出,所以结果如下) 例子2 输出结果 上面 ...

  6. DASH流媒体MPD中的segmentTemplate

    SegmentTemplate利用MPD中的属性代入公式计算可以得到相关通配符的数值,来提供给客户端进行相关地址解析.相较于segmentList,使用 SegmentTemplate 的方式,能够很 ...

  7. Docker之使用Dockerfile创建定制化镜像(四)

    Dockerfile简介 镜像的定制实际上就是定制每一层所添加的配置.文件.如果我们可以把每一层修改.安装.构建.操作的命令都写入一个脚本,用这个脚本来构建.定制镜像,那么哪些无法重复的问题.镜像构建 ...

  8. 熬夜23天吃透,九大核心专题,成功收割了阿里、百度、美团3家offer

    前言 今年受疫情影响非常大,春招和金三银四都要比往年来得更迟一些.春招结束之后,我特意把自己的面试经历顺了顺,总结出了不少的经验.对了,这次一共收割了3个大厂offer,分别是蚂蚁金服.美团和网易,特 ...

  9. 记一次由selinux引起的使用cat查看文件报错Permission denied的问题排查

    事件起因:如下 1.在服务器上root用户,定期会生成一个文件,到/tmp目录,如:qq_5201351.txt,给other加上了r读取 2.zabbix端会周期性取这台服务器/tmp/qq_520 ...

  10. 面试官:一个 TCP 连接可以发多少个 HTTP 请求?

      曾经有这么一道面试题:从 URL 在浏览器被被输入到页面展现的过程中发生了什么? 相信大多数准备过的同学都能回答出来,但是如果继续问:收到的 HTML 如果包含几十个图片标签,这些图片是以什么方式 ...