<?php
/**
- Created by PhpStorm.
- User: HZD
- Date: 2017/8/27
- Time: 下午7:43
*/
namespace common\traits;
use Yii;
// 默认缓存时间
define('DEFAULT_CACHE_DURATION', 60 60 24);
trait RedisCache
{
/**
* @return \yii\caching\Cache
*/
public function getCache() {
return Yii::$app->getCache();
}
/**
* @return yii\redis\Connection;
*/
public function getRedis() {
return Yii::$app->cache->redis;
}
/**
* 模糊查询匹配的keys数组
* @param string $keyPattern
* @return array|bool|null|string
*/
public function getCacheKeys(string $keyPattern) {
$keys = $this->getRedis()->executeCommand('KEYS', [$keyPattern]);
return $keys;
}
/**
* @param string $key
* @return mixed
*/
public function getCacheValue(string $key) {
return $this->getCache()->get($key);
}
/**
* @param string $key
* @param $value
* @param $duration
* @return bool
*/
public function setCacheValue(string $key, $value, $duration=DEFAULT_CACHE_DURATION) {
return $this->getCache()->set($key, $value, $duration);
}
/**
* @param array $keys
*/
public function deleteCacheByKeys(array $keys=[]) {
foreach ($keys as $key) {
$this->getCache()->delete($key);
}
}
/**
* 获取key的剩余时间
* @param string $key
* @return int 剩余的ms数,key不存在,返回-2,key存在,但没有设置剩余时间返回-1
*/
public function getRemainingTime(string $key) {
return $this->getRedis()->executeCommand('PTTL', [$key]);
}
}
/**
* 产生一个随机长度的字符串,由数字和纯字母组成
* @param int $length
* @return string
*/
public function generateRandString(int $length=8) {
$str = '';
$seeds = "0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($seeds) - 1;
for($i=0; $i < $length; $i++) {
$str .= $seeds[rand(0, $max)];
}
return $str;
}
要通配符查询由某些关联字组成的keys,类似这样子就可以了。
$this->getCacheKeys('likeCount*')