成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Go使用consul做服務發現

開發 前端
通過使用 consul api 我們可以簡單的實現基于 consul 的服務發現,在通過結合 http rpc 就可簡單的實現服務的調用,下面一章來簡單講下 go 如何發起 http 請求,為我們做 rpc 做個鋪墊

一、目標

二、使用步驟

1. 安裝 consul

我們可以直接使用官方提供的二進制文件來進行安裝部署,其官網地址為 https://www.consul.io/downloads

 

Go 使用 consul 做服務發現

下載后為可執行文件,在我們開發試驗過程中,可以直接使用 consul agent -dev 命令來啟動一個單節點的 consul

在啟動的打印日志中可以看到 agent: Started HTTP server on 127.0.0.1:8500 (tcp), 我們可以在瀏覽器直接訪問 127.0.0.1:8500 即可看到如下

 

Go 使用 consul 做服務發現

這里我們的 consul 就啟動成功了

2. 服務注冊

在網絡編程中,一般會提供項目的 IP、PORT、PROTOCOL,在服務治理中,我們還需要知道對應的服務名、實例名以及一些自定義的擴展信息

在這里使用 ServiceInstance 接口來規定注冊服務時必須的一些信息,同時用 DefaultServiceInstance 實現

  1. type ServiceInstance interface { 
  2.     // return The unique instance ID as registered. 
  3.     GetInstanceId() string 
  4.     // return The service ID as registered. 
  5.     GetServiceId() string 
  6.     // return The hostname of the registered service instance. 
  7.     GetHost() string 
  8.     // return The port of the registered service instance. 
  9.     GetPort() int    // return Whether the port of the registered service instance uses HTTPS. 
  10.     IsSecure() bool    // return The key / value pair metadata associated with the service instance. 
  11.     GetMetadata() map[string]string 
  12. }type DefaultServiceInstance struct { 
  13.     InstanceId string 
  14.     ServiceId  string 
  15.     Host       string 
  16.     Port       int    Secure     bool    Metadata   map[string]string 
  17. }func NewDefaultServiceInstance(serviceId string, host string, port int, secure bool, 
  18.     metadata map[string]string, instanceId string) (*DefaultServiceInstance, error) { 
  19.     // 如果沒有傳入 IP 則獲取一下,這個方法在多網卡的情況下,并不好用    if len(host) == 0 { 
  20.         localIP, err := util.GetLocalIP()        if err != nil { 
  21.             return nil, err 
  22.         }        host = localIP    }    if len(instanceId) == 0 { 
  23.         instanceId = serviceId + "-" + strconv.FormatInt(time.Now().Unix(), 10) + "-" + strconv.Itoa(rand.Intn(9000)+1000) 
  24.     }    return &DefaultServiceInstance{InstanceId: instanceId, ServiceId: serviceId, Host: host, Port: port, Secure: secure, Metadata: metadata}, nil 
  25. }func (serviceInstance DefaultServiceInstance) GetInstanceId() string { 
  26.     return serviceInstance.InstanceId 
  27. }func (serviceInstance DefaultServiceInstance) GetServiceId() string { 
  28.     return serviceInstance.ServiceId 
  29. }func (serviceInstance DefaultServiceInstance) GetHost() string { 
  30.     return serviceInstance.Host 
  31. }func (serviceInstance DefaultServiceInstance) GetPort() int {    return serviceInstance.Port 
  32. }func (serviceInstance DefaultServiceInstance) IsSecure() bool {    return serviceInstance.Secure 
  33. }func (serviceInstance DefaultServiceInstance) GetMetadata() map[string]string { 
  34.     return serviceInstance.Metadata 

定義接口

在上面規定了需要注冊的服務的必要信息,下面定義下服務注冊和剔除的方法

  1. type ServiceRegistry interface { 
  2.     Register(serviceInstance cloud.ServiceInstance) bool 
  3.     Deregister() 

具體實現

因為 consul 提供了 http 接口來對 consul 進行操作,我們也可以使用 http 請求方式進行注冊和剔除操作,具體 http 接口文檔見 https://www.consul.io/api-docs, consul 默認提供了go 語言的實現,這里直接使用 github.com/hashicorp/consul/api

  1. import ( 
  2.     "errors" 
  3.     "fmt" 
  4.     "github.com/hashicorp/consul/api" 
  5.     "strconv" 
  6.     "unsafe" 
  7. )type consulServiceRegistry struct { 
  8.     serviceInstances     map[string]map[string]cloud.ServiceInstance 
  9.     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 
  10.     if serviceInstance.IsSecure() { 
  11.         tags = append(tags, "secure=true"
  12.     } else { 
  13.         tags = append(tags, "secure=false"
  14.     }    if serviceInstance.GetMetadata() != nil { 
  15.         var tags []string 
  16.         for key, value := range serviceInstance.GetMetadata() { 
  17.             tags = append(tags, key+"="+value) 
  18.         }        registration.Tags = tags    }    registration.Tags = tags    registration.Address = serviceInstance.GetHost()    // 增加consul健康檢查回調函數    check := new(api.AgentServiceCheck)    schema := "http" 
  19.     if serviceInstance.IsSecure() { 
  20.         schema = "https" 
  21.     }    check.HTTP = fmt.Sprintf("%s://%s:%d/actuator/health"schema, registration.Address, registration.Port) 
  22.     check.Timeout = "5s" 
  23.     check.Interval = "5s" 
  24.     check.DeregisterCriticalServiceAfter = "20s" // 故障檢查失敗30s后 consul自動將注冊服務刪除 
  25.     registration.Check = check    // 注冊服務到consul    err := c.client.Agent().ServiceRegister(registration)    if err != nil { 
  26.         fmt.Println(err)        return false 
  27.     }    if c.serviceInstances == nil { 
  28.         c.serviceInstances = map[string]map[string]cloud.ServiceInstance{} 
  29.     }    services := c.serviceInstances[serviceInstance.GetServiceId()]    if services == nil { 
  30.         services = map[string]cloud.ServiceInstance{} 
  31.     }    services[serviceInstance.GetInstanceId()] = serviceInstance    c.serviceInstances[serviceInstance.GetServiceId()] = services    c.localServiceInstance = serviceInstance    return true 
  32. }// deregister a servicefunc (c consulServiceRegistry) Deregister() {    if c.serviceInstances == nil { 
  33.         return 
  34.     }    services := c.serviceInstances[c.localServiceInstance.GetServiceId()]    if services == nil { 
  35.         return 
  36.     }    delete(services, c.localServiceInstance.GetInstanceId())    if len(services) == 0 { 
  37.         delete(c.serviceInstances, c.localServiceInstance.GetServiceId())    }    _ = c.client.Agent().ServiceDeregister(c.localServiceInstance.GetInstanceId())    c.localServiceInstance = nil 
  38. }// new a consulServiceRegistry instance// token is optionalfunc NewConsulServiceRegistry(host string, port int, token string) (*consulServiceRegistry, error) { 
  39.     if len(host) < 3 { 
  40.         return nil, errors.New("check host"
  41.     }    if port <= 0 || port > 65535 { 
  42.         return nil, errors.New("check port, port should between 1 and 65535"
  43.     }    config := api.DefaultConfig() 
  44.     config.Address = host + ":" + strconv.Itoa(port) 
  45.     config.Token = token 
  46.     client, err := api.NewClient(config) 
  47.     if err != nil { 
  48.         return nil, err 
  49.     }    return &consulServiceRegistry{client: *client}, nil 

測試用例

注冊服務的代碼基本完成,來測試一下

  1. func TestConsulServiceRegistry(t *testing.T) { 
  2.     host := "127.0.0.1" 
  3.     port := 8500 
  4.     registryDiscoveryClient, _ := extension.NewConsulServiceRegistry(host, port, ""
  5.     ip, err := util.GetLocalIP()    if err != nil { 
  6.         t.Error(err)    }    serviceInstanceInfo, _ := cloud.NewDefaultServiceInstance("go-user-server""", 8090, 
  7.         false, map[string]string{"user":"zyn"}, ""
  8.     registryDiscoveryClient.Register(serviceInstanceInfo)    r := gin.Default()    // 健康檢測接口,其實只要是 200 就認為成功了 
  9.     r.GET("/actuator/health", func(c *gin.Context) { 
  10.         c.JSON(200, gin.H{ 
  11.             "message""pong"
  12.         }) 
  13.     }) 
  14.     err = r.Run(":8090"
  15.     if err != nil{ 
  16.         registryDiscoveryClient.Deregister() 
  17.     } 

如果成功,則會在 consul 看到 go-user-server 這個服務

3. 服務發現

在服務發現中,一般會需要兩個方法

  • 獲取所有的服務列表
  • 獲取指定的服務的所有實例信息

接口定義

  1. type DiscoveryClient interface { 
  2.     /** 
  3.      * Gets all ServiceInstances associated with a particular serviceId. 
  4.      * @param serviceId The serviceId to query. 
  5.      * @return A List of ServiceInstance. 
  6.      */ 
  7.     GetInstances(serviceId string) ([]cloud.ServiceInstance, error)    /** 
  8.      * @return All known service IDs. 
  9.      */ 
  10.     GetServices() ([]string, error)} 

具體實現

來實現一下

  1. type consulServiceRegistry struct { 
  2.     serviceInstances     map[string]map[string]cloud.ServiceInstance 
  3.     client               api.Client    localServiceInstance cloud.ServiceInstance}func (c consulServiceRegistry) GetInstances(serviceId string) ([]cloud.ServiceInstance, error) { 
  4.     catalogService, _, _ := c.client.Catalog().Service(serviceId, "", nil) 
  5.     if len(catalogService) > 0 { 
  6.         result := make([]cloud.ServiceInstance, len(catalogService)) 
  7.         for index, sever := range catalogService { 
  8.             s := cloud.DefaultServiceInstance{                InstanceId: sever.ServiceID,                ServiceId:  sever.ServiceName,                Host:       sever.Address,                Port:       sever.ServicePort,                Metadata:   sever.ServiceMeta,            }            result[index] = s        }        return result, nil 
  9.     }    return nil, nil 
  10. }func (c consulServiceRegistry) GetServices() ([]string, error) { 
  11.     services, _, _ := c.client.Catalog().Services(nil) 
  12.     result := make([]string, unsafe.Sizeof(services)) 
  13.     index := 0 
  14.     for serviceName, _ := range services { 
  15.         result[index] = serviceName        index++    }    return result, nil 
  16. }// new a consulServiceRegistry instance 
  17. // token is optional 
  18. func NewConsulServiceRegistry(host string, port int, token string) (*consulServiceRegistry, error) { 
  19.     if len(host) < 3 { 
  20.         return nil, errors.New("check host"
  21.     } 
  22.     if port <= 0 || port > 65535 { 
  23.         return nil, errors.New("check port, port should between 1 and 65535"
  24.     } 
  25.     config := api.DefaultConfig() 
  26.     config.Address = host + ":" + strconv.Itoa(port) 
  27.     config.Token = token 
  28.     client, err := api.NewClient(config) 
  29.     if err != nil { 
  30.         return nil, err 
  31.     } 
  32.     return &consulServiceRegistry{client: *client}, nil 

測試用例

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

結果

  1. consul_service_registry_test.go:57: [consul go-user-server      ] <nil> 
  2. 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 做個鋪墊

責任編輯:未麗燕 來源: 今日頭條
相關推薦

2023-06-02 08:33:43

微服務架構服務注冊

2022-01-16 23:10:40

語言服務注冊

2021-07-07 05:46:46

運維監控Prometheus

2017-06-25 13:33:25

Spring Clou微服務架構

2022-01-26 09:36:53

Consul語言微服務

2025-01-20 00:10:00

Go語言Kratos

2018-12-27 09:28:08

Consul服務Server

2021-09-30 08:54:58

prometheus監控遠端服務

2023-07-04 07:45:11

gogRPC服務

2023-04-03 07:17:34

CP集群AP

2023-09-07 23:25:34

微服務服務發現

2015-04-28 15:14:53

云平臺發現服務ZooKeeper

2015-06-03 10:01:56

云平臺發現服務ZooKeeper

2021-01-08 13:52:15

Consul微服務服務注冊中心

2025-01-09 08:32:50

2025-02-04 13:53:18

NixGogRPC

2018-11-22 15:07:17

代碼github程序

2019-12-24 09:39:06

Kubernetes工具微服務

2022-08-14 07:04:44

微服務架構設計模式

2020-06-29 07:58:18

ZooKeeperConsul 注冊中心
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美亚洲日本 | 成人精品一区二区三区中文字幕 | 国产精品久久精品 | 中文字幕国产一区 | 在线免费观看毛片 | 日本一区视频在线观看 | 中文字幕日本一区二区 | 国产xxxx在线 | 成人在线精品视频 | 国产精品久久久久一区二区三区 | 亚洲性网 | 91精品国产色综合久久 | 亚洲网站在线观看 | 亚洲成人精品 | 成人国产精品久久久 | 9久久精品 | 中文字幕1区| 国产精品久久av | 一级特黄网站 | 91在线影院 | 国产精品精品视频一区二区三区 | 日本电影韩国电影免费观看 | 一级毛片视频免费观看 | 91在线影院 | 久久网亚洲 | 欧美日韩视频 | 一区二区三区高清在线观看 | 亚洲经典一区 | 国产一区二区精品在线 | 国产在线观看一区 | av在线视 | 亚洲高清视频一区二区 | 国产羞羞视频在线观看 | 亚洲精品无 | 夜夜爽99久久国产综合精品女不卡 | 91精品国产91久久久久久 | 丁香五月缴情综合网 | 亚洲a视| 九色视频网站 | 免费观看av网站 | 国产福利在线视频 |