許多開發者僅將 Redis 視為「更快的 Memcached」,實則 Redis 豐富的數據結構(String、Hash、List、Set、Sorted Set、HyperLogLog、Bitmap、Geospatial 等)能優雅解決大量業務難題。本文梳理電商/社交類項目中 8 大經典 Redis + PHP 實戰場景,附核心代碼片段。
喜歡數、評論數、瀏覽數、鑒定數……高併發寫入場景,INCR/HINCRBY 原子操作完美勝任。
<?php
$redis->hSet('product:123', 'like_num', 5);
$redis->hIncrBy('product:123', 'like_num', 1); // 原子 +1
$redis->hGetAll('product:123'); // 獲取全量屬性
// 輸出:['like_num' => 6]
?>
選型理由:Hash 結構將單一商品所有計數聚合在一個 Key 下,讀寫極其高效,避免大量小 Key 分散。
動態數、關注數、粉絲數、發帖數……同理採用 Hash。
$redis->hSet('user:10000', 'follow', 5);
$redis->hIncrBy('user:10000', 'follow', 1);
$redis->hGetAll('user:10000');
關注/粉絲/好友關係用 Sorted Set,Score 存時間戳,天然支援按時間排序、篩選近期關注。
// 用戶 1000 關注 1001、1002
$redis->zAdd('user:1000:follow', 1463557212, '1001');
$redis->zAdd('user:1000:follow', 1463557333, '1002');
// 用戶 2000 關注 1001、1003
$redis->zAdd('user:2000:follow', 1463577568, '1001');
$redis->zAdd('user:2000:follow', 1463896964, '1003');
// 共同關注 = 求交集
$redis->zInter('common_follow:1000:2000', ['user:1000:follow', 'user:2000:follow']);
$redis->zRange('common_follow:1000:2000', 0, -1); // ['1001']
商品列表、評論列表、@提醒列表……List/Set/Sorted Set/Hash 結構比單純 Key-Value 更貼合業務,性能不遜於 Memcached。
// 列表緩存示例
$redis->rPush('pageviews:user:', $data);
$redis->expire('pageviews:user:', 60); // 注意更新 TTL
評論頻控、發帖頻控、刷單檢測。Sorted Set 記錄最近操作時間窗口,配合 ZRANGEBYSCORE 秒級判斷。
// 5 秒內不得評論超過 2 次
$recent = $redis->zRangeByScore('user:1000:comment', time()-5, time());
if (count($recent) >= 2) exit('5秒內不能評論2次');
$redis->zAdd('user:1000:comment', time(), 'comment_content');
// 定期清理舊數據(保留 1 天熱數據,全量存日誌供 Hadoop 離線分析)
關注的人、專題、品牌動態聚合流。Sorted Set 以時間戳為 Score,支援分頁、按時間倒序。
$redis->zAdd('user:2000:feed:topic', time(), '13');
$redis->expire('user:2000:feed:topic', 86400); // 24h TTL
ZREVRANGE 降序獲取最新LPUSH 新增,LRANGE 取 Top N// 最新喜歡商品
$redis->zAdd('user:1000:product:like', time(), '3002');
$redis->zRevRange('user:1000:product:like', 0, -1, true); // 降序
// 排行榜
$redis->lPush('rank:product:like', '3002');
$redis->lRange('rank:product:like', 0, 9); // Top 10
系統通知、評論回覆、點贊提醒……Hash 結構分類計數,HINCRBY 原子增減,HGETALL 一次性讀取全部分類未讀數。
$redis->hSet('user:1000:msg:notice', 'system', 1);
$redis->hIncrBy('user:1000:msg:notice', 'comment', 1);
$redis->hGetAll('user:1000:msg:notice');
// ['system' => 1, 'comment' => 1]
List 結構實現生產者-消費者模型:LPUSH 入隊,BRPOP 阻塞式出隊,支援分布式多消費者。
// 生產者
$redis->lPush('queue:order:process', json_encode($orderData));
// 消費者
while ($data = $redis->brPop('queue:order:process', 5)) {
processOrder(json_decode($data[1], true));
}
業務:實體ID:屬性(如 product:123:like_num)Redis 不只是緩存,更是高併發架構中的「瑞士軍刀」。善用其數據結構特性,能讓業務邏輯更簡潔、性能更極致。