如何在并行多进程块中使用 ActiveRecord 事务?
How to use ActiveRecord Transactions within Parallel multi-process blocks?
我正在尝试使用 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
连接池执行并行时遇到了类似的问题。我通过改变工作类型来解决它,从进程到线程。根据 parallel
文档,如果您要显式使用 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
希望对您有所帮助。
我正在尝试使用 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
连接池执行并行时遇到了类似的问题。我通过改变工作类型来解决它,从进程到线程。根据 parallel
文档,如果您要显式使用 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
希望对您有所帮助。