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

  • 同上
相关推荐
Albert Edison1 天前
【Redis】Centos7.9 安装 Redis 5 教程
数据库·redis·缓存
Steadfast_GG1 天前
Redis中的通用命令
redis·缓存
酉鬼女又兒1 天前
零基础入门计算机网络:网络层核心任务、三大关键问题、两种服务类型与 TCP/IP 网际层协议体系全解析
服务器·网络·网络协议·tcp/ip·计算机网络·php·求职招聘
神仙别闹1 天前
基于 PHP + MySQL学生信息管理系统
android·mysql·php
颜笑晏晏1 天前
长输入短输出场景下的 SGLang 推理性能实测前缀缓存、PD 分离配比与参数调优
缓存·推理优化·sglang·ai infra·pd分离
真实的菜1 天前
Redis 从入门到精通(十四):Redis 7.x 新特性全解 —— 系列收官之作
数据库·redis·缓存
天启HTTP1 天前
开启全局代理后网络变慢,问题出在哪
开发语言·前端·网络·tcp/ip·php
荒-漠1 天前
phpstorm2026版本汉化
php·phpstorm
小小工匠1 天前
Redis - 缓存与数据库一致性:问题分析与解决方案
redis·缓存·性能优化·消息队列·并发
闪电悠米1 天前
黑马点评-Redis 消息队列-02_list_pubsub_limits
java·数据库·ide·redis·缓存·list·intellij-idea