八 hyperf 缓存的使用

290 阅读1分钟

hyperf/cache 提供了基于 Aspect 实现的切面缓存,也提供了实现 Psr\SimpleCache\CacheInterface 的缓存类

一安装

composer require hyperf/cache	

二 配置

<?php

return [
    'default' => [
        'driver' => Hyperf\Cache\Driver\RedisDriver::class,
        'packer' => Hyperf\Utils\Packer\PhpSerializerPacker::class,
        'prefix' => 'c:',
    ],
];

三 注解方式使用

这个很实用,直接将函数包装成先取缓存,没有则取数据


use Hyperf\Cache\Annotation\Cacheable;

#[Cacheable(prefix: "count", value: "_#{table}_#{where}", ttl: 10, listener: "listen-tag")]
public function count($table, $where)
{
    return Db::table($table)->whereRaw($where)->count();
}

image.png

四 删缓存 (参数 listen-tag 和 value 对应的params)

use Hyperf\Cache\Listener\DeleteListenerEvent;

#[Inject]
protected EventDispatcherInterface $dispatcher;

$this->dispatcher->dispatch(new DeleteListenerEvent('listen-tag', ['table' => $t, 'where' => $where]));

五 创建cache 对象方式使用 (没啥必要不如直接操作 redis)

$cache = $container->get(\Psr\SimpleCache\CacheInterface::class);

//实现CacheInterface
public function get(string $key, mixed $default = null): mixed;

六 CachePut 注解

写法与Cacheable 一至,每次都写缓存。(更新数据时用合适)

七 CacheEvict 注解

每次运行后,将对应缓存清理。