我在Yii2里使用了Redis缓存,我发觉我需要一个功能,类似原生的Redis一样,可以根据通配符查询数据。类似如下截图
请问能实现么?
看文档有的,不过我没有类似的需求,你可以看一下:
http://www.yiichina.com/doc/api/2.0/yii-caching-expressiondependency
@laughmaker #2楼 奥,好像是,看来你只有自己开发了
表达式命中缓存的需求,没有出来过这种需求
还是描述一下我的解决方法,在Yii里,缓存的Key,系统是通过如下方式生成的:
public function buildKey($key)
{
if (is_string($key)) {
$key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);
} else {
$key = md5(json_encode($key));
}
return $this->keyPrefix . $key;
}
也就是如果位数大于32,或者不是字符串,或者字符串里包含的不是纯数字和字毌,那么会通过md5做一次转换。也就是你传入的key跟最后生成存储在redis中的key不是同一个。
所以我自己做了一个方法来生成key,保证key就只是纯数字和字母组成,且不超过32位,这样就保持了一致性。
然后通过执行这个命令得到想要的keys
$keys = $this->getRedis()->executeCommand('KEYS', [$keyPattern]);
这个接口,可以执行redis的相关命令。 完整的命令在这个链接里都有。 http://doc.redisfans.com
@laughmaker [#5楼](#comment5) 可以你的代码完整的贴一下吗?,后面有类似的需求可以参考一下你的代码,多谢!
<?php /**
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*')
@laughmaker #7楼 代码格式乱了