Cache
<?php
return [
'default' => [
'driver' => Hyperf\Cache\Driver\RedisDriver::class,
'packer' => Hyperf\Utils\Packer\PhpSerializer::class,
'prefix' => 'c:',
],
];
Simple Cache 也就是 PSR-16 规范,本组件适配了该规范,如果您希望使用实现 Psr\SimpleCache\CacheInterface
缓存类,比如要重写 EasyWeChat
的缓存模块,可以直接从依赖注入容器中获取 Psr\SimpleCache\CacheInterface
即可,如下所示:
$cache = $container->get(\Psr\SimpleCache\CacheInterface::class);
注解方式
组件提供 Hyperf\Cache\Annotation\Cacheable
注解,作用于类方法,可以配置对应的缓存前缀、失效时间、监听器和缓存组。例如,UserService 提供一个 user 方法,可以查询对应id的用户信息。当加上 Hyperf\Cache\Annotation\Cacheable
注解后,会自动生成对应的Redis缓存,key值为user:id
,超时时间为 9000
秒。首次查询时,会从数据库中查,后面查询时,会从缓存中查。
<?php
declare(strict_types=1);
namespace App\Service;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Cache\Listener\DeleteListenerEvent;
class SystemService
{
/**
* @var EventDispatcherInterface
*/
protected $dispatcher;
public function flushCache($userId)
{
$this->dispatcher->dispatch(new DeleteListenerEvent('user-update', [$userId]));
return true;
}
}
Cacheable
例如以下配置,缓存前缀为 user
, 超时时间为 7200
, 删除事件名为 USER_CACHE
。生成对应缓存 KEY 为 c:user:1
。
use App\Models\User;
use Hyperf\Cache\Annotation\Cacheable;
/**
* @Cacheable(prefix="user", ttl=7200, listener="USER_CACHE")
*/
public function user(int $id): array
{
$user = User::query()->find($id);
return [
'user' => $user->toArray(),
'uuid' => $this->unique(),
];
}
当设置 value
后,框架会根据设置的规则,进行缓存 KEY
键命名。如下实例,当 $user->id = 1
时,缓存 KEY
为 c:userBook:_1
CachePut
不同于 Cacheable
,它每次调用都会执行函数体,然后再对缓存进行重写。所以当我们想更新缓存时,可以调用相关方法。
use App\Models\User;
/**
* @CachePut(prefix="user", ttl=3601)
*/
public function updateUser(int $id)
{
$user = User::query()->find($id);
$user->name = 'HyperfDoc';
$user->save();
return [
'user' => $user->toArray(),
'uuid' => $this->unique(),
];
}
CacheEvict
use Hyperf\Cache\Annotation\CacheEvict;
/**
* @CacheEvict(prefix="userBook", value="_#{id}")
*/
public function updateUserBook(int $id)
{
return true;
}
Hyperf\Cache\Driver\RedisDriver
会把缓存数据存放到 Redis
中,需要用户配置相应的 Redis配置
。此方式为默认方式。
协程内存驱动
本驱动乃Beta版本,请谨慎使用。
如果您需要将数据缓存到 Context
中,可以尝试此驱动。例如以下应用场景 Demo::get
会在多个地方调用多次,但是又不想每次都到 Redis
中进行查询。
<?php
return [
'co' => [
'driver' => Hyperf\Cache\Driver\CoroutineMemoryDriver::class,
'packer' => Hyperf\Utils\Packer\PhpSerializerPacker::class,
],
];