Laravel中队列的Beanstalkd故障转移

时间:2015-01-30 11:30:04

标签: php laravel beanstalkd

有没有人知道Laravel队列的强大故障转移机制?

有一次,我的beanstalkd服务器在Laravel(4)队列驱动程序中触发Pheanstalk_Exception_ConnectionException时出现了某种错误(仍在弄清楚出现了什么问题)。结果,新工作无法被推到队列中。

我想要实现的目标是为QueueInterface设置某种故障转移驱动程序,它可以使用多个驱动程序实例,因此我可以定义例如' sync'或者' redis'驱动程序作为故障转移队列。然后,当beanstalkd失败时,该驱动程序将执行作业,并且不会丢失任何工作。

1 个答案:

答案 0 :(得分:3)

我只是想为你做一个小小的尝试,并希望它能给出一个想法......我认为每个人对队列都有不同的需求,所以这就是我所做的。

说实话,我只是删除了一堆我的代码,试图简化我所做的事情。我想从中尝试一下。

在你的队列配置中:

'connections' => array(
    'beanstalkd' => array(
        'driver' => 'beanstalk_extended',
        'host'   => 'my.ip.address',
        'queue'  => 'default',
        'ttr'    => 60,
    ),
    'my_fallback' => array(
        'driver' => 'sync',
    ),
);

在ServiceProvider @ boot中:

/**
 * Boot the Beanstalkd queue.
 */
protected function bootQueue()
{
    $this->app['queue']->extend('beanstalk_extended', function () {
        return new BeanstalkConnector;
    });

    $this->app->bindShared('queue.failer', function($app) {
        $config = $app['config']['queue.failed'];
        return new DatabaseFailedJobProvider($app['db'], $config['database'], $config['table']);
    });

    $this->app->bindShared('queue.worker', function($app) {
        return new Worker($app['queue'], $app['queue.failer'], $app['events']);
    });
}

连接器:

<?php namespace App\Framework\Queue\Connectors;

use Illuminate\Queue\Connectors\ConnectorInterface;
use Pheanstalk_Pheanstalk as Pheanstalk;
use App\Framework\Queue\Beanstalk;

class BeanstalkConnector implements ConnectorInterface
{

/**
 * Establish a queue connection.
 *
 * @param  array $config
 * @return \Illuminate\Queue\QueueInterface
 */
    public function connect(array $config)
    {
        $pheanstalk = new Pheanstalk($config['host']);
        $bean = new Beanstalk($pheanstalk, $config['queue'], array_get($config, 'ttr', Pheanstalk::DEFAULT_TTR));
       return $bean;
    }
}

然后在Beanstalkd扩展名中:

/**
 * Push a new job onto the queue.
 *
 * @param  string $job
 * @param  mixed $data
 * @param  string $queue
 * @return int
 */
public function push($job, $data = '', $queue = null)
{
    try {
        $queue = $this->getQueue($queue);
        $id = parent::push($job, $data, $queue);
        return $id;
    } catch (\Exception $e) {
        return \Queue::connection('my_fallback')->push($job, $data, $queue);
    }
}