Go秒杀系统——RabbitMQ核心概念与工作模式
package main
import (
"fmt"
"github.com/streadway/amqp"
)
func main() {
// 连接RabbitMQ服务器
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_exchange", "fanout", true, false, false, false, nil)
failOnError(err, "Failed to declare an exchange")
q, err := ch.QueueDeclare("logs_queue", true, false, false, false, nil)
failOnError(err, "Failed to declare a queue")
err = ch.QueueBind("logs_queue", "", "logs_exchange", false, nil)
failOnError(err, "Failed to bind a queue")
// 消费者代码
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 {
fmt.Printf(" [x] %s\n", d.Body)
}
}()
fmt.Println(" [*] Waiting for logs. To exit press CTRL+C")
<-forever
}
func failOnError(err error, msg string) {
if err != nil {
fmt.Printf("%s: %s\n", msg, err)
}
}
这段代码展示了如何在Go语言中使用streadway/amqp库来连接RabbitMQ服务器,声明交换器、队列并将它们绑定起来,然后消费队列中的消息。这是实现RabbitMQ秒杀系统中必要的RabbitMQ操作。
评论已关闭