-
Notifications
You must be signed in to change notification settings - Fork 3
/
publisher_etcd.go
52 lines (44 loc) · 1.18 KB
/
publisher_etcd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package grpcx
import (
"context"
"fmt"
"time"
"github.com/coreos/etcd/clientv3"
etcdnaming "github.com/coreos/etcd/clientv3/naming"
"google.golang.org/grpc/naming"
)
type etcdPublisher struct {
prefix string
ttl int64
timeout time.Duration
client *clientv3.Client
resolver *etcdnaming.GRPCResolver
}
func newEtcdPublisher(client *clientv3.Client, prefix string, ttl int64, timeout time.Duration) (Publisher, error) {
return &etcdPublisher{
prefix: prefix,
ttl: ttl,
timeout: timeout,
client: client,
resolver: &etcdnaming.GRPCResolver{
Client: client,
},
}, nil
}
func (p *etcdPublisher) Publish(service string, meta naming.Update) error {
lessor := clientv3.NewLease(p.client)
defer lessor.Close()
ctx, cancel := context.WithTimeout(p.client.Ctx(), p.timeout)
leaseResp, err := lessor.Grant(ctx, p.ttl)
cancel()
if err != nil {
return err
}
_, err = p.client.KeepAlive(p.client.Ctx(), leaseResp.ID)
if err != nil {
return err
}
ctx, cancel = context.WithTimeout(p.client.Ctx(), p.timeout)
defer cancel()
return p.resolver.Update(ctx, fmt.Sprintf("%s/%s", p.prefix, service), meta, clientv3.WithLease(clientv3.LeaseID(leaseResp.ID)))
}