forked from chrobson/RedisCache
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.go
More file actions
61 lines (46 loc) · 1.04 KB
/
redis.go
File metadata and controls
61 lines (46 loc) · 1.04 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
package main
import (
"bytes"
"context"
"encoding/gob"
"os"
"time"
"github.com/go-redis/redis/v8"
)
type Client struct {
client *redis.Client
}
func NewRedis() (*Client, error) {
client := redis.NewClient(&redis.Options{
Addr: os.Getenv("REDIS"),
DB: 0,
DialTimeout: 100 * time.Millisecond,
ReadTimeout: 100 * time.Millisecond,
})
if _, err := client.Ping(context.Background()).Result(); err != nil {
return nil, err
}
return &Client{
client: client,
}, nil
}
func (c *Client) GetName(ctx context.Context, nconst string) (Person, error) {
cmd := c.client.Get(ctx, nconst)
cmdb, err := cmd.Bytes()
if err != nil {
return Person{}, err
}
b := bytes.NewReader(cmdb)
var res Person
if err := gob.NewDecoder(b).Decode(&res); err != nil {
return Person{}, err
}
return res, nil
}
func (c *Client) SetName(ctx context.Context, n Person) error {
var b bytes.Buffer
if err := gob.NewEncoder(&b).Encode(n); err != nil {
return err
}
return c.client.Set(ctx, n.Id, b.Bytes(), 25*time.Second).Err()
}