rabbitmq操作
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.2 KiB

3 years ago
  1. package rabbitmq
  2. import (
  3. "errors"
  4. "log"
  5. "github.com/streadway/amqp"
  6. )
  7. var Conn *amqp.Connection
  8. var Chan *amqp.Channel
  9. func Connect(host, port, username, pwd, vhost string) error {
  10. log.Println("RabbitMQ connecting...")
  11. var err error
  12. if username != "" && pwd != "" && host != "" && port != "" {
  13. if vhost == "" {
  14. vhost = "/"
  15. }
  16. Conn, err = amqp.Dial("amqp://" + username + ":" + pwd + "@" + host + ":" + port + "/" + vhost)
  17. if err != nil {
  18. log.Println("ERROR", "Failed to connect to RabbitMQ", err)
  19. } else {
  20. log.Println("RabbitMQ has connected")
  21. }
  22. // defer conn.Close()
  23. } else {
  24. log.Println("ERROR", "RabbitMQ connection params errors")
  25. err = errors.New("RabbitMQ connection params errors")
  26. }
  27. return err
  28. }
  29. func Channel() error {
  30. var err error
  31. Chan, err = Conn.Channel()
  32. if err != nil {
  33. log.Println("ERROR", "Failed to open a channel")
  34. } else {
  35. log.Println("open a channel")
  36. }
  37. // defer ch.Close()
  38. return err
  39. }
  40. func CloseChannel() error {
  41. err := Chan.Close()
  42. if err == nil {
  43. log.Println("RabbitMQ channel closed")
  44. }
  45. return err
  46. }
  47. func CloseConn() error {
  48. err := Conn.Close()
  49. if err == nil {
  50. log.Println("RabbitMQ connection closed")
  51. }
  52. return err
  53. }