标签 消息队列 下的文章

MySQL配合ThinkPHP(tp6.0.8)实现消息队列

参考上一篇文章:Redis配合ThinkPHP(tp6.0.8)实现消息队列

配置

和Redis版本不一样地方主要在于config\queue.php配置,如下图:
微信截图_20210709161558.png

和Redis版本一样,配置文件中其他参数都是安装think-queue时默认生成的,我没有做改动。

重点部分

和Redis不同的是,MySQL实现消息队列需要两个数据库表:jobsfailed_jobs(如果是自己添加时需加上前缀),通过migrate方式生成,会自动添加表前缀。

首先,安装think-queque扩展:composer require topthink/think-migration,如果是tp5.1,则只能安装2.x版本,使用命令:composer require topthink/think-migration=2.0.*

然后,执行两条命令,分别生成jobsfailed_jobs表的迁移类文件:
php think queue:table
php think queue:failed-table

最后,执行php think migrate:run,数据库表就生成好了。

当然,也可以自行在数据库中添加这两张表,下面列出它们的结构:

CREATE TABLE `jobs` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `queue` varchar(255) NOT NULL,
 `payload` longtext NOT NULL,
 `attempts` tinyint(3) unsigned NOT NULL,
 `reserve_time` int(11) unsigned DEFAULT NULL,
 `available_time` int(11) unsigned NOT NULL,
 `create_time` int(11) unsigned NOT NULL,
 PRIMARY KEY (`id`),
 KEY `queue` (`queue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `failed_jobs` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `connection` text NOT NULL,
 `queue` text NOT NULL,
 `payload` longtext NOT NULL,
 `exception` longtext NOT NULL,
 `fail_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

剩余的操作和Redis一致,全文结束。

Redis配合ThinkPHP(tp6.0.8)实现消息队列

运行环境

Windows 10 本地环境
PHP 7.2.9
ThinkPHP v6.0.8
Redis v3.2.100

安装

tp6.0只能通过composer方式安装,而且默认框架不带ORM和Queue,都需要通过composer方式安装。tp6.0环境默认安装的是最新版think-queue,目前是3.X版本
composer require topthink/think-queue

注意:如果是tp5.1,只能安装2.X版本,命令为:composer require topthink/think-queue=2.*

验证是否安装成功,只需命令行执行:php think queue:listen -h,看到如下画面,说明安装成功。
微信截图_20210708154210.png

配置

安装成功之后,在config目录下会有一个queue.php文件,我们选择redis驱动类型,默认驱动类型是sync,即同步执行。
微信截图_20210708154515.png

- 阅读剩余部分 -