forked from evangwt/grc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gormcache_redis.go
62 lines (52 loc) · 1.7 KB
/
gormcache_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
/*
Copyright 2023 evangwt
Copyright 2023 Rodolfo González González for the modifications in
this fork.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package gormcache
import (
"context"
"encoding/json"
"errors"
"time"
redis "github.com/redis/go-redis/v9"
)
// RedisClient is a wrapper for go-redis client
type RedisClient struct {
client *redis.Client
}
// NewRedisClient returns a new RedisClient instance
func NewRedisClient(client *redis.Client) *RedisClient {
return &RedisClient{
client: client,
}
}
// Get gets value from redis by key using json encoding/decoding
func (r *RedisClient) Get(ctx context.Context, key string) (interface{}, error) {
data, err := r.client.Get(ctx, key).Bytes()
if err != nil {
if errors.Is(err, redis.Nil) {
return nil, nil
}
return nil, err
}
//log.Printf("get cache, key: %v", key)
return data, nil
}
// Set sets value to redis by key with ttl using json encoding/decoding
func (r *RedisClient) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error {
data, err := json.Marshal(value) // encode value to json bytes using json encoding/decoding
if err != nil {
return err
}
return r.client.Set(ctx, key, data, ttl).Err()
}