dongwu9063
2018-12-29 12:34
浏览 108
已采纳

无法使用Go从RabbitMQ发送消息

I just started reading about RabbitMQ and I'm trying to send large number of messages in a for loop. The problem is that it just doesn't work.

package main

import (
    "fmt"
    "github.com/streadway/amqp"
    "strconv"
)

func main() {
    var connectionString = "amqp://guest:guest@localhost:5672/"
    conn, _ := amqp.Dial(connectionString)
    defer conn.Close()

    ch, _ := conn.Channel()
    defer ch.Close()

    q, _ := ch.QueueDeclare(
        "user_actions", // name
        true,   // durable
        false,   // delete when unused
        false,   // exclusive
        false,   // no-wait
        nil,     // arguments
    )

    for i := 0; i < 10000; i++ {
        body := "Hello from Go! " + strconv.Itoa(i)
        ch.Publish(
            "",     // exchange
            "hello", // routing key
            false,  // mandatory
            false,  // immediate
            amqp.Publishing {
                ContentType: "text/plain",
                Body:        []byte(body),
            })
        fmt.Println("Sent: "+body)
    }

}

I even tried reducing the number of iterations and even tried sending messages outside of the loop but it just doesn't work. What am I doing wrong?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsa4d4789789 2018-12-29 12:37
    已采纳

    The provided code seems fine except that you are using the default exchange and providing a route name different than your queue name.

    Chances are you'll want to use the queue name as the routing name. Try to replace hello with user_actions in ch.Publish function.

    点赞 打赏 评论

相关推荐 更多相似问题