PHP Redis 实时存储行情数据:30秒过期,保留最新20条
connect('127.0.0.1', 6379);
// 模拟行情数据,每秒更新一次
while (true) {
$time = time();
$data = array(
'symbol' => 'BTC/USD',
'price' => rand(50000, 60000),
'time' => $time,
);
// 存入 Redis
$redis->zAdd('quotes', $time, json_encode($data));
$redis->expire('quotes', 30); // 设置过期时间为30秒
// 获取最新20条数据
$quotes = $redis->zRevRange('quotes', 0, 19, true);
$quotes = array_reverse($quotes);
// 打印结果
echo '最新20条行情数据:\n';
foreach ($quotes as $quote) {
$data = json_decode($quote, true);
echo "{$data['symbol']} {$data['price']} {$data['time']}\n";
}
// 等待1秒
sleep(1);
}
?>
原文地址: https://www.cveoy.top/t/topic/obCz 著作权归作者所有。请勿转载和采集!