ichannel is a channel for interprocess communication between ruby processes on the same machine or network. The basic premise is that you can "put" a ruby object onto the channel and on the other end(maybe in a different process, or maybe on a different machine) you can "get" the object from the channel. A unix socket (local to a single machine) or redis can be used for storage.
A channel depends on a serializer when reading and writing from the underlying socket(e.g: redis or a unix socket) but you can use any serializer that implements the dump and load methods. The default is set to be Marshal since it is a core ruby module but you could also use JSON, YAML, MessagePack, or <insert your serializer here>.
A demo of how to pass ruby objects through a channel and also between processes. Marshal is the serializer of choice, and a streamed UNIXSocket is used for storage:
channel = IChannel.unix Marshal pid = fork do channel.put Process.pid channel.put 'Hello!' end Process.wait pid channel.get # => Fixnum channel.get # => 'Hello!'
A demo of a channel sending messages between machines by using redis for storage:
channel = IChannel.redis Marshal, host: "10.0.0.1", key: "readme-example" channel.put %w(a) # In another process, on another machine, far away… channel = IChannel.redis Marshal, host: "10.0.0.1", key: "readme-example" channel.get # => ["a"]
Knowing when a channel is readable can be useful so that you can avoid a blocking read on the underlying UNIXSocket. This (bad) example demonstrates how to do that:
channel = IChannel.unix Marshal pid = fork do sleep 3 channel.put 42 end until channel.readable? # do something else end channel.get # => 42 Process.wait pid
MessagePack doesn't implement
load but a wrapper can be easily
module MyMessagePack def self.dump(msg) MessagePack.pack(msg) end def self.load(msg) MessagePack.unpack(msg) end end channel = IChannel.unix MyMessagePack
- CRuby (1.9+)
- Rubinius (1.9+)
If you plan on using redis you'll need to install the 'redis' gem. It's
optional and only loaded when
IChannel.redis is invoked:
$ gem install redis
And to finish:
$ gem install ichannel
An implementation of the future pattern that leverages
MIT. See LICENSE.txt.