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

  • 同上
相关推荐
野犬寒鸦2 小时前
从零起步学习Redis || 第十一章:主从切换时的哨兵机制如何实现及项目实战
java·服务器·数据库·redis·后端·缓存
callJJ4 小时前
缓存雪崩、击穿、穿透是什么与解决方案
缓存
星光一影5 小时前
【OA办公系统】神点企业OA办公助手/全开源
mysql·nginx·开源·php·源代码管理
如竟没有火炬6 小时前
LRU缓存——双向链表+哈希表
数据结构·python·算法·leetcode·链表·缓存
阿湯哥7 小时前
Redis数据库隔离业务缓存对查询性能的影响分析
数据库·redis·缓存
麦兜*7 小时前
Redis 7.2 新特性实战:Client-Side Caching(客户端缓存)如何大幅降低延迟?
数据库·spring boot·redis·spring·spring cloud·缓存·tomcat
偷光8 小时前
浏览器中的隐藏IDE: Console (控制台) 面板
开发语言·前端·ide·php
he___H8 小时前
尚庭公寓中Redis的使用
数据库·redis·缓存·尚庭公寓
JaguarJack8 小时前
别再用 PHP 动态方法调用了!三个坑让你代码难以维护
后端·php
半桔8 小时前
【网络编程】网络通信基石:从局域网到跨网段通信原理探秘
linux·运维·网络协议·php