producer.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package main
  2. import (
  3. "log"
  4. "github.com/streadway/amqp"
  5. )
  6. func failOnError(err error, msg string) {
  7. if err != nil {
  8. log.Fatalf("%s: %s", msg, err)
  9. }
  10. }
  11. func main() {
  12. conn, err := amqp.Dial("amqp://toor:aaaAAA111!!!@ubuntu:5672/")
  13. failOnError(err, "Failed to connect to RabbitMQ")
  14. defer conn.Close()
  15. ch, err := conn.Channel()
  16. failOnError(err, "Failed to open a channel")
  17. defer ch.Close()
  18. q, err := ch.QueueDeclare(
  19. "task_queue", // 队列名称
  20. true, // durable 持久化队列
  21. false, // autoDelete
  22. false, // exclusive
  23. false, // noWait
  24. nil, // arguments
  25. )
  26. failOnError(err, "Failed to declare a queue")
  27. body := "Hello Persistent RabbitMQ Message"
  28. err = ch.Publish(
  29. "", // exchange
  30. q.Name, // routing key
  31. false, // mandatory
  32. false, // immediate
  33. amqp.Publishing{
  34. DeliveryMode: amqp.Persistent, // 持久化消息
  35. ContentType: "text/plain",
  36. Body: []byte(body),
  37. })
  38. failOnError(err, "Failed to publish a message")
  39. log.Printf(" [x] Sent %s\n", body)
  40. }