...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package redis
16
17 import (
18 "context"
19 "crypto/tls"
20 "errors"
21 "fmt"
22 "strings"
23
24 redis "github.com/redis/go-redis/v9"
25 )
26
27 const ProviderType = "redis"
28
29
30 type IndexStorageProvider struct {
31 client *redis.Client
32 }
33
34 func NewProvider(address, port, password string, enableTLS bool, insecureSkipVerify bool) (*IndexStorageProvider, error) {
35 provider := &IndexStorageProvider{}
36 provider.client = redis.NewClient(&redis.Options{
37 Addr: fmt.Sprintf("%v:%v", address, port),
38 Network: "tcp",
39 Password: password,
40 DB: 0,
41 })
42
43
44 if enableTLS {
45 provider.client.Options().TLSConfig = &tls.Config{
46 InsecureSkipVerify: insecureSkipVerify,
47 }
48 }
49 return provider, nil
50 }
51
52
53
54 func (isp *IndexStorageProvider) LookupIndices(ctx context.Context, keys []string) ([]string, error) {
55 if isp.client == nil {
56 return []string{}, errors.New("redis client has not been initialized")
57 }
58 cmds, err := isp.client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
59 for _, key := range keys {
60 pipe.LRange(ctx, strings.ToLower(key), 0, -1)
61 }
62 return nil
63 })
64 if err != nil {
65 return []string{}, fmt.Errorf("redis client: %w", err)
66 }
67 var result []string
68 for _, cmd := range cmds {
69 result = append(result, cmd.(*redis.StringSliceCmd).Val()...)
70 }
71 return result, nil
72 }
73
74
75
76 func (isp *IndexStorageProvider) WriteIndex(ctx context.Context, keys []string, index string) error {
77 if isp.client == nil {
78 return errors.New("redis client has not been initialized")
79 }
80 _, err := isp.client.Pipelined(ctx, func(pipe redis.Pipeliner) error {
81 for _, key := range keys {
82 pipe.LPush(ctx, strings.ToLower(key), index)
83 }
84 return nil
85 })
86 if err != nil {
87 return fmt.Errorf("redis client: %w", err)
88 }
89 return nil
90 }
91
92
93 func (isp *IndexStorageProvider) Shutdown() error {
94 if isp.client == nil {
95 return nil
96 }
97 return isp.client.Close()
98 }
99
View as plain text