thinkphp8 查询数据库后加缓存

2024-05-06 603 1

为你的 getPaymentList 方法增加缓存,你可以利用 ThinkPHP 的缓存机制。你可以使用 Cache::remember 方法来进行缓存。下面是优化后的代码:

use think\facade\Cache;

public static function getPaymentList()
{
    return Cache::remember('payment_list', function () {
        return self::where('status', '=', '1')
            ->order('id asc')
            ->field('id,title')
            ->select();
    }, 3600); // 3600秒 = 1小时
}

在这个例子中:

  1. Cache::remember 会首先检查缓存中是否有键名为 'payment_list' 的缓存。
  2. 如果有,它会直接返回缓存内容。
  3. 如果没有,它会执行提供的闭包函数来获取数据,并将其缓存,缓存时间为 3600 秒(即 1 小时)。
  4. 你可以根据需要调整缓存时间。

另外,如果你想在其他地方更容易清除这个缓存,可以考虑将 'payment_list' 放入一个类常量中。这样可以更好地维护代码:

use think\facade\Cache;

class YourModel extends Model
{
    const PAYMENT_LIST_CACHE_KEY = 'payment_list';

    public static function getPaymentList()
    {
        return Cache::remember(self::PAYMENT_LIST_CACHE_KEY, function () {
            return self::where('status', '=', '1')
                ->order('id asc')
                ->field('id,title')
                ->select();
        }, 3600);
    }

    public static function clearPaymentListCache()
    {
        Cache::delete(self::PAYMENT_LIST_CACHE_KEY);
    }
}

在这个优化后的代码中:

  1. 我们使用 PAYMENT_LIST_CACHE_KEY 作为缓存键。
  2. 提供了一个 clearPaymentListCache 方法来清除缓存。

    相关文章

    织音云上新香港Platinum 8358处理器性能怪兽,爆炸高配折后最低仅需32元/月,数据对标物理机
    2025年华纳云新年焕新季,香港云4H4G3M特惠696元/年,E5物理服务器688元/月起
    莱卡云:2025年1月香港云服务器、美国云服务器、日本云服务器促销活动
    ThinkPHP6多应用多语言切换,最佳解决方案
    thinkphp thinkphp6 安装JWT
    php使用ip-api根据ip地扯获取位置信息

    评论(1)

    发布评论