golang整合rabbitmq-实现创建生产者绑定交换机-创建消费者消费完整代码
以下是一个简化的Go语言代码示例,展示了如何使用streadway/amqp
库创建一个简单的RabbitMQ生产者和消费者。
生产者代码(发送消息):
package main
import (
"log"
"github.com/streadway/amqp"
)
func main() {
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()
err = ch.ExchangeDeclare("logs_direct", "direct", true, false, false, false, nil)
failOnError(err, "Failed to declare an exchange")
body := "Hello World!"
err = ch.Publish("logs_direct", "info", false, false, amqp.Publishing{
ContentType: "text/plain",
Body: []byte(body),
})
failOnError(err, "Failed to publish a message")
log.Printf(" [x] Sent %s", body)
}
func failOnError(err error, msg string) {
if err != nil { {
log.Fatalf("%s: %s", msg, err)
}
}
消费者代码(接收消息):
package main
import (
"log"
"github.com/streadway/amqp"
)
func main() {
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()
err = ch.ExchangeDeclare("logs_direct", "direct", true, false, false, false, nil)
failOnError(err, "Failed to declare an exchange")
q, err := ch.QueueDeclare("", false, false, true, false, nil)
failOnError(err, "Failed to declare a queue")
if err = ch.QueueBind("logs", "info", "logs_direct", false, nil); err != nil {
log.Fatalf("Queue Bind Failed: %s", err)
}
msgs, err := ch.Consume(q.Name, "", true, false, false, false, nil)
failOnError(err, "Failed to register a consumer")
forever := make(chan bool)
go func() {
for d := range msgs {
log.Printf(" [x] %s", d.Body)
}
}()
log.Printf(" [*] Waiting for logs. To exit press CTRL+C")
<-forever
}
func failOnError(err error, msg string) {
if err != nil {
log.Fatalf("%s: %s", msg, err)
}
}
确保你已经安装了streadway/amqp
库,如果没有安装,可以使用以下命令安装:
go get github.com/streadway/amqp
以上代码仅作为创建生产者和消费者的参考,具体的RabbitMQ服务器地址、用户凭证、交
评论已关闭