Skip to content

Commit

Permalink
added middleware in consumer
Browse files Browse the repository at this point in the history
  • Loading branch information
zaharinea committed Dec 13, 2020
1 parent 5aea7c6 commit ebf989c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
40 changes: 33 additions & 7 deletions consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,35 @@ import (
"github.com/streadway/amqp"
)

// MiddlewareFunc defines the handler
type MiddlewareFunc func(handler HandlerFunc) HandlerFunc

type contextKey int

// QueueNameKey key in context
const QueueNameKey contextKey = 0

// Consumer struct
type Consumer struct {
Connection
queues map[string]*Queue
exchanges map[string]*Exchange
wg *sync.WaitGroup
queues map[string]*Queue
exchanges map[string]*Exchange
middlewares []MiddlewareFunc
wg *sync.WaitGroup
}

// NewConsumer returns a new Consumer struct
func NewConsumer(uri string, logger Logger) *Consumer {
middlewares := []MiddlewareFunc{}
exchanges := make(map[string]*Exchange)
queues := make(map[string]*Queue)
err := make(chan error)
ctx, cancel := context.WithCancel(context.Background())
wg := &sync.WaitGroup{}
return &Consumer{
exchanges: exchanges,
queues: queues,
middlewares: middlewares,
exchanges: exchanges,
queues: queues,
Connection: Connection{
uri: uri,
err: err,
Expand Down Expand Up @@ -96,6 +107,11 @@ func (c *Consumer) RegisterExchange(exchange *Exchange) {
c.exchanges[exchange.Name] = exchange
}

//RegisterMiddleware register middleware
func (c *Consumer) RegisterMiddleware(m ...MiddlewareFunc) {
c.middlewares = append(c.middlewares, m...)
}

func (c *Consumer) reconnect() error {
if err := c.connect(); err != nil {
return err
Expand Down Expand Up @@ -200,6 +216,15 @@ func (c *Consumer) recoveryWorker(queue *Queue, workerNumber int, delivery *amqp
go c.consumeWorker(queue, workerNumber)
}

func buildChain(f HandlerFunc, m ...MiddlewareFunc) HandlerFunc {
// if our chain is done, use the original handler func
if len(m) == 0 {
return f
}
// otherwise nest the handler funcs
return m[0](buildChain(f, m[1:cap(m)]...))
}

func (c *Consumer) consumeWorker(queue *Queue, workerNumber int) {
defer c.wg.Done()

Expand All @@ -209,8 +234,9 @@ func (c *Consumer) consumeWorker(queue *Queue, workerNumber int) {
case delivery := <-queue.deliveries:
defer c.recoveryWorker(queue, workerNumber, &delivery)

c.logger.Debugf("Got event: queue=%s, worker=%d", queue.Name, workerNumber)
if queue.handler(c.ctx, delivery) {
ctx := context.WithValue(c.ctx, QueueNameKey, queue.Name)
result := buildChain(queue.handler, c.middlewares...)(ctx, delivery)
if result {
if err := delivery.Ack(false); err != nil {
c.logger.Errorf("Falied ack %s", queue.Name)
}
Expand Down
12 changes: 11 additions & 1 deletion examples/consumer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,17 @@ import (
rmqclient "github.com/zaharinea/go-rmq-client"
)

func loggingMiddleware(handler rmqclient.HandlerFunc) rmqclient.HandlerFunc {
return func(ctx context.Context, msg amqp.Delivery) bool {
queueName := ctx.Value(rmqclient.QueueNameKey).(string)
fmt.Printf("start processing event: queue=%s, msg=%s\n", queueName, string(msg.Body))
res := handler(ctx, msg)
fmt.Printf("end processing event: queue=%s, msg=%s\n", queueName, string(msg.Body))
return res
}
}

func handler(ctx context.Context, msg amqp.Delivery) bool {
fmt.Printf("event: msg=%s\n", string(msg.Body))
time.Sleep(time.Second * 3)
return true
}
Expand All @@ -38,6 +47,7 @@ func main() {
"x-dead-letter-routing-key": "queue2-failed",
}).SetRequeue(false).SetHandler(handler).SetCountWorkers(4)
consumer.RegisterQueue(queue2, queue2Failed)
consumer.RegisterMiddleware(loggingMiddleware)

consumer.Start()

Expand Down

0 comments on commit ebf989c

Please sign in to comment.