一、安装
            
            
              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])
- 同上