| 1 |
- <?php
/**
* 缓存服务
* @author wesmiler
*/
namespace app\index\service;
use \think\cache\driver\Redis as BaseRedis;
use think\Exception;
class RedisService
{
public static $redis = null;
public static function instance(){
try {
if(self::$redis){
return self::$redis;
}
$option = config('config.redis');
$redis = new BaseRedis($option);
return $redis;
} catch (\Exception $exception){
return false;
// throw new \RedisException('redis error:'.$exception->getMessage());
}
}
/**
* 设置
* @param $key
* @param $val
* @param int $expire
*/
public static function set($key, $val, $expire=0){
if(self::instance() == null){
return false;
}
$expire = $expire? $expire : 0;
$val = is_array($val)? json_encode($val, 256) : $val;
self::instance()->set($key, $val, $expire);
}
/**
* 获取
* @param $key
* @return bool
*/
public static function get($key){
if(self::instance() == null){
return false;
}
$cacheData = self::instance()->get($key);
$data = $cacheData? json_decode($cacheData, true) : [];
if(empty($data)){
$data = $cacheData;
}
return $data;
}
/**
* 删除
* @param $key
* @return bool
*/
public static function del($key){
if(self::instance() == null){
return false;
}
return self::instance()->rm($key);
}
/**
* 递增
* @param $key
* @return bool
*/
public static function inc($key, $step=1){
if(self::instance() == null){
return false;
}
return self::instance()->inc($key, $step);
}
/**
* 递减
* @param $key
* @return bool
*/
public static function dec($key, $step=1){
if(self::instance() == null){
return false;
}
return self::instance()->dec($key, $step);
}
/**
* 批量删除
* @param $key
* @return bool
*/
public static function delByKeys($key){
if(self::instance() == null){
return false;
}
return self::instance()->rms($key);
}
/**
* 右入队处理
* @param $key
* @param $data
*/
public static function rpush($key, $data){
return self::instance()->rpush($key, $data);
}
/**
* 左入出处理
* @param $key
*/
public static function lpop($key){
return self::instance()->lpop($key);
}
/**
* 设置有效时间
* @param $key
* @param $expire
* @return mixed
*/
public static function expire($key, $expire){
return self::instance()->expire($key, $expire);
}
/**
* 键名是否存在
* @param $key
* @param $expire
* @return mixed
*/
public static function exists($key){
return self::instance()->exists($key);
}
}
|