如何在 Ruby on Rails Web 应用程序上创建 RabbitMQ 使用者? [英] How to create a RabbitMQ consumer on a Ruby on Rails web app?

查看:49
本文介绍了如何在 Ruby on Rails Web 应用程序上创建 RabbitMQ 使用者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在构建一个使用 Ruby on Rails 前端和 Java 后端的 Web 应用程序.所以基本上当用户登录网站时,我希望在屏幕上显示该用户的所有交易数据历史列表.

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.

我需要这样做的方法(出于各种我不会介绍的原因)是让 Ruby 层上的代码向队列发送消息(使用 RabbitMQ,打包为 JSON 对象),该消息将是由Java层的代码从队列中取出.

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.

Java 层然后需要将其响应(事务数据历史记录,打包为 JSON 对象)发送到另一个队列,我的 Ruby 层中的代码将使用该队列,然后将其显示在浏览器上.

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.

所以这个请求/响应周期需要是异步的,我在 Ruby 层上的消费者代码还需要知道向哪个客户端显示详细信息,具体取决于它需要的消息.

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.

推荐答案

你可以使用 bunny gem:https://github.com/ruby-amqp/bunny

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

这是一个小例子:

#!/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

这篇关于如何在 Ruby on Rails Web 应用程序上创建 RabbitMQ 使用者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆