返回介绍

开发指南 - gRPC命名与发现

发布于 2020-08-31 21:59:41 字数 3983 浏览 1043 评论 0 收藏 0

etcd provides a gRPC resolver to support an alternative name system that fetches endpoints from etcd for discovering gRPC services. The underlying mechanism is based on watching updates to keys prefixed with the service name.

Using etcd discovery with go-grpc

The etcd client provides a gRPC resolver for resolving gRPC endpoints with an etcd backend. The resolver is initialized with an etcd client and given a target for resolution:

  1. import (
  2. "github.com/coreos/etcd/clientv3"
  3. etcdnaming "github.com/coreos/etcd/clientv3/naming"
  4. "google.golang.org/grpc"
  5. )
  6. ...
  7. cli, cerr := clientv3.NewFromURL("http://localhost:2379")
  8. r := &etcdnaming.GRPCResolver{Client: cli}
  9. b := grpc.RoundRobin(r)
  10. conn, gerr := grpc.Dial("my-service", grpc.WithBalancer(b))

Managing service endpoints

The etcd resolver treats all keys under the prefix of the resolution target following a “/“ (e.g., “my-service/“) with JSON-encoded go-grpc naming.Update values as potential service endpoints. Endpoints are added to the service by creating new keys and removed from the service by deleting keys.

Adding an endpoint

New endpoints can be added to the service through etcdctl:

  1. ETCDCTL_API=3 etcdctl put my-service/1.2.3.4 '{"Addr":"1.2.3.4","Metadata":"..."}'

The etcd client’s GRPCResolver.Update method can also register new endpoints with a key matching the Addr:

  1. r.Update(context.TODO(), "my-service", naming.Update{Op: naming.Add, Addr: "1.2.3.4", Metadata: "..."})

Deleting an endpoint

Hosts can be deleted from the service through etcdctl:

  1. ETCDCTL_API=3 etcdctl del my-service/1.2.3.4

The etcd client’s GRPCResolver.Update method also supports deleting endpoints:

  1. r.Update(context.TODO(), "my-service", naming.Update{Op: naming.Delete, Addr: "1.2.3.4"})

Registering an endpoint with a lease

Registering an endpoint with a lease ensures that if the host can’t maintain a keepalive heartbeat (e.g., its machine fails), it will be removed from the service:

  1. lease=`ETCDCTL_API=3 etcdctl lease grant 5 | cut -f2 -d' '`
  2. ETCDCTL_API=3 etcdctl put --lease=$lease my-service/1.2.3.4 '{"Addr":"1.2.3.4","Metadata":"..."}'
  3. ETCDCTL_API=3 etcdctl lease keep-alive $lease

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文