package rabbitmq
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
|
|
"github.com/streadway/amqp"
|
|
)
|
|
|
|
var Conn *amqp.Connection
|
|
var Chan *amqp.Channel
|
|
|
|
func Connect(host, port, username, pwd, vhost string) error {
|
|
|
|
log.Println("RabbitMQ connecting...")
|
|
var err error
|
|
if username != "" && pwd != "" && host != "" && port != "" {
|
|
if vhost == "" {
|
|
vhost = "/"
|
|
}
|
|
Conn, err = amqp.Dial("amqp://" + username + ":" + pwd + "@" + host + ":" + port + "/" + vhost)
|
|
if err != nil {
|
|
log.Println("ERROR", "Failed to connect to RabbitMQ", err)
|
|
} else {
|
|
log.Println("RabbitMQ has connected")
|
|
}
|
|
// defer conn.Close()
|
|
} else {
|
|
log.Println("ERROR", "RabbitMQ connection params errors")
|
|
err = errors.New("RabbitMQ connection params errors")
|
|
}
|
|
|
|
return err
|
|
}
|
|
|
|
func Channel() error {
|
|
var err error
|
|
Chan, err = Conn.Channel()
|
|
if err != nil {
|
|
log.Println("ERROR", "Failed to open a channel")
|
|
} else {
|
|
log.Println("open a channel")
|
|
}
|
|
// defer ch.Close()
|
|
return err
|
|
}
|
|
|
|
func CloseChannel() error {
|
|
err := Chan.Close()
|
|
if err == nil {
|
|
log.Println("RabbitMQ channel closed")
|
|
}
|
|
return err
|
|
}
|
|
|
|
func CloseConn() error {
|
|
err := Conn.Close()
|
|
if err == nil {
|
|
log.Println("RabbitMQ connection closed")
|
|
}
|
|
return err
|
|
}
|