交作业啦~
来源:3-13 本阶段练习题
只为编程
2019-07-26
练习题答案:
- 总结消费流程
- 使用订阅模式实现广播
// 创建订阅模式的rabbitMq实例
func NewPublishTestClient(exchangeName string) *RabbitMq {
rabbitMq := NewRabbitMqClient("", exchangeName, "")
var err error
rabbitMq.conn, err = amqp.Dial(rabbitMq.Mqurl)
if err != nil {
errors.New("failed to connection")
}
rabbitMq.channel, err = rabbitMq.conn.Channel()
if err != nil {
errors.New("failed to channel")
}
return rabbitMq
}
// 订阅模式生产者
func (r *RabbitMq) PublishClientSent(message string) {
// 1. 试探性创建exchange
err := r.channel.ExchangeDeclare(
r.Exchange,
"fanout",
false,
false,
false,
false,
nil,
)
if err != nil {
errors.New("failed to declare exchange")
}
// 2. 发送消息
r.channel.Publish(
r.Exchange,
"",
false,
false,
amqp.Publishing{
ContentType: "text/plain",
Body: []byte(message),
},
)
}
// 订阅模式消费者
func (r * RabbitMq) ConsumePublishText () {
// 1. 试探性创建exchange
err := r.channel.ExchangeDeclare(
r.Exchange,
"fanout",
false,
false,
false,
false,
nil,
)
if err != nil {
errors.New("consumePublish failed to declare exchange")
}
// 2. 试探性创建queue
queue, err := r.channel.QueueDeclare(
"",
false,
false,
true,
false,
nil,
)
if err != nil {
errors.New("consumePublish failed to declare queue")
}
// 3. 将queue绑定到exchange上
err = r.channel.QueueBind(
queue.Name,
"",
r.Exchange,
false,
nil,
)
if err != nil {
errors.New("consumePublish failed bind queue to exchange")
}
// 4. 开始消费
messages, err := r.channel.Consume(
queue.Name,
"",
true,
true,
false,
false,
nil,
)
if err != nil {
errors.New("consumePublish failed to consume")
}
forever := make(chan int)
go func() {
for message := range messages {
fmt.Printf("Consume a message: %s routingKey: %s\n", message.Body, message.RoutingKey)
}
}()
fmt.Println("Consume is running ...")
<- forever
}
- 使用RabbitMQ 消费模式下的话题模式,挑选指定颜色进行消费
publishColorsTopic.go
package main
import (
"rabbitmq/Rabbitmq"
"strconv"
"time"
"fmt"
)
func main() {
rabbitMqRed := Rabbitmq.NewRabbitMqTopic("exColors", "a.red.b")
rabbitMqYellow := Rabbitmq.NewRabbitMqTopic("exColors", "b.c.yellow")
for i := 0; i <= 10; i++ {
rabbitMqRed.PublishTopic("red " + strconv.Itoa(i))
rabbitMqYellow.PublishTopic("yellow " + strconv.Itoa(i))
time.Sleep(1 * time.Second)
fmt.Println("color sent success ", i)
}
}
consumeColorYellow.go
package main
import (
"rabbitmq/Rabbitmq"
)
func main() {
rabbitMqYellow := Rabbitmq.NewRabbitMqTopic("exColors", "*.*.yellow")
rabbitMqYellow.ConsumeTopic()
}
consumeColorRed.go
package main
import (
"rabbitmq/Rabbitmq"
)
func main() {
rabbitMqYellow := Rabbitmq.NewRabbitMqTopic("exColors", "*.*.yellow")
rabbitMqYellow.ConsumeTopic()
}
自己的理解,还请老师和各位学长们指定啦~,谢谢
写回答
1回答
-
Cap
2019-07-26
太棒了???,学习了知识之后,通过自己的理解画出来,方法非常好,总结的也不错。
012019-07-26
相似问题