无法使用Go从RabbitMQ发送消息

时间:2018-12-29 12:34:10

标签: go rabbitmq

我刚刚开始阅读有关RabbitMQ的内容,并且试图在for循环中发送大量消息。问题在于它根本不起作用。

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)
    }

}

我什至尝试减少迭代次数,甚至尝试在循环外发送消息,但这是行不通的。我在做什么错了?

1 个答案:

答案 0 :(得分:3)

提供的代码看起来不错,除了您使用的是默认交换并提供与队列名称不同的路由名称。

您可能想使用队列名称作为路由名称。尝试在hello函数中将user_actions替换为ch.Publish

相关问题