How to create a RabbitMQ consumer on a Ruby on Rails web app?

浪子不回头ぞ 提交于 2019-12-23 02:42:26

问题


So I am building a web app that uses a Ruby on Rails frontend and a Java backend. So basically when a user logs into the website I want a list of all the transactional data history for that user to be displayed on the screen.

The way I need to do this(for various reasons that I wont go in to) is to have code on the Ruby layer send a message(using RabbitMQ, packaged as a JSON object) to a queue and this message will be taken from the queue by code in the Java layer.

The Java layer then needs to send its response(the transactional data history, packaged as a JSON object) to another queue which code in my Ruby layer will consume and then display this on the browser.

So this request/response cycle needs to be async my consumer code on the Ruby layer also needs to know what client to display the details to, depending on the message it takes.

Can this be done on rails? Thanks.


回答1:


You could use the bunny gem: https://github.com/ruby-amqp/bunny

Here's a small example:

#!/usr/bin/env ruby
# encoding: utf-8

require "bunny"

def get_timestamp
  "#{Time.now.strftime('%H:%M:%S')}"
end

conn = Bunny.new
conn.start

queue_name = ENV['RABBITMQ_QUEUE'] || 'default_queue'

args = {}
args['x-message-ttl'] = 5000

ch = conn.create_channel
q  = ch.queue(
  queue_name,
  :arguments   => args,
  :auto_delete => false,
  :exclusive   => false,
  :durable     => true
)

puts " [*] Waiting for messages in #{q.name}. To exit press CTRL+C"

begin
  q.subscribe(:block => true, :manual_ack => true) do |delivery_info, properties, body|
    puts "[#{get_timestamp}] [ruby client] Received #{body}"

    # Acknowledge that the message has been
    # processed. This prevents:
    # - flooding the client with messages
    # - losing messages if the client dies
    ch.ack(delivery_info.delivery_tag)
  end
rescue

ensure
  conn.close
end


来源:https://stackoverflow.com/questions/31882572/how-to-create-a-rabbitmq-consumer-on-a-ruby-on-rails-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!