-
Notifications
You must be signed in to change notification settings - Fork 7
/
redis.go
63 lines (52 loc) · 1.42 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
55
56
57
58
59
60
61
62
63
package notifier
import (
"context"
"encoding/json"
"github.com/PxyUp/fitter/pkg/builder"
"github.com/PxyUp/fitter/pkg/config"
"github.com/PxyUp/fitter/pkg/logger"
"github.com/redis/go-redis/v9"
"time"
)
var (
_ Notifier = &redisNotifier{}
)
type redisNotifier struct {
logger logger.Logger
name string
cfg *config.RedisNotifierConfig
}
func (r *redisNotifier) notify(record *singleRecord, input builder.Interfacable) error {
redisClient := redis.NewClient(&redis.Options{
Addr: formatWithRecord(r.cfg.Addr, record, input),
Password: formatWithRecord(r.cfg.Password, record, input),
DB: r.cfg.DB,
})
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
msg, errMars := json.Marshal(record)
if errMars != nil {
r.logger.Errorw("cant marshal message", "error", errMars.Error())
return errMars
}
errSend := redisClient.Publish(ctx, formatWithRecord(r.cfg.Channel, record, input), msg).Err()
if errSend != nil {
r.logger.Errorw("cant send message", "error", errSend.Error())
return errSend
}
return redisClient.Close()
}
func (o *redisNotifier) GetLogger() logger.Logger {
return o.logger
}
func (r *redisNotifier) WithLogger(logger logger.Logger) *redisNotifier {
r.logger = logger
return r
}
func NewRedis(name string, cfg *config.RedisNotifierConfig) *redisNotifier {
return &redisNotifier{
logger: logger.Null,
name: name,
cfg: cfg,
}
}