Skip to content

Commit b457386

Browse files
Created seperate Redis module (it would be the redis package for complete project)
1 parent 1a922d4 commit b457386

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

internal/redis/redis.go

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package redis
2+
3+
import (
4+
"context"
5+
"fmt"
6+
"time"
7+
8+
"github.com/redis/go-redis/v9"
9+
)
10+
11+
/* defines the methods to expose (for dependency injection) */
12+
type RedisClient interface {
13+
Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
14+
Get(ctx context.Context, key string) (string, error)
15+
HSet(ctx context.Context, key string, values ...interface{}) *redis.IntCmd
16+
RPush(ctx context.Context, key string, value interface{}) *redis.IntCmd
17+
LRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd
18+
}
19+
20+
/* redisClient implementation */
21+
type redisClient struct {
22+
client *redis.Client
23+
}
24+
25+
/* for creating a new redis client */
26+
func NewRedisClient(address, password string, db int) (RedisClient, error) {
27+
rdb := redis.NewClient(&redis.Options{
28+
Addr: address,
29+
Password: password,
30+
DB: db,
31+
})
32+
33+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
34+
defer cancel()
35+
36+
if err := rdb.Ping(ctx).Err(); err != nil {
37+
return nil, fmt.Errorf("could not connect to Redis: %w", err)
38+
}
39+
40+
return &redisClient{client: rdb}, nil
41+
}
42+
43+
/* Set sets a key-value pair in Redis */
44+
func (r *redisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
45+
return r.client.Set(ctx, key, value, expiration).Err()
46+
}
47+
48+
/* retrieves a value by key from Redis */
49+
func (r *redisClient) Get(ctx context.Context, key string) (string, error) {
50+
return r.client.Get(ctx, key).Result()
51+
}
52+
53+
/* for pushing multiple elements in Redis */
54+
func (r *redisClient) RPush(ctx context.Context, key string, value interface{}) *redis.IntCmd {
55+
return r.client.RPush(ctx, key, value)
56+
}
57+
58+
/* retrieve a subset of the list stored at a specified key */
59+
func (r *redisClient) LRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd {
60+
return r.client.LRange(ctx, key, start, stop)
61+
}
62+
63+
/* hash set for redis */
64+
func (r *redisClient) HSet(ctx context.Context, key string, values ...interface{}) *redis.IntCmd {
65+
return r.client.HSet(ctx, key, values...)
66+
}

0 commit comments

Comments
 (0)