/
redis.go
53 lines (41 loc) · 961 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
package utils
import (
"bytes"
"compress/gzip"
"context"
"time"
"github.com/redis/go-redis/v9"
)
// 压缩存储
func RedisGzipSet(ctx context.Context, redisClient *redis.Client, key string, data []byte, expired time.Duration) error {
buf := new(bytes.Buffer)
gzipW := gzip.NewWriter(buf)
gzipW.Write(data)
gzipW.Close()
zipData := buf.Bytes()
_, err := redisClient.Set(context.Background(), key, zipData, time.Minute).Result()
return err
}
//读取并解压
func RedisGzipGet(ctx context.Context, redisClient *redis.Client, key string) ([]byte, error) {
s, err := redisClient.Get(context.Background(), key).Bytes()
if nil != err {
return nil, err
}
gzipR, err := gzip.NewReader(bytes.NewBuffer(s))
if nil != err {
return nil, err
}
out := new(bytes.Buffer);
bs := make([]byte, len(s))
for {
n,err := gzipR.Read(bs)
if 0 < n {
out.Write(bs[0:n])
}
if nil != err {
break;
}
}
return out.Bytes(), nil
}