-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
109 lines (91 loc) · 2.32 KB
/
client.go
File metadata and controls
109 lines (91 loc) · 2.32 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package kamacache
import (
"context"
"fmt"
"time"
"github.com/sirupsen/logrus"
pb "github.com/youngyangyang04/KamaCache-Go/pb"
clientv3 "go.etcd.io/etcd/client/v3"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type Client struct {
addr string
svcName string
etcdCli *clientv3.Client
conn *grpc.ClientConn
grpcCli pb.KamaCacheClient
}
var _ Peer = (*Client)(nil)
func NewClient(addr string, svcName string, etcdCli *clientv3.Client) (*Client, error) {
var err error
if etcdCli == nil {
etcdCli, err = clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, fmt.Errorf("failed to create etcd client: %v", err)
}
}
conn, err := grpc.Dial(addr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithBlock(),
grpc.WithTimeout(10*time.Second),
grpc.WithDefaultCallOptions(grpc.WaitForReady(true)),
)
if err != nil {
return nil, fmt.Errorf("failed to dial server: %v", err)
}
grpcClient := pb.NewKamaCacheClient(conn)
client := &Client{
addr: addr,
svcName: svcName,
etcdCli: etcdCli,
conn: conn,
grpcCli: grpcClient,
}
return client, nil
}
func (c *Client) Get(group, key string) ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resp, err := c.grpcCli.Get(ctx, &pb.Request{
Group: group,
Key: key,
})
if err != nil {
return nil, fmt.Errorf("failed to get value from kamacache: %v", err)
}
return resp.GetValue(), nil
}
func (c *Client) Delete(group, key string) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
resp, err := c.grpcCli.Delete(ctx, &pb.Request{
Group: group,
Key: key,
})
if err != nil {
return false, fmt.Errorf("failed to delete value from kamacache: %v", err)
}
return resp.GetValue(), nil
}
func (c *Client) Set(ctx context.Context, group, key string, value []byte) error {
resp, err := c.grpcCli.Set(ctx, &pb.Request{
Group: group,
Key: key,
Value: value,
})
if err != nil {
return fmt.Errorf("failed to set value to kamacache: %v", err)
}
logrus.Infof("grpc set request resp: %+v", resp)
return nil
}
func (c *Client) Close() error {
if c.conn != nil {
return c.conn.Close()
}
return nil
}