已展示用户的文章列表为例
require_once '../../CacheRedis.php';
$server = '127.0.0.1:6379';
$redis = CacheRedis::getInstance($server);
// 用户的文章列表
$user_id = 12;
$key = 'user:article:list:' . $user_id;
$article_ids = [1,2,3,4,5,6,7,8,9,10];
// 模拟用户发布文章流程
foreach ($article_ids as $article_id) {
// 选取lpush或rpush要根据业务场景,我们这里是想要优先展示最新的文章
$res = $redis->lPush($key, $article_id);
$res = $redis->expire($key, 5);
}
// 模拟访问用户文章列表流程
$page = 0;
$page_count = 2;
do {
$start = $page * $page_count;
$end = $start + $page_count - 1;
// 要注意, end是结束为止的下标
if (!$redis->exists($key)) {
// 从db获取文章列表
// 种缓存
}
$list = $redis->lRange($key, $start, $end);
if (empty($list)) {
break;
}
var_dump($list);
$page++;
} while(true);
// 模拟用户下线/删除文章流程
$res = $redis->del($key);
// ps: 列表一般只存id, 具体内容,通过id再去查string,hash等, 尽量保证数据缓存的唯一性,避免修改清缓存时需清多处缓存
推荐相关精品课程: redis基础&实战教程


