PHP Hyperf的缓存使用方式

还没会走,老想着怎么跑。
两种使用方式
1 simpleCache
2 使用注解方式
1 只需要把Psr\SimpleCache\CacheInterface 注入就可以使用
如:
/**
* @Inject()
* @var CacheInterface
*/
protected $cache;
public function cache()
{
$cache = $this->cache->set('xxx', uniqid());
return $cache;
}
2 使用注解
a 添加简单字符
@Cacheable(prefix="cache")
public function getCache(string $name)
{
return $name;
}
方法的返回值就是缓存的值,而缓存的key,默认是 c:cache:$name,Cacheable 可以设置ttl过期时间,单位为秒
b 修改缓存
/**
* @CachePut(prefix="cache")
*/
public function putCache(string $name = 'Jack')
{
return $name;
}
c 删除缓存
/**
* @CacheEvict(prefix="cache")
*/
public function deleteCache(string $name)
{
return true;
}
d 设置对象的属性到缓存
假设有个NosenseService类,属性有name和gender
/**
* Description:
* User: Jack
* Date: 2020/7/17 15:01
* @Cacheable(prefix="test", value="#{nosenseService.name}")
*/
public function getTestName(NosenseService $nosenseService)
{
return $nosenseService->name;
}
tips:注意nosenseService 要跟变量名($nosenseService)保持一致。
e 协程缓存
在config/autoload/cache.php,额外配置一个分组
'memory' => [
'driver' => Hyperf\Cache\Driver\CoroutineMemoryDriver::class,
'packer' => Hyperf\Utils\Packer\PhpSerializerPacker::class,
'prefix' => 'c:',
],
使用的时候添加上group,这样做的好处是同时有多个方法调用获取缓存方法,不用每次都从redis获取。
/**
* @Cacheable(prefix="memory", group="memory")
*/
public function getFromMemory()
{
sleep(2);
return 'Hello '.uniqid();
}
f 自定义缓存驱动
在config/autoload/redis.php 额外配置cache选项
'cache' => [
'host' => env('REDIS_HOST', '192.168.12.13'),
'auth' => env('REDIS_AUTH', null),
'port' => (int) env('REDIS_PORT', 6379),
'db' => 1, //放入db1
'pool' => [
'min_connections' => 1,
'max_connections' => 10,
'connect_timeout' => 10.0,
'wait_timeout' => 3.0,
'heartbeat' => -1,
'max_idle_time' => (float) env('REDIS_MAX_IDLE_TIME', 60),
],
],
然后编写一个RedisDriver
namespace App\Service;
use Hyperf\Redis\RedisProxy;
use Psr\Container\ContainerInterface;
class RedisDriver extends \Hyperf\Cache\Driver\RedisDriver
{
/**
* RedisDriver constructor.
*/
public function __construct(ContainerInterface $container, array $config)
{
parent::__construct($container, $config);
$this->redis = make(RedisProxy::class, ['pool'=>'cache']);//创建一个代理
}
}
然后把config/autoload/cache.php中default配置项 driver单项配置为
\App\Service\RedisDriver::class, 这样在使用的时候就会自动写入到db为1的redis中,还可以在config/autoload/dependencies.php中建立一个映射
return [
Hyperf\Cache\Driver\RedisDriver::class=> \App\Service\RedisDriver::class
]
这样就能在redis 库1中找到刚才设置的key了。ps:redis 切换数据库 select 1;
it never too late to learn。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注