共计 1820 个字符,预计需要花费 5 分钟才能阅读完成。
TP5 的 redis 驱动在项目中使用遇到的问题
- 缓存的 Key 前缀取的是 config 中配置的,没有单独管理。
- 不能使用 redis 一些本身高级命令,比如 sadd 等。
- 一些常用的操作可以再次封装,比如分布式锁等。
key 的管理类
key 要统一管理起来,便于后续的阅读以及扩展
<?php | |
namespace libs; | |
/** | |
* 缓存 key 映射类:缓存 KEY 要统一配置,便于后期批量更改和管理 | |
* 注意其命名规则:项目名:模块名:名称:类型 tkmall:mem:uid:hash | |
* Class CacheKeyMap | |
* @package libs | |
*/ | |
class CacheKeyMap | |
{ | |
public static $prefix = 'tkmall:'; | |
/** | |
* 基于会员 uid 的 hash,管理会员资料 | |
* @param $uid | |
* @param int $prefix | |
* @return string | |
*/ | |
public static function memberUidHash($uid,$prefix=0) | |
{if($prefix){ | |
// 用于 keys,scan 等命令 | |
return self::$prefix . 'mem:' . $uid .':*'; | |
} | |
return self::$prefix . 'mem:' . $uid .':hash'; | |
} | |
} |
libsRedis
<?php | |
namespace libs; | |
use think\cache\driver\Redis as tpRedis; | |
/** | |
* 定制化的 redis | |
* Class Redis | |
* @package libs | |
*/ | |
class Redis extends tpRedis{ | |
protected static $_instance = null; | |
/** | |
* 获取单例 redis 对象,一般用此方法实例化 | |
* @return Redis|null | |
*/ | |
public static function getInstance() | |
{if(!is_null(self::$_instance)){return self::$_instance;} | |
self::$_instance = new self(); | |
return self::$_instance; | |
} | |
/** | |
* 架构函数 | |
* Redis constructor. | |
*/ | |
public function __construct() | |
{$options = config('cache.redis'); | |
$options['prefix'] = CacheKeyMap::$prefix; | |
parent::__construct($options); | |
} | |
/** | |
* 覆写,实际的缓存标识以 CacheKeyMap 来管理 | |
* @access protected | |
* @param string $name 缓存名 | |
* @return string | |
*/ | |
protected function getCacheKey($name) | |
{return $name;} | |
/** | |
* redis 排重锁 | |
* @param $key | |
* @param $expires | |
* @param int $value | |
* @return mixed | |
*/ | |
public function redisLock($key, $expires, $value = 1) | |
{ | |
// 在 key 不存在时, 添加 key 并 $expires 秒过期 | |
return $this->handler()->set($key, $value, ['nx', 'ex' => $expires]); | |
} | |
/** | |
* 调用缓存类型自己的高级方法 | |
* @param $method | |
* @param $args | |
* @return mixed|void | |
* @throws \Exception | |
*/ | |
public function __call($method,$args){if(method_exists($this->handler, $method)){return call_user_func_array(array($this->handler,$method), $args); | |
}else{exception(__CLASS__.':'.$method.'不存在'); | |
return; | |
} | |
} | |
} |
服务提供者配置
app/provider.php
// 应用容器绑定定义 | |
return ['redis' => 'libs\Redis']; |
使用
$redis = $this->app['redis']; | |
$redis->hMSet(CacheKeyMap::memberUidHash($uid), ['name' => 'Joe', 'salary' => 2000]); |
正文完