GO RabbitMQ


安装

  1. 通过homebrew安装RabbitMQ
    brew install rabbitmq

2.启动

rabbitmq-server

3.图形化界面
localhost:15672

需要登录,可以用:
username:guest,passwrod:guest登录

4.创建新账号

username:admin,password:123456

rabbitmqctl add_user admin 123456

5.给账号配置角色

rabbitmqctl set_user_tags admin administrator

现在可以用admin:123456登录了

GO RabbitMQ

生产消息


func failOnError(err error, msg string) {
  if err != nil {
    log.Fatalf("%s: %s", msg, err)
  }
}


conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()

ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()

q, err := ch.QueueDeclare(
  "hello", // name
  false,   // durable
  false,   // delete when unused
  false,   // exclusive
  false,   // no-wait
  nil,     // arguments
)
failOnError(err, "Failed to declare a queue")

body := "Hello World!"
err = ch.Publish(
  "",     // exchange
  q.Name, // routing key
  false,  // mandatory
  false,  // immediate
  amqp.Publishing {
    ContentType: "text/plain",
    Body:        []byte(body),
  })
failOnError(err, "Failed to publish a message")

源代码:https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/go/send.go

消费消息

func failOnError(err error, msg string) {
  if err != nil {
    log.Fatalf("%s: %s", msg, err)
  }
}

conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
failOnError(err, "Failed to connect to RabbitMQ")
defer conn.Close()

ch, err := conn.Channel()
failOnError(err, "Failed to open a channel")
defer ch.Close()

q, err := ch.QueueDeclare(
  "hello", // name
  false,   // durable
  false,   // delete when unused
  false,   // exclusive
  false,   // no-wait
  nil,     // arguments
)
failOnError(err, "Failed to declare a queue")

msgs, err := ch.Consume(
  q.Name, // queue
  "",     // consumer
  true,   // auto-ack
  false,  // exclusive
  false,  // no-local
  false,  // no-wait
  nil,    // args
)
failOnError(err, "Failed to register a consumer")

forever := make(chan bool)

go func() {
  for d := range msgs {
    log.Printf("Received a message: %s", d.Body)
  }
}()

log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
<-forever

源代码:https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/go/receive.go

github上有人对rabbitmq的五种模式进行了封装,https://github.com/ormissia/go-rabbitmq

参考

【1】Mac安装RabbitMQ

【2】从什么时候开始努力都不会晚

【3】go连接RabbitMQ “no access to this vhost”错误

【4】https://www.rabbitmq.com/tutorials/tutorial-one-go.html


文章作者: Alex
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Alex !
  目录