pollo/lib/pubsub/adapters/redispubsub.go

72 lines
1.7 KiB
Go
Raw Normal View History

2023-05-18 20:04:55 -06:00
package adapters
import (
"context"
"os"
"atri.dad/lib"
"atri.dad/lib/pubsub"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
)
var RedisClient *redis.Client
type RedisPubSubMessage struct {
pubsub *redis.PubSub
}
// RedisPubSub is a Redis implementation of the PubSub interface.
type RedisPubSub struct {
Client *redis.Client
}
2024-04-09 11:58:08 -06:00
func NewRedisClient() (*redis.Client, error) {
2023-05-18 20:04:55 -06:00
if RedisClient != nil {
2024-04-09 11:58:08 -06:00
return RedisClient, nil
2023-05-18 20:04:55 -06:00
}
godotenv.Load(".env")
redis_url := os.Getenv("REDIS_URL")
2023-05-18 20:04:55 -06:00
2024-04-09 11:58:08 -06:00
opts, err := redis.ParseURL(redis_url)
2024-04-09 11:58:08 -06:00
if err != nil {
2024-04-09 12:03:26 -06:00
return nil, err
2024-04-09 11:58:08 -06:00
}
lib.LogInfo.Printf("\n[PUBSUB/REDIS]Connecting to Redis at %s\n", opts.Addr)
RedisClient = redis.NewClient(opts)
2023-05-18 20:04:55 -06:00
2024-04-09 11:58:08 -06:00
return RedisClient, nil
2023-05-18 20:04:55 -06:00
}
func (m *RedisPubSubMessage) ReceiveMessage(ctx context.Context) (*pubsub.Message, error) {
msg, err := m.pubsub.ReceiveMessage(ctx)
if err != nil {
return nil, err
}
lib.LogInfo.Printf("\n[PUBSUB/REDIS] Received message: %s\n", msg.Payload)
return &pubsub.Message{Payload: msg.Payload}, nil
}
func (ps *RedisPubSub) SubscribeToChannel(channel string) (pubsub.PubSubMessage, error) {
pubsub := ps.Client.Subscribe(context.Background(), channel)
_, err := pubsub.Receive(context.Background())
if err != nil {
return nil, err
}
lib.LogInfo.Printf("\n[PUBSUB/REDIS] Subscribed to channel %s\n", channel)
return &RedisPubSubMessage{pubsub: pubsub}, nil
}
func (r *RedisPubSub) PublishToChannel(channel string, message string) error {
err := r.Client.Publish(context.Background(), channel, message).Err()
if err != nil {
return err
}
lib.LogInfo.Printf("\n[PUBSUB/REDIS] Publishing message to channel %s: %s\n", channel, message)
return nil
}