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

  • 同上
相关推荐
云存储小天使12 小时前
训练效率提升50%以上:GooseFS 写缓存及其在具身智能数据处理中的应用
缓存·腾讯云·对象存储·goosefs
纯.Pure_Jin(g)15 小时前
靶场PHP函数整理+防御方式
开发语言·php·ctf
程序员夏洛15 小时前
Redis 数据过期后的删除策略是什么?
数据库·redis·缓存
鱼鳞_15 小时前
热门八股-Redis
数据库·redis·缓存
hweiyu0017 小时前
Redis命令:MIGRATE
redis·缓存
神仙别闹18 小时前
基于C++ WinPcap 的网络抓包软件
网络·c++·php
A.说学逗唱的Coke19 小时前
【人工智能专题】Redis 杀进 AI 数据层:向量搜索、语义缓存与 Agent 记忆工程从入门到踩坑
人工智能·redis·缓存
XiYang-DING19 小时前
地图城市缓存优化:ApplicationReadyEvent + Caffeine + Redis + Redisson 分布式锁
redis·分布式·缓存
斑马13920 小时前
Linux软件编程学习笔记(五)——线程
开发语言·php