在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;
    }
}

在这里插入图片描述

直接可用代码

<?php

namespace app\api\service;

use think\facade\Cache;

class ProductCacheService
{
    /**
     * 获取产品数据(先查缓存,缓存缺失则查库并更新)
     * @param array $ids 产品 ID 列表
     * @return array 产品数据
     */
    public function getProductsByIds(array $ids): array
    {
        $cacheKeyPrefix = $this->getRedisKey('shopProductList');

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

        $cacheKeys = array_map(fn($id) => $cacheKeyPrefix . $id, $ids);
        $cacheData = Cache::store('redis')->mget($cacheKeys);

        if ($cacheData) {
            foreach ($ids as $i => $id) {
                $key = $cacheKeys[$i];
                $item = $cacheData[$i] ?? null;
                if ($item) {
                    $cached[$id] = is_array($item) ? $item : json_decode($item, true);
                } else {
                    $missIds[] = $id;
                }
            }
        }

        // 模拟数据库查询
        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) {
                if (in_array($item['id'], $missIds)) {
                    $key = $cacheKeyPrefix . $item['id'];
                    Cache::store('redis')->set($key, json_encode($item), 60);
                    $cached[$item['id']] = $item;
                }
            }
        }

        return array_values($cached);
    }

    /**
     * 获取 Redis 缓存键
     * @param string $prefix 前缀
     * @param mixed $suffix 后缀
     * @return string 缓存键
     */
    private 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;
    }
}

TP6(ThinkPHP 6)是一个基于PHP的开源框架,它提供了丰富的功能和工具来简化Web应用程序的开发过程。在TP6使用Redis可以提高应用程序的性能和可扩展性。下面是一个演示如何在TP6使用Redis的例子: 首先,确保你已经安装了Redis和PHP的Redis扩展。然后,在TP6的配置文件`config/cache.php`中配置Redis连接信息,例如: ```php return [ // 默认缓存驱动 'default' => env('cache.driver', 'redis'), // 缓存连接方式配置 'stores' => [ // Redis缓存连接配置 'redis' => [ // 驱动方式 'type' => 'redis', // 服务器地址 'host' => '127.0.0.1', // 端口号 'port' => 6379, // 密码 'password' => '', // 缓存前缀 'prefix' => '', // 缓存有效期 0表示永久缓存 'expire' => 0, ], ], ]; ``` 接下来,在控制器中使用Redis进行缓存操作。例如,我们可以在一个控制器方法中设置和获取缓存: ```php <?php namespace app\controller; use think\facade\Cache; class Index { public function index() { // 设置缓存 Cache::store('redis')->set('name', 'John Doe'); // 获取缓存 $name = Cache::store('redis')->get('name'); return 'Hello, ' . $name; } } ``` 在上面的例子中,我们使用`Cache::store('redis')`来指定使用Redis作为缓存驱动。然后,我们可以使用`set`方法设置缓存使用`get`方法获取缓存。 请注意,以上只是一个简单的示例,你可以根据自己的需求在TP6使用更多的Redis功能和方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值