1
0
mirror of https://github.com/eventials/goevents.git synced 2025-04-26 13:48:59 +08:00
eventials.goevents/amqp/consumer.go

280 lines
5.3 KiB
Go
Raw Normal View History

2016-12-01 10:52:22 -02:00
package amqp
import (
"regexp"
"strings"
2017-03-09 17:32:05 -03:00
"sync"
"time"
2016-12-01 10:52:22 -02:00
2016-12-01 11:40:58 -02:00
"github.com/eventials/goevents/messaging"
2017-03-09 17:32:05 -03:00
log "github.com/Sirupsen/logrus"
2016-12-01 10:52:22 -02:00
amqplib "github.com/streadway/amqp"
)
type handler struct {
action string
2016-12-01 11:40:58 -02:00
handler messaging.EventHandler
2016-12-01 10:52:22 -02:00
re *regexp.Regexp
}
type Consumer struct {
2017-03-09 17:32:05 -03:00
config ConsumerConfig
m sync.Mutex
2016-12-01 10:52:22 -02:00
conn *Connection
autoAck bool
handlers []handler
2016-12-28 09:20:29 -02:00
channel *amqplib.Channel
queue *amqplib.Queue
exchangeName string
queueName string
2017-03-09 17:32:05 -03:00
closed bool
}
// ConsumerConfig to be used when creating a new producer.
type ConsumerConfig struct {
consumeRetryInterval time.Duration
2016-12-01 10:52:22 -02:00
}
2016-12-01 16:17:55 -02:00
// NewConsumer returns a new AMQP Consumer.
2017-03-09 17:32:05 -03:00
// Uses a default ConsumerConfig with 2 second of consume retry interval.
2016-12-28 09:20:29 -02:00
func NewConsumer(c messaging.Connection, autoAck bool, exchange, queue string) (messaging.Consumer, error) {
return NewConsumerConfig(c, autoAck, exchange, queue, ConsumerConfig{
2017-03-09 17:32:05 -03:00
consumeRetryInterval: 2 * time.Second,
})
}
2016-12-01 10:52:22 -02:00
// NewConsumerConfig returns a new AMQP Consumer.
func NewConsumerConfig(c messaging.Connection, autoAck bool, exchange, queue string, config ConsumerConfig) (messaging.Consumer, error) {
2017-03-09 17:32:05 -03:00
consumer := &Consumer{
config: config,
conn: c.(*Connection),
autoAck: autoAck,
handlers: make([]handler, 0),
exchangeName: exchange,
queueName: queue,
}
err := consumer.setupTopology()
go consumer.handleReestablishedConnnection()
return consumer, err
}
func (c *Consumer) Close() {
c.closed = true
c.channel.Close()
}
func (c *Consumer) setupTopology() error {
c.m.Lock()
defer c.m.Unlock()
var err error
c.channel, err = c.conn.OpenChannel()
2016-12-28 09:20:29 -02:00
if err != nil {
2017-03-09 17:32:05 -03:00
return err
2016-12-28 09:20:29 -02:00
}
2017-03-09 17:32:05 -03:00
err = c.channel.ExchangeDeclare(
c.exchangeName, // name
"topic", // type
true, // durable
false, // auto-delete
false, // internal
false, // no-wait
nil, // arguments
2016-12-28 09:20:29 -02:00
)
if err != nil {
2017-03-09 17:32:05 -03:00
return err
2016-12-28 09:20:29 -02:00
}
2017-03-09 17:32:05 -03:00
q, err := c.channel.QueueDeclare(
c.queueName, // name
true, // durable
false, // auto-delete
false, // exclusive
false, // no-wait
nil, // arguments
2016-12-28 09:20:29 -02:00
)
2017-03-09 17:32:05 -03:00
c.queue = &q
2016-12-28 09:20:29 -02:00
if err != nil {
2017-03-09 17:32:05 -03:00
return err
2016-12-28 09:20:29 -02:00
}
2017-03-09 17:32:05 -03:00
return nil
2016-12-01 10:52:22 -02:00
}
2017-03-09 17:32:05 -03:00
func (c *Consumer) handleReestablishedConnnection() {
for !c.closed {
<-c.conn.NotifyReestablish()
err := c.setupTopology()
if err != nil {
log.WithFields(log.Fields{
"type": "goevents",
"subType": "consumer",
"error": err,
2017-03-09 17:32:05 -03:00
}).Error("Error setting up topology after reconnection")
}
}
2016-12-28 09:20:29 -02:00
}
2016-12-01 10:52:22 -02:00
func (c *Consumer) dispatch(msg amqplib.Delivery) {
if fn, ok := c.getHandler(msg.RoutingKey); ok {
defer func() {
if err := recover(); err != nil {
if !c.autoAck {
msg.Nack(false, true)
}
}
}()
ok := fn(msg.Body)
if !c.autoAck {
if ok {
msg.Ack(false)
} else {
msg.Nack(false, true)
}
}
} else {
// got a message from wrong exchange?
// ignore and don't requeue.
msg.Nack(false, false)
}
}
2016-12-01 11:40:58 -02:00
func (c *Consumer) getHandler(action string) (messaging.EventHandler, bool) {
2016-12-01 10:52:22 -02:00
for _, h := range c.handlers {
if h.re.MatchString(action) {
return h.handler, true
}
}
return nil, false
}
2016-12-01 16:17:55 -02:00
// Subscribe allow to subscribe an action handler.
2016-12-01 11:40:58 -02:00
func (c *Consumer) Subscribe(action string, handlerFn messaging.EventHandler) error {
2016-12-01 10:52:22 -02:00
// TODO: Replace # pattern too.
pattern := strings.Replace(action, "*", "(.*)", 0)
re, err := regexp.Compile(pattern)
if err != nil {
return err
}
2016-12-28 09:20:29 -02:00
err = c.channel.QueueBind(
c.queueName, // queue name
action, // routing key
c.exchangeName, // exchange
false, // no-wait
nil, // arguments
2016-12-01 10:52:22 -02:00
)
if err != nil {
return err
}
c.handlers = append(c.handlers, handler{
action,
handlerFn,
re,
})
return nil
}
2016-12-01 16:17:55 -02:00
// Unsubscribe allows to unsubscribe an action handler.
2016-12-01 10:52:22 -02:00
func (c *Consumer) Unsubscribe(action string) error {
2016-12-28 09:20:29 -02:00
err := c.channel.QueueUnbind(
c.queueName, // queue name
action, // routing key
c.exchangeName, // exchange
nil, // arguments
2016-12-01 10:52:22 -02:00
)
if err != nil {
return err
}
idx := -1
for i, h := range c.handlers {
if h.action == action {
idx = i
break
}
}
if idx != -1 {
c.handlers = append(c.handlers[:idx], c.handlers[idx+1:]...)
}
return nil
}
2016-12-01 16:17:55 -02:00
// Listen start to listen for new messages.
2017-03-09 17:32:05 -03:00
func (c *Consumer) Consume() {
for !c.closed {
log.WithFields(log.Fields{
"type": "goevents",
"subType": "consumer",
"queue": c.queueName,
}).Debug("Setting up consumer channel...")
2017-03-09 17:32:05 -03:00
msgs, err := c.channel.Consume(
c.queueName, // queue
"", // consumer
c.autoAck, // auto ack
false, // exclusive
false, // no local
false, // no wait
nil, // args
)
if err != nil {
log.WithFields(log.Fields{
"type": "goevents",
"subType": "consumer",
"queue": c.queueName,
"error": err,
}).Error("Error setting up consumer...")
2017-03-09 17:32:05 -03:00
time.Sleep(c.config.consumeRetryInterval)
continue
}
2016-12-01 10:52:22 -02:00
2017-03-09 17:32:05 -03:00
log.WithFields(log.Fields{
"type": "goevents",
"subType": "consumer",
"queue": c.queueName,
2017-03-09 17:32:05 -03:00
}).Info("Consuming messages...")
2016-12-01 10:52:22 -02:00
2017-03-09 17:32:05 -03:00
for m := range msgs {
c.dispatch(m)
}
2016-12-01 10:52:22 -02:00
2017-03-09 17:32:05 -03:00
log.WithFields(log.Fields{
"type": "goevents",
"subType": "consumer",
"queue": c.queueName,
"closed": c.closed,
}).Info("Consumption finished")
2017-03-09 17:32:05 -03:00
}
2016-12-01 10:52:22 -02:00
}