简体   繁体   English

在 Ruby on Rails 上同时执行多个 Web 服务消费进程

[英]Execution of several processes of consumption of web services at the same time on Ruby on Rails

does anyone know how to run several processes at the same time?有谁知道如何同时运行多个进程? I explain the context:我解释一下上下文:

I am currently connecting to 3 web services, the results will be stored in the database, and then I show them on the screen.我目前正在连接 3 个网络服务,结果将存储在数据库中,然后我将它们显示在屏幕上。

It would be something like this:它会是这样的:

Task1 = Get to WebService method, store results, display on screen Task1 = 获取 WebService 方法,存储结果,显示在屏幕上

Task2 = Method Obtain a web service, store results, display on screen Task2 = Method 获取网络服务,存储结果,显示在屏幕上

Task3 = Method Obtain a web service, store results, display on screen任务 3 = 方法 获取 Web 服务、存储结果、显示在屏幕上

The problem is that each process takes 2 to 3 seconds, and multiplied by the 3 web services, it takes about 9 seconds.问题是每个进程需要 2 到 3 秒,乘以 3 个 Web 服务,大约需要 9 秒。

I would like to find a way to run all 3 processes at the same time, to minimize the execution time and the result is displayed faster on the screen.我想找到一种同时运行所有 3 个进程的方法,以最大程度地减少执行时间并更快地在屏幕上显示结果。 Also, in the future I will need to connect to more web services.此外,将来我将需要连接到更多的网络服务。

I use the web services with the RestClient gem我将 Web 服务与 RestClient gem 一起使用

For something that's not CPU intensive like this, you can just use the Thread class in ruby for this.对于像这样不是 CPU 密集型的东西,您可以为此使用ruby 中的Thread Using that approach the "display on screen" will all happen at once, when the response comes back.使用这种方法,当响应返回时,“屏幕上的显示”将立即发生。

Also, very feasible to push these tasks off into an ActiveJob queue, and update the client when they finish using ActionCable.此外,将这些任务推入 ActiveJob 队列并在它们完成使用 ActionCable 时更新客户端也是非常可行的。

You can use the Typhoeus gem which is a HTTP client that runs requests in parallel:您可以使用Typhoeus gem ,它是一个并行运行请求的 HTTP 客户端:

require 'typhoeus'
hydra = Typhoeus::Hydra.new
hydra.queue(Typhoeus::Request.new("www.example.com/task_1", followlocation: true))
hydra.queue(Typhoeus::Request.new("www.example.com/task_2", followlocation: true))
hydra.queue(Typhoeus::Request.new("www.example.com/task_3", followlocation: true))
hydra.run

But ultimately doing this in one big honking syncronous action is probably not going to be a very sustainable solution.但最终在一个大的同步喇叭动作中这样做可能不是一个非常可持续的解决方案。 hydra.run is still blocking and will only complete once the slowest request finishes. hydra.run仍在阻塞,只有在最慢的请求完成后才会完成。

You'll want to look into using AJAX to do this in multiple requests (from the client to your rails app) so that you can give quick user feedback and then update the page.您需要研究使用 AJAX 在多个请求(从客户端到您的 Rails 应用程序)中执行此操作,以便您可以快速提供用户反馈,然后更新页面。

Or you can use ActionCable which lets you notify clients via websocks of updates from the server.或者您可以使用 ActionCable,它可以让您通过 websocks 通知客户端来自服务器的更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM