php + redis 实现延迟队列

文章目录

        • 实现原理
        • 代码
        • 消费者
        • 生产者
        • 执行
        • 结果

实现原理
# redis 的zset是有序集合,可以通过分数进行排序
# 将分数设置成任务执行时间
# 通过 ZRANGEBYSCORE key min max 获取任务时间小于当前时间的任务
# 通过 ZREMRANGEBYRANK key 0 0 来移除 执行完的任务
# ZRANGEBYSCORE,ZREMRANGEBYRANK 都是按照分数从小到大排
代码

redisManger

class RedisManger
{
    private $redis;

    private $config = [
        'host' => '127.0.0.1',
        'port' => 6379
    ];

    public function __construct($redisConfig = [])
    {
        $redis = new Redis();
        $config = array_merge($this->config, $redisConfig);
        $redis->connect($config['host'], $config['port']);
        $this->redis = $redis;
    }

    public function zAdd($key, $score, $value)
    {
        $this->redis->zAdd($key, $score, $value);
    }

    public function zGet($key, $max)
    {
        return $this->redis->zRangeByScore($key, 0, $max);
    }

    public function zRemove($key)
    {
        return $this->redis->zRemRangeByRank($key, 0, 0);
    }

}

消费者

consumer


# 引入 redisManger
require "./redis.php";

$redis = new RedisManger();
$key = 'test';
while (true) {
    $data = $redis->zGet($key, time());

    if ($data) {
        foreach ($data as $value) {
            # 执行逻辑
            echo $value . PHP_EOL;
            # 移除
            $redis->zRemove($key);
        }
    }

    sleep(1);
}

生产者

producer

# 引入 redisManger
require "./redis.php";

$redis = new RedisManger();

$time = time();
$redis->zAdd('test', time() + 50, "this is after 50 seconds");
$redis->zAdd('test', time() + 30, "this is after 30 seconds");
$redis->zAdd('test', time() + 40, "this is after 40 seconds");

执行
php ./consumer.php
php ./producer.php 
结果
xieruixiang@xieruixiangdeMacBook-Pro bin % php ./consumer.php
this is after 30 seconds
this is after 40 seconds
this is after 50 seconds

你可能感兴趣的:(PHP,php,redis)