Rails 中的并行化方法 [英] Parallelizing methods in Rails

查看:28
本文介绍了Rails 中的并行化方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 网络应用程序有几十种方法,从调用 API 到处理查询结果.这些方法具有以下结构:

My Rails web app has dozens of methods from making calls to an API and processing query result. These methods have the following structure:

def method_one
  batch_query_API
  process_data
end
..........
def method_nth
  batch_query_API
  process_data
end

def summary
  method_one
  ......
  method_nth
  collect_results
end

如何在 Rails 中同时运行所有查询方法而不是按顺序运行(当然,无需启动多个工作程序)?

How can I run all query methods at the same time instead of sequential in Rails (without firing up multiple workers, of course)?

所有方法都是从单个实例变量调用的.我认为这限制了使用 Sidekiq 或 Delay 同时提交作业.

all of the methods are called from a single instance variable. I think this limits the use of Sidekiq or Delay in submitting jobs simultaneously.

推荐答案

Ruby 拥有出色的 promise gem.您的示例如下所示:

Ruby has the excellent promise gem. Your example would look like:

require 'future'

def method_one
...
def method_nth

def summary
  result1 = future { method_one }
  ......
  resultn = future { method_nth }
  collect_results result1, ..., resultn
end

很简单,不是吗?但让我们了解更多细节.这是一个未来的对象:

Simple, isn't it? But let's get to more details. This is a future object:

result1 = future { method_one }

这意味着 result1 正在后台进行评估.您可以将其传递给其他方法.但是result1还没有结果,还在后台处理.想想传递一个线程.但主要区别在于 - 当您尝试读取它时,它会阻塞并等待结果,而不是传递它.所以在上面的例子中,所有的 result1 .. resultn 变量都会在后台继续计算,但是当收集结果的时候,当你尝试实际读取这些值时,读取将等待查询完成.

It means, the result1 is getting evaluated in the background. You can pass it around to other methods. But result1 doesn't have any result yet, it is still processing in the background. Think of passing around a Thread. But the major difference is - the moment you try to read it, instead of passing it around, it blocks and waits for the result at that point. So in the above example, all the result1 .. resultn variables will keep getting evaluated in the background, but when the time comes to collect the results, and when you try to actually read these values, the reads will wait for the queries to finish at that point.

安装 promise gem 并在 Ruby 控制台中尝试以下操作:

Install the promise gem and try the below in Ruby console:

require 'future'
x = future { sleep 20; puts 'x calculated'; 10 }; nil
# adding a nil to the end so that x is not immediately tried to print in the console
y = future { sleep 25; puts 'y calculated'; 20 }; nil

# At this point, you'll still be using the console!
# The sleeps are happening in the background

# Now do:
x + y
# At this point, the program actually waits for the x & y future blocks to complete

result 中的错字,应该是result1,将echo 改为puts

Typo in result, should have been result1, change echo to puts

这篇关于Rails 中的并行化方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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