-
Notifications
You must be signed in to change notification settings - Fork 0
/
etcd.go
73 lines (59 loc) · 1.36 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"fmt"
"log"
"sync"
"time"
"go.etcd.io/etcd/clientv3"
)
type DistributedCache struct {
client *clientv3.Client
mutex sync.Mutex
}
func NewDistributedCache() (*DistributedCache, error) {
client, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
return nil, err
}
return &DistributedCache{
client: client,
mutex: sync.Mutex{},
}, nil
}
func (dc *DistributedCache) Get(key string) (string, error) {
dc.mutex.Lock()
defer dc.mutex.Unlock()
resp, err := dc.client.Get(context.Background(), key)
if err != nil {
return "", err
}
if len(resp.Kvs) == 0 {
return "", fmt.Errorf("key %s does not exist in cache", key)
}
return string(resp.Kvs[0].Value), nil
}
func (dc *DistributedCache) Set(key string, value string) error {
dc.mutex.Lock()
defer dc.mutex.Unlock()
_, err := dc.client.Put(context.Background(), key, value)
return err
}
func main() {
dc, err := NewDistributedCache()
if err != nil {
log.Fatal(err)
}
err = dc.Set("foo", "bar")
if err != nil {
log.Fatal(err)
}
val, err := dc.Get("foo")
if err != nil {
log.Fatal(err)
}
fmt.Println(val)
}