-
Notifications
You must be signed in to change notification settings - Fork 0
/
Redis.go
62 lines (48 loc) · 997 Bytes
/
Redis.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
package main
import (
"fmt"
"log"
"sync"
"github.com/go-redis/redis"
)
type DistributedCache struct {
client *redis.Client
mutex sync.Mutex
}
func NewDistributedCache() *DistributedCache {
client := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
})
return &DistributedCache{
client: client,
mutex: sync.Mutex{},
}
}
func (dc *DistributedCache) Get(key string) (string, error) {
dc.mutex.Lock()
defer dc.mutex.Unlock()
val, err := dc.client.Get(key).Result()
if err == redis.Nil {
return "", fmt.Errorf("key %s does not exist in cache", key)
} else if err != nil {
return "", err
}
return val, nil
}
func (dc *DistributedCache) Set(key string, value string) error {
dc.mutex.Lock()
defer dc.mutex.Unlock()
return dc.client.Set(key, value, 0).Err()
}
func main() {
dc := NewDistributedCache()
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)
}