GlobalID和内存中的ActiveRecord对象

GlobalID和内存中的ActiveRecord对象

本文介绍了ActiveJob GlobalID和内存中的ActiveRecord对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用排队系统(Sidekiq),希望迁移到ActiveJob以获得性能上的好处,即每次将ActiveRecord对象传递给工作人员时都不必查询数据库。我想问一下并确认一下,因为我不确定100%,但是我的理解是,当ActiveJob使用GlobalID传递在内存中完成的ActiveRecord对象并没有完成对数据库的单独查询时,对吗?

I'm using a queuing system (Sidekiq) and want to move to ActiveJob to gain a performance benefit of not having to query the database every time I pass an ActiveRecord object to a worker. I wanted to ask and confirm since I wasn't 100% sure but my understanding is that when ActiveJob is using the GlobalID to pass ActiveRecord objects that is all done in memory and a separate query to the database is not done, correct?

推荐答案

那是不正确的。

如果使用ActiveJob,它将把任何ActiveRecord对象序列化为global_id字符串,以保存到队列中。然后在作业开始时从该字符串再次查找它。默认情况下,该字符串仅包含应用程序名称,类名称和ID,它将使用您的数据库加载模型。

If you use ActiveJob it will serialize any ActiveRecord object into a global_id string for saving into your queue. Then look it up again from that string when the job starts. By default that string only includes the app name, class name and id, and it will use your database to load the model.

"gid://app/User/1"

DelayedJob会将您提供给它的任何对象序列化为yaml字符串并反序列化它,而不会使数据库超出加载任务。您也可以使用Sidekiq来执行此操作,而不是点击Redis来加载作业,而不接触主数据库。

DelayedJob will serialize any object you give it into a yaml string and unserialize it without hitting the DB beyond loading the job. You can do this with Sidekiq too, instead hitting Redis to load the job and not touching the primary database.

user = User.find(1)
MyJob.perform_later(user.to_yaml)

# Load the user object from the yaml
YAML::load(user.to_yaml) == user # true

您无需访问数据库即可获得对象。但是,YAML将会变得很大,并且使用Redis带来的性能损失可能不值得。

You'll get your object without a trip to the DB. However that YAML is going to be large, and the performance penalty you get with Redis might not be worth it.

您还需要注意其他一些陷阱。就数据和结构而言,对象可能已过时。如果更改代码,则由于结构更改,序列化的对象可能无法再次加载。而且,如果在序列化对象之后更新数据库,则在加载它时,您将在不知不觉中使用旧数据。

There are a few more gotchas you should look out for. The object might be out of date, in both terms of data and of structure. If you change your code, serialized object may have trouble loading again due to structure changes. And if you update the database after serializing the object, when you load it, you'll be working unknowingly with old data.

希望可以帮助您了解ActiveJob和GlobalId提供。

Hope that helps you understand what ActiveJob and GlobalId provide.

这篇关于ActiveJob GlobalID和内存中的ActiveRecord对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:12