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

  • 同上
相关推荐
前端不太难1 天前
RN Hooks 设计规范与反模式清单
开发语言·php·设计规范
weixin_420947641 天前
php composer update 指定包的分支非tag
开发语言·php·composer
m0_738120721 天前
渗透测试——靶机DC-4详细渗透教程
运维·网络·安全·web安全·php
此生只爱蛋1 天前
【Redis】列表List类型
数据库·redis·缓存
Neolnfra1 天前
文件包含漏洞终极指南
开发语言·安全·web安全·网络安全·系统安全·php·可信计算技术
1+2单片机电子设计1 天前
基于 STM32 的网络授权时钟系统设计与实现
开发语言·stm32·单片机·嵌入式硬件·php·51单片机
菜鸟小九1 天前
redis实战(缓存)
数据库·redis·缓存
快乐就去敲代码@!1 天前
Boot Cache Star ⭐(高性能两级缓存系统)
spring boot·redis·后端·缓存·docker·压力测试
PFinal社区_南丞1 天前
现代PHP开发实战
后端·php
廋到被风吹走1 天前
【数据库】【Redis】基本概念和特点
数据库·redis·缓存