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

83 lines
1.4 KiB
Go
Raw Normal View History

2016-12-01 10:52:22 -02:00
package amqp
import (
2016-12-01 11:40:58 -02:00
"github.com/eventials/goevents/messaging"
2016-12-01 10:52:22 -02:00
amqplib "github.com/streadway/amqp"
)
type Connection struct {
connection *amqplib.Connection
channel *amqplib.Channel
queue *amqplib.Queue
exchangeName string
queueName string
}
2016-12-01 16:17:55 -02:00
// NewConnection returns an AMQP Connection.
2016-12-01 11:40:58 -02:00
func NewConnection(url, exchange, queue string) (messaging.Connection, error) {
2016-12-01 10:52:22 -02:00
conn, err := amqplib.Dial(url)
if err != nil {
return nil, err
}
ch, err := conn.Channel()
if err != nil {
return nil, err
}
err = ch.ExchangeDeclare(
exchange, // name
"topic", // type
true, // durable
false, // auto-delete
false, // internal
false, // no-wait
nil, // arguments
)
if err != nil {
return nil, err
}
q, err := ch.QueueDeclare(
queue, // name
true, // durable
false, // auto-delete
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
return nil, err
}
return &Connection{
conn,
ch,
&q,
exchange,
queue,
}, nil
}
2016-12-01 16:17:55 -02:00
// Consumer returns an AMQP Consumer.
2016-12-01 11:40:58 -02:00
func (c *Connection) Consumer(autoAck bool) (messaging.Consumer, error) {
2016-12-01 10:52:22 -02:00
return NewConsumer(c, autoAck)
}
2016-12-01 16:17:55 -02:00
// Producer returns an AMQP Producer.
2016-12-01 11:40:58 -02:00
func (c *Connection) Producer() (messaging.Producer, error) {
2016-12-01 10:52:22 -02:00
return NewProducer(c)
}
2016-12-01 16:17:55 -02:00
// Close closes the AMQP connection.
2016-12-01 10:52:22 -02:00
func (c *Connection) Close() {
c.channel.Close()
c.connection.Close()
}