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])

  • 同上
相关推荐
Z3r4y2 小时前
【代码审计】ECShop_V4.1.19 SQL注入漏洞 分析
php·代码审计·ecshop
ICT系统集成阿祥6 小时前
华为CloudEngine系列交换机堆叠如何配置,附视频
开发语言·华为·php
天硕国产存储技术站7 小时前
国产固态硬盘推荐:天硕工业级SSDDRAM缓存与HMB技术详解
缓存·固态硬盘·国产ssd·国产ssd品牌
Zhangzy@7 小时前
Rust 内存对齐与缓存友好设计
spring·缓存·rust
喆星时瑜8 小时前
Windows图标修复--缓存重建教程
windows·缓存
qq_300240638 小时前
spring cache 支持多结构的 Redis 缓存管理器
spring·缓存
chian-ocean10 小时前
VecDeque 的环形缓冲区:从 `head/tail` 到 `wrapping_add`,一次把缓存、SIMD 与 `no_std` 全部打通
缓存
Wenhao.11 小时前
LeetCode LRU缓存
算法·leetcode·缓存·golang
Xiaok101812 小时前
libpcap 抓包:从打开网卡到解析数据包
服务器·网络·php