【RabbitMQ】fanout type exchange example in golang

本文介绍了RabbitMQ中fanout类型的exchange,它将消息广播到所有绑定的queue。通过golang编写了producer和consumer示例,producer负责发送消息,consumer负责接收。在gopath/src/fanout项目中,分别创建了producer.go(发送消息)和consumer.go(接收消息)。consumer需要声明exchange、queue,并将queue绑定到exchange,然后订阅queue。运行producer和多个consumer,可以在不同终端观察到消息的广播效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【RabbitMQ】核心概念讲到,Exchange有三种类型:

  • fanout
  • direct
  • topic

紧接着的三篇文章将介绍着三种类型,并给出golang的实现,本篇为第一篇,介绍fanout类型(fanout类型的exchange,会将消息发送到所有绑定了该exchange的queue上,可以理解成广播模式)

在我的开发环境中,GOPATH=C:\Users${user_name}\go,在GOPATH\src 目录下新建fanout项目。在fanout项目中新建两个文件:

  • producer.go。负责发送消息
  • consumer.go。负责接收消息

在producer.go中写入以下代码:

package main

import (
        "log"
        "os"

        "github.com/streadway/amqp"
)

func exit_on_error(err error) {
        if err != nil {
                log.Fatal(err)
        }
}

func main() {
        conn, err := amqp.Dial("amqp://<username>:<password>@<host>:<port>/")
        exit_on_error(err)
        defer conn.Close()

        ch, err := conn.Channel()
        exit_on_error(err)
        defer ch.Close()

        err = ch.ExchangeDeclare(
                "example.fanout",   // name
                "fanout", // type
                true,     // durable
                false,    // auto-deleted
                false,    // internal
                false,    // no-wait
                nil,      // arguments
        )
        exit_on_error(err)

        message := os.Args[1]

        err = ch.Publish(
                "example.fanout", // exchange
                "",     // routing key
                false,  // mandatory
                false,  // immediate
                amqp.Publishing{
                        ContentType: "text/plain",
                        Body:        []byte(message),
                },
        )

        log.Printf(" [x] Sent %s", message)
}

producer流程:

  1. 创建exchange
  2. 发送消息到exchange(指定routingkey,但fanout类型的exchange不关心routingkey)

在consumer.go中写入以下代码:

package main

import (
        "log"

        "github.com/streadway/amqp"
)

func exit_on_error(err error) {
        if err != nil {
                log.Fatal(err)
        }
}

func main() {
        conn, err := amqp.Dial("amqp://<username>:<password>@<host>:<port>/")
        exit_on_error(err)
        defer conn.Close()

        ch, err := conn.Channel()
        exit_on_error(err)
        defer ch.Close()

        err = ch.ExchangeDeclare(
                "example.fanout",   // name
                "fanout", // type
                true,     // durable
                false,    // auto-deleted
                false,    // internal
                false,    // no-wait
                nil,      // arguments
        )
        exit_on_error(err)

        q, err := ch.QueueDeclare(
                "",    // name
                false, // durable
                false, // delete when usused
                true,  // exclusive
                false, // no-wait
                nil,   // arguments
        )
        exit_on_error(err)

        err = ch.QueueBind(
                q.Name, // queue name
                "",     // routing key
                "example.fanout", // exchange
                false,
                nil,
        )
        exit_on_error(err)

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

        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
}

说明:conn, err := amqp.Dial("amqp://<username>:<password>@<host>:<port>/")使用<username>等变量,需要替换成实际环境参数

consumer流程:

  1. 申明exchange
  2. 声明queue
  3. 将queue绑定到exchange
  4. 订阅queue

特别说明:如果将producer.go和consumer.go放到同一个目录下,IDE会报错,同一个main package中有两个main function,可以忽略

运行producer:

go run producer.go <message>

运行consumer(为了测试效果,打开两个以上终端,执行以下命令):

go run consumer.go

运行结果示例:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值