Friday, June 22, 2012

first qpid ruby example

Step 1: Add Exchange, Queue, and bind them.

[root@localhost qpidclient]# qpid-config -a guest/guest@localhost add exchange topic mytopic  --durable
[root@localhost qpidclient]# qpid-config -a guest/guest@localhost add queue myqueue
[root@localhost qpidclient]# qpid-config -a guest/guest@localhost bind mytopic myqueue

Using qpid-tool to check if add exchange and queue  successfully.


[root@localhost qpidclient]# qpid-tool
qpid: list exchange
Objects of type org.apache.qpid.broker:exchange
    ID   Created   Destroyed  Index
    ===============================================
    104  13:17:03  -          103.
    111  14:36:44  -          103.mytopic
 qpid: list queue
Objects of type org.apache.qpid.broker:queue
    ID   Created   Destroyed  Index
    ==============================================================
    117  14:38:50  -          103.myqueue


Step 2: Ruby Qpid producer code / server
[root@localhost qpidclient]# vim producer.rb
#!/usr/bin/env ruby

require "rubygems"
require "qpid"
require "socket"

conn = Qpid::Connection.new(TCPSocket.new("localhost", 5672),
                                         :username => "guest",
                                         :password => "guest")
conn.start(10)

ssn = conn.session("qpid_producer")

# create a queue
ssn.queue_declare("myqueue")
ssn.exchange_declare("mytopic", :type => "topic")

dp = ssn.delivery_properties(:routing_key => "myqueue")
mp = ssn.message_properties(:content_type => "text/plain")

ssn.message_transfer(:message => Qpid::Message.new(dp, mp, "hi5"))
while line = gets.strip
  break if line =~ /^(bye)$/i
  ssn.message_transfer(:message => Qpid::Message.new(dp, mp, line.strip))
end
ssn.message_transfer(:message => Qpid::Message.new(dp, mp, "exit"))
ssn.sync

ssn.close()
conn.close()




Step 3 QPID consumer code:


[root@localhost qpidclient]# vim consumer.rb
#!/usr/bin/env ruby

require "rubygems"
require "qpid"
require "socket"

conn = Qpid::Connection.new(TCPSocket.new("localhost", 5672),
                                         :username => "guest",
                                         :password => "guest")
conn.start(10)

ssn = conn.session("qpid_consumer")

incoming = ssn.incoming("messages")
ssn.message_subscribe(
  :destination => "messages",
  :queue => "myqueue",
  :accept_mode => ssn.message_accept_mode.none
)

# start incoming message flow
incoming.start()

while true
 body = incoming.get().body
 puts body
 break if body == "bye"
end

ssn.close()
conn.close()

Step 4: run producer and consumer
[root@localhost qpidclient]# ./producer.rb
hi
hello


[root@localhost qpidclient]# ./consumer.rb
hi
hello



2 comments:

  1. Hi! Which qpid library for ruby are you using? It's not the standard Cqpid is it?

    ReplyDelete
  2. need following package for ubuntu:

    apt-get install libxml2 libxml2-dev

    gem install libxml-ruby

    ReplyDelete