我想在保存django模型时创建beanstalkd作业。为此,我正在听模型的postrongave信号,而关联的处理程序正在创建下面的beanstalkd作业(例如,在myapp/signals.py
中):
@receiver(post_save, sender=MyModel)
def create_job(sender, **kwargs):
beanstalk = beanstalkc.Connection(
host='example.com',
port=11300
)
beanstalk.use('test')
beanstalk.puts('job');
但是,我不喜欢每次收到信号时都会创建新连接的事实。我的问题是:
- 如果我连接到函数外部的beanstalkd,在模块的顶部并重复使用连接,那会很好吗?
- 但是,如果我重复使用连接,并且由于某些原因而断开了连接,整个过程都会受到影响,对吗?那么,这里有更好的解决方案?
最后,我最终遵循了这种方法:
我在common/util/beanstalkd_client.py中创建了一个类:
from django.conf import settings
import beanstalkc
class _BeanstalkdClient:
def __init__(self):
self.beanstalk = beanstalkc.Connection(
host=settings.BEANSTALKD.get('host'),
port=int(settings.BEANSTALKD.get('port'))
)
self.job = None
def watch(self, tube, ignore_default=True):
self.beanstalk.watch(tube)
if ignore_default:
self.beanstalk.ignore('default')
def use(self, tube):
self.beanstalk.use(tube)
def reserve(self):
self.job = self.beanstalk.reserve()
return self.job
def put(self, payload):
self.beanstalk.put(payload)
beanstalkd_client = _BeanstalkdClient()
这使我可以重复使用beanstalkd_client并处理内部的连接。由于Python将始终创建一个模块的实例,因此Beanstalkd_client模块将始终与Beanstalkd有一个连接。
然后在我的信号中:
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
from common.util.beanstalkd_client import beanstalkd_client
beanstalkd_client.use(settings.BEANSTALKD.get('my_tube_name'))
@receiver(post_save, sender=Address)
def es_create_index(sender, **kwargs):
beanstalkd_client.put('my awesome job!')
但是,这仍然无法处理第二点:如果打破了beanstalkd的连接怎么办!