def fanout_to_followers(cls, tweet): # this is to create a fanout task in message queue configured by celery # parameter is tweet. any worker monitoring the message query is able to get the task # the worker process will execute fanout_newsfeeds_task() to complete the async task # if the task need 10s, it will spend on worker process, # not spend on sending tweet process. so delay will be execute and finish immidiately. # note: delay parameter must be a value that can be celery to serialize # because worker process is independent process, even another machine. # so, it can't know what is value in memory of the web process. # thus, we send tweet.id as parameter instead of tweet. because celery doesn't # know how to serialize Tweet. fanout_newsfeeds_main_task.delay(tweet.id, tweet.user_id)
def fanout_to_followers(cls, tweet): # 这句话的作用是,在 celery 配置的 message queue 中创建一个 fanout 的任务 # 参数是 tweet。任意一个在监听 message queue 的 worker 进程都有机会拿到这个任务 # worker 进程中会执行 fanout_newsfeeds_task 里的代码来实现一个异步的任务处理 # 如果这个任务需要处理 10s 则这 10s 会花费在 worker 进程上,而不是花费在用户发 tweet # 的过程中。所以这里 .delay 操作会马上执行马上结束从而不影响用户的正常操作。 # (因为这里只是创建了一个任务,把任务信息放在了 message queue 里,并没有真正执行这个函数) # 要注意的是,delay 里的参数必须是可以被 celery serialize 的值,因为 worker 进程是一个独立 # 的进程,甚至在不同的机器上,没有办法知道当前 web 进程的某片内存空间里的值是什么。所以 # 我们只能把 tweet.id 作为参数传进去,而不能把 tweet 传进去。因为 celery 并不知道 # 如何 serialize Tweet。 fanout_newsfeeds_main_task.delay(tweet.id, tweet.user_id)
def fanout_to_followers(cls, tweet): fanout_newsfeeds_main_task.delay(tweet.id, tweet.user_id)