在tp6中,使用redis 缓存列表。

<?php

namespace app\api\controller\Test;

use app\api\controller\Common;
use think\facade\Cache;

class Jim extends Common
{
    public function getSubjectsByIds()
    {
        $ids = [1, 2, 22,33,44,3, 4, 5];
        $cacheKeyPrefix = $this->getRedisKey('shopProductList');

        $cached = [];
        $missIds = [];

        $cacheKeys = array_map(fn($id) => $cacheKeyPrefix . $id, $ids);

        $cacheData = Cache::store('redis')->mget($cacheKeys);

        $cacheData = array_combine($cacheKeys, $cacheData); // ✅ 修复这里

        dump($cacheData);

        foreach ($ids as $i => $id) {
            $key = $cacheKeys[$i];
            $item = $cacheData[$key] ?? null;

            if ($item) {
                $cached[$id] = is_array($item) ? $item : json_decode($item, true);
            } else {
                $missIds[] = $id;
            }
        }
        dump($missIds);
        if (!empty($missIds)) {

            $dbList = [
                ['id'=>1, 'name'=>'Product 1'],
                ['id'=>2, 'name'=>'Product 2'],
                ['id'=>3, 'name'=>'Product 3'],
                ['id'=>4, 'name'=>'Product 4'],
                ['id'=>5, 'name'=>'Product 5'],
            ];

            foreach ($dbList as $item) {
                $key = $cacheKeyPrefix . $item['id'];
                Cache::store('redis')->set($key, json_encode($item), 60);
                $cached[$item['id']] = $item;
            }
//            dd($missIds);
        }

        $result = [];
        foreach ($ids as $id) {
            if (isset($cached[$id])) {
                $result[] = $cached[$id];
            }
        }

        dd($result);
    }

    public function getRedisKey(string $prefix, $suffix = ''): string
    {
        $app = config('app.app_name') ?? 'app';
        $env = config('app.env') ?? 'prod';
        $key = "{$app}:{$env}:{$prefix}";

        if (!empty($suffix)) {
            if (is_array($suffix)) {
                $suffix = implode("_", $suffix);
            }
            $key .= ":{$suffix}";
        }

        return $key;
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值