Skip to content

Instantly share code, notes, and snippets.

@uneeq
Last active May 2, 2019
Embed
What would you like to do?
RabbitMQ communication system (draft)
require 'rubygems'
require 'bunny'
require 'json'
require 'securerandom'
module Bunny
module Employees
class Fetcher
QUEUE_NAME = 'employees'
def initialize
self.rabbit = Bunny.new.start
self.channel = rabbit.create_channel
self.exchange = channel.default_exchange
self.queue = channel.queue(QUEUE_NAME)
end
def call
lock = Mutex.new
condition = ConditionVariable.new
response_queue = channel.queue(response_queue_name)
params = { employee: { uuid: ARGV.first } }.to_json
puts "Fetch employee data with params: #{params}"
response_queue.subscribe do |_delivery_info, _properties, body|
@response_attributes = JSON.parse(body)
lock.synchronize { condition.signal }
end
exchange.publish(
params, routing_key: queue.name, reply_to: response_queue.name
)
lock.synchronize { condition.wait(lock) }
puts @response_attributes
rabbit.close
end
private
attr_accessor :rabbit, :channel, :exchange, :queue
def response_queue_name
[QUEUE_NAME, 'response', SecureRandom.hex].join('.')
end
end
end
end
Bunny::Employees::Fetcher.new.call
# ruby fetcher.rb 'uniq1'
require 'bunny'
require 'byebug'
require 'json'
module Bunny
module Employees
class Listner
QUEUE_NAME = 'employees'
EMPLOYEE_DB = {
'uniq1' => { id: 1, name: 'Username1', company: 'Dvelp' },
'uniq2' => { id: 2, name: 'Username2', company: 'Dvelp' },
'uniq3' => { id: 3, name: 'Username3', company: 'Dvelp' }
}
def initialize
self.rabbit = Bunny.new.start
self.channel = rabbit.create_channel
self.exchange = channel.default_exchange
self.queue = channel.queue(QUEUE_NAME)
end
def call
puts ' [*] Waiting for messages. To exit press CTRL+C'
queue.subscribe(block: true) do |_delivery_info, properties, body|
puts " [x] Received #{body} from #{properties.reply_to}"
params = JSON.parse(body)
record = ar_search(params['employee'])
exchange.publish(record.to_json, routing_key: properties.reply_to)
puts " [x] Send response #{record}"
end
rescue Interrupt => _
rabbit.connection.close
exit(0)
end
private
attr_accessor :rabbit, :channel, :exchange, :queue
def ar_search(params)
EMPLOYEE_DB[params['uuid']]
end
end
end
end
Bunny::Employees::Listner.new.call
# ruby listener.rb
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment