加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 渲染后如何调用方法?

发布时间:2020-12-16 23:03:56 所属栏目:百科 来源:网络整理
导读:渲染页面后,我需要在远程服务上做请求 我的控制器: after_filter :remote_action,only: :updatedef update @res = MyService.do_action foo,bar return render json: @res[:json],status: @res[:status] unless @res[:success]enddef remote_action # There
渲染页面后,我需要在远程服务上做请求

我的控制器:

after_filter :remote_action,only: :update

def update
  @res = MyService.do_action foo,bar
  return render json: @res[:json],status: @res[:status] unless @res[:success]
end

def remote_action
  # There is remote http request
end

我需要在渲染页面后调用remote_action方法

解决方法

在将模板转换为html之后运行after_filter,但在此之前将html作为对客户端的响应发送.因此,如果您正在做一些像制作远程http请求那样慢的事情,那么这会降低您的响应速度,因为它需要等待远程请求完成:换句话说,远程请求将阻止您的响应.

为了避免阻塞,你可以分叉一个不同的线程:看看

https://github.com/tra/spawnling

使用它,您只需将代码更改为

def remote_action
  Spawnling.new do
    # There is remote http request
  end
end

在回复响应之前,仍会触发远程调用,但由于它已被分叉到新线程中,因此响应不会等待远程请求返回,它将立即发生.

您还可以查看https://github.com/collectiveidea/delayed_job,它将作业放入数据库表中,其中一个单独的进程将它们拉出并执行它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读