文章目录
实现原理
代码
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);
}
}
消费者
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);
}
生产者
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