message broker sifatida redis qo'shildi
This commit is contained in:
46
internal/broker/rabbitmq.go
Normal file
46
internal/broker/rabbitmq.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/JscorpTech/notification/internal/domain"
|
||||
"github.com/JscorpTech/notification/internal/rabbitmq"
|
||||
)
|
||||
|
||||
type rabbitMQBroker struct {
|
||||
Ctx context.Context
|
||||
}
|
||||
|
||||
func NewRabbitMQBroker(ctx context.Context) domain.BrokerPort {
|
||||
return &rabbitMQBroker{
|
||||
Ctx: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func (r rabbitMQBroker) Subscribe(topic string, handler func(domain.NotificationMsg)) {
|
||||
conn, ch, err := rabbitmq.Connect()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer conn.Close()
|
||||
defer ch.Close()
|
||||
|
||||
ch.ExchangeDeclare(topic, "direct", true, false, false, false, nil)
|
||||
q, _ := ch.QueueDeclare(topic, true, false, false, false, nil)
|
||||
ch.QueueBind(q.Name, topic, topic, false, nil)
|
||||
|
||||
msgs, _ := ch.Consume(q.Name, "", true, false, false, false, nil)
|
||||
|
||||
go func() {
|
||||
for msg := range msgs {
|
||||
var notification domain.NotificationMsg
|
||||
if err := json.Unmarshal(msg.Body, ¬ification); err != nil {
|
||||
fmt.Print(err.Error())
|
||||
}
|
||||
go handler(notification)
|
||||
}
|
||||
}()
|
||||
}
|
||||
39
internal/broker/redis.go
Normal file
39
internal/broker/redis.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/JscorpTech/notification/internal/domain"
|
||||
"github.com/JscorpTech/notification/internal/redis"
|
||||
)
|
||||
|
||||
type redisBroker struct {
|
||||
Ctx context.Context
|
||||
}
|
||||
|
||||
func NewRedisBroker(ctx context.Context) domain.BrokerPort {
|
||||
return &redisBroker{
|
||||
Ctx: ctx,
|
||||
}
|
||||
}
|
||||
|
||||
func (r redisBroker) Subscribe(topic string, handler func(domain.NotificationMsg)) {
|
||||
go func() {
|
||||
for {
|
||||
var notification domain.NotificationMsg
|
||||
val, err := redis.RDB.BLPop(r.Ctx, 0, topic).Result()
|
||||
if err != nil {
|
||||
fmt.Print(err.Error())
|
||||
return
|
||||
}
|
||||
if err := json.Unmarshal([]byte(val[1]), ¬ification); err != nil {
|
||||
fmt.Print(err.Error())
|
||||
return
|
||||
}
|
||||
go handler(notification)
|
||||
}
|
||||
}()
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user