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

ruby-on-rails – 如何在并行多进程块中使用ActiveRecord事务?

发布时间:2020-12-17 02:24:47 所属栏目:百科 来源:网络整理
导读:我正在尝试使用Rails中的ActiveRecord并行更新Postgres中的条目,我的代码看起来像这样. # new_records is the result of an ActiveRecord query.Parallel.each(new_records,in_processes: 8) do |record| ActiveRecord::Base.connection_pool.with_connectio
我正在尝试使用Rails中的ActiveRecord并行更新Postgres中的条目,我的代码看起来像这样.

# new_records is the result of an ActiveRecord query.
Parallel.each(new_records,in_processes: 8) do |record|
            ActiveRecord::Base.connection_pool.with_connection do
                ActiveRecord::Base.transaction do
                    edit_record(record)
                    record.save!
                end
            end
end

当我运行它时,我收到以下错误:

ActiveRecord::StatementInvalid:
       PG::ConnectionBad: PQconsumeInput() server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

任何人都可以帮我解决如何并行正确运行ActiveRecord事务?

解决方法

尝试为ActiveRecord连接池执行并行时,我遇到了类似的问题.我通过改变工作者类型,从进程到线程来解决它.根据并行文档,如果您要使用明确的ActiveRecord连接池,则建议使用线程.

您的代码可以重写为:

Parallel.each(new_records,in_threads: 8) do |record|
   ActiveRecord::Base.connection_pool.with_connection do
       ActiveRecord::Base.transaction do
           edit_record(record)
           record.save!
        end
   end
end

我希望你觉得这有帮助.

(编辑:李大同)

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

    推荐文章
      热点阅读