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)

  • 同上
相关推荐
仍然.5 小时前
Redis---缓存
数据库·redis·缓存
骇客野人7 小时前
微服务多级缓存架构设计
缓存·微服务·架构
北京盛世宏博7 小时前
工业环境监测选型:Modbus TCP以太网温湿度传感器部署、调试、避坑全指南
开发语言·网络·php
4SAPI8 小时前
AI API Gateway平台哪个好?从架构视角看企业多模型网关选型与实践
java·大数据·人工智能·gateway·php
ly76898 小时前
MongoDB 副本集选举风暴排查:从心跳超时到 Journal 刷盘阻塞
数据库·mongodb·php·mongodb 副本集·选举风暴·journal 刷盘·writeconcern
源图客8 小时前
浏览器开发者工具使用
开发语言·php
qetfw9 小时前
Debian iptables 防火墙:默认拒绝、SNAT 与 DNAT 验证
linux·服务器·debian·php
ESDWAN11 小时前
跨境网络频繁掉线怎么排查?从企业内网到 SD-WAN 链路的故障诊断
开发语言·网络·php
禾小西12 小时前
05丨Redis 内存快照:宕机后,如何实现快速恢复?
数据库·redis·缓存