dongpai1942 2019-06-06 12:27
浏览 49

多个goroutine是否可以在不共享的情况下同时连接到同一rabbitmq交换机?

I'm trying to set up consumers for topics that are published to our exchange, like an API gateway that publishes messages to one of several subscribers.

I can't find an example of multiple subscribers that aren't just put in the main function of a single file.

  1. Can I create a goroutine for each consumer without breaking the connection that every other consumer has?
  2. Is a channel inside a goroutine appropriate within another goroutine?

Here is the main file:

package main

func main() {

    ...

    go myMessagePackage.Subscribe("example_topic1")
    go myMessagePackage.Subscribe("example_topic2")
    go myMessagePackage.Subscribe("example_topic3")

    ...

}

And this is what each consumer looks like:

package myMessagePackage

import...

func Subscribe(topic string, queueName string)  {

    conn, err := amqp.Dial(getConnectionString())
    failOnError(err, "API Consumer failed to connect to RabbitMQ")
    defer conn.Close()

    ch, err := conn.Channel()
    failOnError(err, "API Consumer failed to open a channel")
    defer ch.Close()

    err = ch.ExchangeDeclare(
        env.RabbitMq_Exchange_Name,
        env.RabbitMq_Exchange_Type,
        true,
        false,
        false,
        false,
        nil,
    )
    failOnError(err, "API Consumer failed to declare an exchange")

    q, err := ch.QueueDeclare(
        queueName,
        true,
        false,
        false,
        false,
        nil,
    )
    failOnError(err, "API Consumer failed to declare a queue")

    err = ch.QueueBind(
        q.Name,
        topic,
        env.RabbitMq_Exchange_Name,
        false,
        nil)
    failOnError(err, "API Consumer failed to bind a queue")

    msgs, err := ch.Consume(
        q.Name,
        "",
        true,
        false,
        false,
        false,
        nil,
    )
    failOnError(err, "API Consumer failed to register a consumer")

    forever := make(chan bool)

    go func() {
        for d := range msgs {
            log.Printf("API Consumer received a message from backend: %s", d.Body)
            routeResponse(d.Body)
        }
    }()

    log.Printf("API Consumer on topic %s started. Waiting for messages.", topic)
    <-forever
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
    • ¥15 perl MISA分析p3_in脚本出错
    • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?