【问题标题】:How to communicate between ZeroMQ contexts in different Goroutines?如何在不同 Goroutine 中的 ZeroMQ 上下文之间进行通信?
【发布时间】:2012-09-30 23:59:20
【问题描述】:

我正在使用this as boilerplate,除了在同一个程序中我还有一些 goroutines 作为工作程序并连接到后端端点 tcp://127.0.0.1:5560。

我想做的是让它通过更有效的方式连接,例如 ipc://、inproc://,甚至是 unix 套接字。我已经尝试过这些,但没有奏效。 ZeroMQ 不能使用 Channels 吗?

那么如何在没有 tcp 的情况下将不同的 goroutine 与 ZeroMQ 上下文连接起来?有更好的选择吗?

更新: 代码:

// Simple message queuing broker
// Same as request-reply broker but using QUEUE device
//
// Author:  Brendan Mc.
// Requires: http://github.com/alecthomas/gozmq

package main

import (
    zmq "github.com/alecthomas/gozmq"
)

func startWorker() {
    context, _ := zmq.NewContext()
    defer context.Close()

    worker, _ := context.NewSocket(zmq.REP)
    //err := worker.Connect("ipc:///backend")  // Tried it, but nothing
    //err := worker.Connect("inproc:///backend")  // Tried it, but nothing
    err := worker.Connect("tcp://127.0.0.1:5560") // this works
    if err != nil {
        fmt.Println(err)
    }

    for {
        data, err := worker.Recv(0)
        fmt.Println(string(data))
        worker.Send([]byte("I got your data"), 0)
    }
}

func main() {
    context, _ := zmq.NewContext()
    defer context.Close()

    // Socket facing clients
    frontend, _ := context.NewSocket(zmq.ROUTER)
    defer frontend.Close()
    frontend.Bind("tcp://*:5559")

    // Socket facing services
    backend, _ := context.NewSocket(zmq.DEALER)
    defer backend.Close()
    //backend.Bind("ipc:///backend")  // Tried it, but nothing
    //backend.Bind("inproc:///backend")  // Tried it, but nothing
    backend.Bind("tcp://*:5560") // this works

    for i := 0; i < 4; i++ {
        go startWorker() // Start workers in a separate goroutine
    }

    // Start built-in device
    zmq.Device(zmq.QUEUE, frontend, backend)

    // We never get here…
}

【问题讨论】:

  • 我不太确定你在问什么?您想知道您是否可以使用其他协议与 0MQ?或者你是在问 0MQ 是否可以安全地从多个 goroutine 中使用?
  • 我在问我是否可以对 0mq 使用不同的协议,在 goroutine 之间进行通信。我可以通过 tcp 在 goroutines 之间进行通信,但我不能使用 inproc 或 ipc 进行通信。这些也可以在 Go 的 goroutines 下工作吗?
  • 发布一些代码,使用 zmq 有无数的小事情会导致一些问题......通常使用 ZMQ,只要一切都在相同的过程。每个 goroutine 都需要“共享”相同的上下文(上下文是线程安全的)并从中创建每个 inproc:// 连接。
  • 添加了代码,我认为问题(以及这个问题的答案)是因为goroutines不共享相同的上下文,它们无法通过inproc://连接。这是正确的@g19fanatic 吗? ipc:// 或 unix 套接字呢?为什么不是那些?
  • 为什么要使用 0mq 在 goroutine 之间进行通信?为什么不只使用频道?

标签: tcp go ipc zeromq inproc


【解决方案1】:

为了使用inproc:// 传输,所有套接字需要共享相同的上下文(这是线程安全的)。

此外,如果您使用相同的 Context,则 ZMQ 不需要任何后端 I/O 线程

您没有提及您在哪个操作系统下运行,但ipc:// 传输仅在大多数 *nix 下可用。在 Windows 下,您只能使用以下传输:tcp://、inproc://、pgm://。查看zmq_connect 文档了解更多信息。

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多