1.fastadmin后台安装消息队列插件
这个他会帮我们自动 topthink/think-queue 这个包;
手动安装方式:
composer require topthink/think-queue:v1.1.6
2.配置队列的连接信息
找到 application/extra/queue.php
(1)redis连接方式(推荐使用,主要是快)
return [
//'connector' => 'Sync'
'connector' => 'redis', // 队列驱动使用 redis
'host' => '127.0.0.1', // redis 主机地址
'password' => 'xiaotao', // redis 密码
'port' => 6379, // redis 端口
'select' => 2, // redis db 库, 0-15
'timeout' => 0, // redis 超时时间
'persistent' => false, // redis 持续性,连接复用
];
(2)mysql连接方式
return [
'connector' => 'database',
'expire' => 60,
'default' => 'task', //默认任务名称
'table' => 'bro_faqueue_jobs', //存放的数据库表
'dsn' => [
'type' => 'mysql',
'database' => 'test', //数据库名
'hostname' => '127.0.0.1', //主机地址
'username' => 'test', //连接用户名
'password' => 'test888', //密码
'prefix' => '',
],
];
3.写入队列任务代码
创建队列类Task.php,名字根据需求自起;
<?php
namespace app\queue;
use app\common\controller\Pay;
use app\common\model\ShopOrder;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use think\queue\Job;
class Task
{
public function teamOpen(Job $job,$data){
Log::init([
'type'=>'file',
'path' => LOG_PATH.'logs/task'
]);
try {
//队列任务
$orderModel = new ShopOrder();
$orders = collection($orderModel->with('goodsDetail')->where(['team_code'=>$data['team_code'],'order_status'=>14])->select())->toArray();
$update = [];
if ($orders){
$pay = new Pay();
foreach ($orders as $k =>$v){
$details = $v['goodsDetail'];
$youhui = $details['pay_price'] - $details['num']*$details['team_base_price'];
if ($youhui > 0 && $details['team_base_price']>0){
$pay->refound($v['order_no'],$v['serial_no'],get_order_sn('U').$k,$v['pay_price'],round($youhui,2));
}
$update[] = [
'id'=>$v['id'],
'order_status'=> $v['server_type'] == 1 ? 3 : 4,
'team_price'=> $details['num']*$details['team_base_price']
];
}
}
!empty($update) && $orderModel->saveAll($update);
$job->delete();
}catch (Exception $e){
Log::write($e);
}
return true;
}
public function failed($data)
{
//消息失败方法
}
}
4.进行消费,加入队列任务
3,启用队列,查看执行信息
php think queue:listen --queue 队列名