当前位置:首页 > PHP > 正文内容

php redis队列

高老师6年前 (2020-07-07)PHP2984

本篇文章是给新手学习php redis队列怎么玩的。我们模拟验证码发送,通过队列完成。

(1).创建一个验证码发送接口

/**
 * 发送验证码
 */
public function sendCaptcha()
{
    //外部参数(获取手机号)
    $mobile = $_REQUEST['mobile'] ?? 0;
    if (!$mobile)
    {
        exit(json_encode(['code' => -1, 'msg' => '手机号码不得为空'], 256));
    }

    //生成短信验证码(随机数4位)
    $captcha = rand(1111, 9999);

    //组装队列数据Json
    $send_data = [
        'mobile' => $mobile,
        'captcha' => $captcha,
    ];

    //连接本地的Redis 服务
    $redis = new \Redis();
    $redis->connect('127.0.0.1', 6379);

    //向Redis的send_captcha队列投递数据
    $isPush = $redis->lPush('send_captcha', json_encode($send_data));
    if (!$isPush)
    {
        exit(json_encode(['code' => -1, 'msg' => '验证码发送失败'], 256));
    }

    //输出发送成功
    exit(json_encode(['code' => 0, 'msg' => '验证码发送成功'], 256));
}

(2).创建一个命令行队列处理脚本console.php

<?php

//连接本地的Redis 服务
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);

//循环从Redis的send_captcha队列提取数据
while (true)
{
    //从队列提取数据,超时时间5秒
    //$content正常返回第一个元素是队列名称,第二个元素是你保存的值
    $content = $redis->brPop('send_captcha', 5);
    if ($content)
    {

        //提取数据中的手机号和验证码
        $data = json_decode($content['1'], true);
        $mobile = $data['mobile'];
        $captcha = $data['captcha'];

        //进行发送,此处为伪代码
        //sendCode($mobile,$captcha);

        //输出日志
        echo "向{$mobile}发送验证码{$captcha}成功" . PHP_EOL;
    }
}

(3).模拟请求验证码接口

curl http://xxxx.com/sendCaptcha
 
//输出
{"code":0,"msg":"验证码发送成功"}

(4).启动命令行脚本php console.php,脚本输出如下

向13380793145发送验证码6188成功

解析:通过向接口提交手机号,接口会把要发送的手机号和验证码保存到队列,而另外1个命令行脚本会监听队列并及时发送验证码。假如同时来100人同时发送验证码也不担心会阻塞导致网络带宽资源耗尽。

扫描二维码推送至手机访问。

版权声明:本文由高久峰个人博客发布,如需转载请注明出处。

本文链接:https://blog.20230611.cn/post/140.html

分享给朋友:

“php redis队列” 的相关文章

php scoket,php webscoket,php webscoket 服务器

php scoket,php webscoket,php webscoket 服务器

项目需要使用websocket推送最新订单,客户服务器非linux不支持swoole,因此使用原生,直接上代码(1).PHP服务端<?php ini_set('error_reporting', E_ALL ^ E_NOTICE); ini_set...

PHP二维数组排序,PHP多维数组排序, array_multisort()

PHP二维数组排序,PHP多维数组排序, array_multisort()

使用php函数array_multisort()即可实现和SQL一样的order by排序. 例如我们需要对会员表按照主键降序排列,年龄升序排列://会员表数据 $list = []; $list[] = ['mid' =>&n...

php守护进程

php守护进程

<?php /**  * daemonize让当前脚本为守护进程执行  * @param string $callback 匿名函数  */ function daemonize($callback) {...

php finally使用

php finally使用

<?php /**  * @throws Exception  */ function curl() {     throw  new \Exception('err...

PHP Warning:  ftok(): Project identifier is invalid

PHP Warning: ftok(): Project identifier is invalid

在使用ftok生成ipc进程通信key尝试将第二个参数项目标识符传入字符串报错:PHP Warning:  ftok(): Project identifier is invalid,查阅资料发现第二个字符串只能是1个字符串,长度为1....

packagist包发布稳定版

packagist包发布稳定版

自己的composer已经发布到packagist,但是无法使用composer require easy-task/easy-task来安装,只能在配置文件使用如下方式安装:"require": {     "easy...