-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
86 lines (70 loc) · 1.66 KB
/
proxy.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
74
75
76
77
78
79
80
81
82
83
84
85
86
package kredis
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
type Proxy struct {
ctx context.Context
client *redis.Client
key string
expiresIn time.Duration
}
func NewProxy(key string, opts ...ProxyOption) (*Proxy, error) {
options := ProxyOptions{context: context.Background()}
for _, opt := range opts {
opt(&options)
}
client, namespace, err := getConnection(options.Config())
if err != nil {
return nil, err
}
if namespace != "" {
key = fmt.Sprintf("%s:%s", namespace, key)
}
return &Proxy{
ctx: options.context,
client: client,
key: key,
expiresIn: options.ExpiresIn(),
}, nil
}
// Used when setting defaults
func (p *Proxy) watch(setter func() error) error {
err := p.client.Watch(p.ctx, func(tx *redis.Tx) error {
n, err := tx.Exists(p.ctx, p.key).Result()
if err != nil {
return err
} else if n > 0 { // already exists
return nil
}
return setter()
}, p.key)
if err != nil {
return err
}
return nil
}
func (p *Proxy) Key() string {
return p.key
}
func (p *Proxy) Client() *redis.Client {
return p.client
}
// Get the key's current TTL. Redis is only called if the type was configured
// WithExpiry(). If no expiry is configured, a zero value Duration is returned
func (p *Proxy) TTL() (time.Duration, error) {
if p.expiresIn == 0 {
return time.Duration(0), nil
}
return p.client.TTL(p.ctx, p.key).Result()
}
// Set the key's EXPIRE using the configured expiresIn. If there is no
// value configured, nothing happens.
func (p *Proxy) RefreshTTL() (bool, error) {
if p.expiresIn == 0 {
return false, nil
}
return p.client.Expire(p.ctx, p.key, p.expiresIn).Result()
}