Hugh's Blog

PHP + Redis 简单消息队列

 

消息队列在高并发的时候,可以缓解对数据库的压力,下面使用 PHP + Redis(list) 简单模拟下这个过程。

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

$type = isset($_GET['type']) ? 'read' : 'write';

switch ($type) {
    case 'write':
        // 随机获取内容,写入队列
        $redis->lpush('articles', json_encode(randomArticle())); // lrange articles 0 -1
        $redis->close();
        break;
    case 'read':
        // 获取队列内容,下面是写入文件,也可以写入数据库
        while (true) {
            if ($article = $redis->rpop('articles')) {
                writeToFile($article);
            } else {
                sleep(1);
            }
        }
        $redis->close();
        break;
}

function randomArticle()
{
    $chars = 'abcdefghigklmnopqrstuvwxyz1234567890';
    $title = substr(str_shuffle($chars), 0, 6);
    $content = substr(str_shuffle($chars), 6);
    $time = 1420000000 + rand(1, 10000000);
    return ['title' => $title, 'content' => $content, 'time' => $time];
}

function writeToFile($string)
{
    $fp = fopen(__DIR__ . '/articles.txt', 'a');
    flock($fp, LOCK_EX) ;
    fwrite($fp, $string . "\r\n");
    flock($fp, LOCK_UN);
    fclose($fp);
}

生产消息模拟:http://localhost/redis.php

保存消息模拟:http://localhost/redis.php?type=read


参考

redis实现简单的消息队列(php)