golang rabbitmq topic 消费生产
使用注意订阅
- proudcut
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/streadway/amqp"
"log"
)
func main() {
amqpServerURL := `amqp://127.0.0.1:5672`
amqpExchangeName := `meet_member_exchange`
amqpQueueName := `meet_member_queue`
amqpRoutingKey := `meet_member_routing_key`
connectRabbitMQ, err := amqp.Dial(amqpServerURL)
if err != nil {
panic(err)
}
defer connectRabbitMQ.Close()
channelRabbitMQ, err := connectRabbitMQ.Channel()
if err != nil {
panic(err)
}
defer channelRabbitMQ.Close()
if _, err = channelRabbitMQ.QueueDeclare(amqpQueueName, true, false, false, false, nil); err != nil {
panic(err)
}
if err = channelRabbitMQ.ExchangeDeclare(amqpExchangeName, amqp.ExchangeTopic, true, false, false, false, nil); err != nil {
panic(err)
}
if err = channelRabbitMQ.QueueBind(amqpQueueName, amqpRoutingKey, amqpExchangeName, false, nil); err != nil {
panic(err)
}
app := fiber.New()
app.Use(
logger.New(),
)
app.Get("/send", func(c *fiber.Ctx) error {
message := amqp.Publishing{
ContentType: "text/plain",
Body: []byte(c.Query("msg")),
}
if err_ := channelRabbitMQ.Publish(amqpExchangeName, amqpRoutingKey, false, false, message); err_ != nil {
return err_
}
return nil
})
log.Fatal(app.Listen(":3000"))
}
- consumer
package main
import (
"github.com/streadway/amqp"
"log"
)
func main() {
amqpServerURL := `amqp://127.0.0.1:5672`
amqpQueueName := `meet_member_queue`
amqpConsumerName := `meet_member_consumer`
connectRabbitMQ, err := amqp.Dial(amqpServerURL)
if err != nil {
panic(err)
}
defer connectRabbitMQ.Close()
channelRabbitMQ, err := connectRabbitMQ.Channel()
if err != nil {
panic(err)
}
defer channelRabbitMQ.Close()
messages, err := channelRabbitMQ.Consume(amqpQueueName, amqpConsumerName, true, false, false, false, nil)
if err != nil {
log.Println(err)
}
log.Println("Successfully connected to RabbitMQ")
log.Println("Waiting for messages")
forever := make(chan bool)
go func() {
for message := range messages {
log.Printf(" > Received message: %s\n", message.Body)
}
}()
<-forever
}
本文来自博客园,作者:vx_guanchaoguo0,转载请注明原文链接:https://www.cnblogs.com/guanchaoguo/p/16255144.html