[英]How can I ensure Sidekiq background jobs run against the same database they were initiated from
I have been implementing horizontal database sharding in Rails 6.1 using the new native multiple database connection switching.我一直在使用新的本机多数据库连接切换在 Rails 6.1 中实现水平数据库分片。 This has worked great in general, but I am trying to find the best way ensure that background jobs (via Sidekiq backed by a shared Redis DB) are run against the same database shard that they were initiated from.
这通常效果很好,但我正在尝试找到最佳方法,以确保后台作业(通过由共享 Redis DB 支持的 Sidekiq)针对启动它们的同一数据库分片运行。
eg I have two horizontal database shards, Database A and Database B. The job is enqueued from a web process while connected to database A (using a Rack middleware).例如,我有两个水平数据库分片,数据库 A 和数据库 B。作业从 web 进程排队,同时连接到数据库 A(使用 Rack 中间件)。 When that job is run later in the Sidekiq process, I would like the job to be automatically run against Database A.
当该作业稍后在 Sidekiq 进程中运行时,我希望该作业自动针对数据库 A 运行。
A brute-force way to do this would be to pass the current connected database as an argument into every job, and then, in each job, connect to the database specified in the argument using the functionality at https://guides.rubyonrails.org/active_record_multiple_databases.html .一种蛮力的方法是将当前连接的数据库作为参数传递给每个作业,然后在每个作业中,使用https://guides.rubyonrails 中的功能连接到参数中指定的数据库。 org/active_record_multiple_databases.html 。
If I was using an older solution to horizontal sharding like Apartment, the https://github.com/influitive/apartment-sidekiq gem would be exactly what I needed.如果我使用像 Apartment 这样的水平分片的旧解决方案,那么https://github.com/influitive/apartment-sidekiq gem 正是我所需要的。 However I cannot find any solutions on how to do something similar with Rails's new native functionality.
但是,我找不到任何关于如何使用 Rails 的新本机功能做类似事情的解决方案。
What is the best way to accomplish this?实现这一目标的最佳方法是什么?
This is impossible.这是不可能的。 Jobs can be created in Process A and executed in Process B. Connection sharing is impossible between processes.
作业可以在进程 A 中创建并在进程 B 中执行。进程之间无法进行连接共享。
You want to save the current shard using a client middleware and restore it in a server middleware.您想使用客户端中间件保存当前分片并在服务器中间件中恢复它。 See the notes about ActiveSupport::CurrentAttributes and the Middleware wiki page .
请参阅有关ActiveSupport::CurrentAttributes和Middleware wiki 页面的注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.