2011-05-23 55 views
2

我有一个Rails项目和两个ruby mini-daemons在后台运行。他们之间沟通的最佳方式是什么?ruby​​进程间通信

像下面通信应该是可能的: 导轨 - >过程1 - >过程2 - >的Rails

有些请求将是同步,异步其他。

队列(类似于AMQ或基于自定义Redis的)或RPC HTTP调用?

回答

1

我通过RabbitMq +兔子宝石实现了一个系统。

更新:

阅读http://blog.brightbox.co.uk/posts/queues-and-callbacks后,我决定尝试RabbitMQ的。有两个宝石amqp(异步,基于eventmachine)或兔子(同步)。 amqp很棒,但是如果你使用Rails与乘客,它可以做一些奇怪的事情。

系统是这样工作的,守护进程在队列上监听消息:

# The incoming data should be a JSON encoded hash that looks like: 
# { "method" => method_to_call, "opts" => [ Array of opts for method ], 
# "output" => "a queue where to send the result (optional)" } 
# If output is specified it will publish the JSON encoded response there. 
def listen_on(queue_name, class) 
    BUNNY.start 
    bunny = BUNNY.queue(queue_name) 

    bunny.subscribe do |msg| 
    msg = JSON.parse(msg[:payload]) 

    result = class.new.send(msg["method"], *msg["opts"]) 

    if msg["output"] 
     BUNNY.queue(msg["output"]).publish(result.to_json) 
    end 
    end 

因此,一旦接收到消息它调用从一个类的方法。需要注意的一点是,在守护进程中使用Rails和amqp是最理想的选择。但我喜欢使用一个宝石pe服务。

+0

@MB为了他人的利益,你能分享一下你的解决方案的更多细节吗? – Sampson 2011-06-04 15:27:24

+0

如果你想在rails上使用amqp,你应该检查[thin](http://code.macournoyer.com/thin/)。它是基于事件机器的,因此您可以放入您的amqp代码,因为您已经在EM循环中。 – Femaref 2012-06-08 20:58:28