15. 缓存(Cache)

一、安装

shell 复制代码
composer require hyperf/cache

二、配置

  • 文件:config/autoload/cache.php

    php 复制代码
    <?php
    
    return [
        'default' => [
            'driver' => Hyperf\Cache\Driver\RedisDriver::class,	// 缓存驱动,默认为 Redis
            'packer' => Hyperf\Codec\Packer\PhpSerializerPacker::class,	// 打包器
            'prefix' => 'c:',	// 缓存前缀
            'skip_cache_results' => [],		// 指定的结果不被缓存
        ],
    ];

三、使用 注解方式

1. 获取并生成缓存(#Cacheable

php 复制代码
<?php
namespace App\Service;

use App\Model\User;
use Hyperf\Cache\Annotation\Cacheable;

class CacheService
{
    #[Cacheable(prefix: 'user', value: "_#{id}", ttl: 900)]
    public function user($id)
    {
        $user = User::query()->find($id);

        if (!$user) {
            return null;
        }
        return $user->toArray();
    }
}
  • 调用
php 复制代码
<?php
namespace App\Controller;

use App\Service\CacheService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\AutoController;

#[AutoController]
class CacheController
{
    #[Inject]
    private CacheService $cacheService;

    public function index()
    {
        return $this->cacheService->user(1);
    }
}

2. 更新缓存(#CachePut

  • 同上

3. 删除缓存 (#CacheEvict

  • 同上
相关推荐
小七-七牛开发者8 天前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
两个人的幸福11 天前
Windows 桌面应用自研 PHP 队列(下):完整代码与六大工程化优化
php
BingoGo13 天前
PHP 泛型之殇 泛型 RFC 提案被拒绝
后端·php
JaguarJack13 天前
PHP 泛型之殇 泛型 RFC 提案被拒绝
后端·php
用户30745969820714 天前
PHP 扩展——从入门到理解
php
鹏仔先生14 天前
拷贝漫画APP下载页PHP程序,后台带免费AI写作
php
云水一下15 天前
从零开始学 PHP 系列(一):PHP 的前世今生与开发环境搭建
开发语言·php
xingpanvip15 天前
星盘接口开发文档:本命盘接口指南
android·开发语言·css·php·lua
ofoxcoding15 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
NeilYuen15 天前
gRPC结合FAISS构建AI助手语义缓存模块(一):设计
人工智能·缓存·faiss