package main
import (
"context"
"fmt"
"github.com/streadway/amqp"
"learning_tools/rabbitmq/mq"
"time"
)
/**
这里使用fanout类型交换器
(广播模式) 生产的每一条消息,由所有消费者进行处理操作 (把消息投递到所有与此交换器绑定的队列中)
*/
func main() {
ctx, cancel := context.WithCancel(context.Background())
conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
if err != nil {
panic(err)
}
// 开启 channel
channel, err := conn.Channel()
if err != nil {
panic(err)
}
//创建一个交换器
if err = channel.ExchangeDeclare(
"e1",
amqp.ExchangeFanout, //这里选择他的类型
true,
false,
false,
true,
nil); err != nil {
panic(err)
}
//创建一个队列 q1
qd1, err := channel.QueueDeclare("q1",
true,
false,
false,
true,
nil);
if err != nil {
panic(err)
}
qd2, err := channel.QueueDeclare("q2",
true,
false,
false,
true,
nil);
if err != nil {
panic(err)
}
//交换机和队列绑定 ,这里间隔队列绑定在一个交换器上面
if err = channel.QueueBind(qd1.Name, "a", "e1", true, nil); err != nil {
panic(err)
}
if err = channel.QueueBind(qd2.Name, "b", "e1", true, nil); err != nil {
panic(err)
}
//消费者
go mq.SampleConsumption(ctx, "q1", "c1")
go mq.SampleConsumption(ctx, "q2", "c2")
/**
开始发送消息到队列
*/
for i := 0; i < 5; i++ {
if err = channel.Publish("e1",
"c",
false,
false,
amqp.Publishing{
Timestamp: time.Now(),
DeliveryMode: amqp.Persistent,
ContentType: "text/plain",
Body: []byte(fmt.Sprintf("%d:,Hello Rabbit MQ!", i)),
}); err != nil {
panic(err)
}
}
time.Sleep(time.Second * 2)
cancel()
time.Sleep(time.Second * 1)
}
注意:这里的QueueBind里面key 都设置不一样 和 Publish里面key设置也不一样,交换器都把消息给了队列,这就是fanout类型交换器的
作用,只要绑定这种交换器,队列都换被消息广播