Skip to content

Instantly share code, notes, and snippets.

@eddy8
Last active June 15, 2021 01:11
Show Gist options
  • Save eddy8/0dacf73fe8890297ce1919daa3b07964 to your computer and use it in GitHub Desktop.
Save eddy8/0dacf73fe8890297ce1919daa3b07964 to your computer and use it in GitHub Desktop.
use laravel queue standalone v5.3
<?php
/**
* 初始化
*/
use Illuminate\Queue\Capsule\Manager as QueueManager;
use Illuminate\Redis\Database;
require 'vendor/autoload.php';
require 'SendEmail.php';
require 'MyQueueException.php';
$queue = new QueueManager;
$container = $queue->getContainer();
$container['config']['database.redis'] = [
'cluster' => false,
'default' => [
'host' => '127.0.0.1',
'password' => null,
'port' => 6379,
'database' => 0,
],
];
$container->singleton('redis', function ($container) {
return new Database($container['config']['database.redis']);
});
$container['config']["queue.connections.redis"] = [
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 30,
];
$queue->addConnection([
'driver' => 'redis',
'connection' => 'default',
'queue' => 'default',
'retry_after' => 30,
]);
$queue->setAsGlobal();
return $queue;
<?php
/*
composer 引入以下库
"illuminate/queue": "5.3.*",
"illuminate/redis": "5.3.*",
"illuminate/events": "5.3.*"
*/
$queue = require 'init.php';
// 分发任务
$queue->push('SendEmail', ['message' => 'Hello, world!']);
<?php
/**
* 异常处理类
*/
use \Illuminate\Contracts\Debug\ExceptionHandler;
class MyQueueException implements ExceptionHandler
{
/**
* Report or log an exception.
*
* @param \Exception $e
* @return void
*/
public function report(\Exception $e)
{
//处理异常
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Symfony\Component\HttpFoundation\Response
*/
public function render($request, \Exception $e)
{
}
/**
* Render an exception to the console.
*
* @param \Symfony\Component\Console\Output\OutputInterface $output
* @param \Exception $e
* @return void
*/
public function renderForConsole($output, \Exception $e)
{
$this->report($e);
}
}
<?php
/**
* 任务类
*/
class SendEmail
{
public function fire($job, $data)
{
try {
// 处理任务
print_r($data);
// 删除任务
$job->delete();
} catch (\Exception $e) {
//
}
}
}
<?php
/**
* worker
*/
use Illuminate\Queue\Worker;
use Illuminate\Events\Dispatcher;
use Illuminate\Queue\WorkerOptions;
$queue = require 'init.php';
$dispatcher = new Dispatcher();
$worker = new Worker($queue->getQueueManager(), $dispatcher, new MyQueueException());
$options = new WorkerOptions();
$options->maxTries = 3;
$options->timeout = 300;
$worker->daemon('redis', 'default', $options);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment