如何在Laravel中用Redis缓存数组内指定对象并将缓存与数组一同返回
Laravel 基于Redis实现数组指定对象缓存与合并返回方案
前提:已完成Laravel Redis基础配置,安装了
predis/predis扩展包或PHP Redis扩展,.env中Redis连接参数配置正确。
实现逻辑说明
用Redis哈希(Hash)结构存储缓存的水果对象,以水果名称作为哈希字段唯一标识,读取时优先读取缓存内容,未命中缓存则使用原数组数据,最终合并为统一结构返回。
步骤1:写入指定对象到Redis缓存
use Illuminate\Support\Facades\Redis; // 定义需要缓存的指定对象 $needCacheItems = [ ['fruit' => 'banana', 'color' => 'yellow'], ['fruit' => 'apple', 'color' => 'red'] ]; // 统一缓存键,避免和其他业务冲突 $cacheKey = 'business:fruits:cache'; foreach ($needCacheItems as $item) { // 哈希字段为水果名,值序列化存储 Redis::hSet($cacheKey, $item['fruit'], json_encode($item)); } // 给缓存设置过期时间,示例为1小时,可按需调整 Redis::expire($cacheKey, 3600);
步骤2:合并缓存与原数组返回
// 原数组数据 $sourceData = [ ["apple", "red"], ["banana", "yellow"], ["orange", "orange"], ]; $cacheKey = 'business:fruits:cache'; // 读取所有缓存数据并反序列化 $cachedMap = array_map( fn($value) => json_decode($value, true), Redis::hGetAll($cacheKey) ); $mergedResult = []; foreach ($sourceData as $rawItem) { $fruitName = $rawItem[0]; // 优先使用缓存数据,未命中则用原数组生成对应结构 $mergedResult[] = $cachedMap[$fruitName] ?? [ 'fruit' => $fruitName, 'color' => $rawItem[1] ]; } return $mergedResult;
可选优化方案
如果不想直接操作Redis底层方法,也可以用Laravel封装的Cache门面实现,后续切换缓存驱动无需修改业务代码:
- 写入缓存
use Illuminate\Support\Facades\Cache; Cache::put('fruit:banana', ['fruit' => 'banana', 'color' => 'yellow'], 3600); Cache::put('fruit:apple', ['fruit' => 'apple', 'color' => 'red'], 3600);
- 读取合并
$mergedResult = []; foreach ($sourceData as $rawItem) { $fruitName = $rawItem[0]; $mergedResult[] = Cache::get('fruit:' . $fruitName) ?? [ 'fruit' => $fruitName, 'color' => $rawItem[1] ]; }
内容的提问来源于stack exchange,提问作者felcon albaladejo
相关产品推荐
相关产品推荐

