当前位置:   article > 正文

php + redis 实现延迟队列_php redis延迟队列 实现

php redis延迟队列 实现

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

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);
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
消费者

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);
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
生产者

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");

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
执行
php ./consumer.php
php ./producer.php 
  • 1
  • 2
结果
xieruixiang@xieruixiangdeMacBook-Pro bin % php ./consumer.php
this is after 30 seconds
this is after 40 seconds
this is after 50 seconds

  • 1
  • 2
  • 3
  • 4
  • 5
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/201044
推荐阅读
相关标签
  

闽ICP备14008679号