/
redis.go
54 lines (48 loc) · 1.18 KB
/
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
package data
import (
"context"
"fmt"
"strconv"
"strings"
"github.com/go-redis/redis/v8"
"github.com/starryrbs/kfan/app/history/service/internal/biz"
)
func historyKey(userId int64) string {
return fmt.Sprintf("histort-%d", userId)
}
func (h *historyRepo) GetHistoryCache(ctx context.Context, userId int64) ([]*biz.History, error) {
results, err := h.data.rdb.ZRangeArgsWithScores(ctx, redis.ZRangeArgs{
Key: historyKey(userId),
Start: 0,
Stop: 10,
Rev: true,
}).Result()
if err != nil {
return nil, err
}
histories := make([]*biz.History, 0)
for _, z := range results {
vs := strings.Split(z.Member.(string), "-")
objId, err := strconv.ParseInt(vs[1], 10, 64)
if err != nil {
return nil, err
}
histories = append(histories, &biz.History{
ObjId: objId,
ObjType: vs[0],
UserId: userId,
CreateAt: z.Score,
})
}
return histories, nil
}
func (h historyRepo) SaveHistoryCache(ctx context.Context, history *biz.History) error {
_, err := h.data.rdb.ZAdd(ctx, historyKey(history.UserId), &redis.Z{
Score: history.CreateAt,
Member: fmt.Sprintf("%s-%d", history.ObjType, history.ObjId),
}).Result()
if err != nil {
return err
}
return err
}