1. 封装 App\Cache\BaseCache.php
<?php
namespace App\Cache;
use Illuminate\Support\Facades\Redis;
abstract class BaseCache
{
/**
* 1 小时
*/
public const ONE_HOUR = 60 * 60;
/**
* 1 天
*/
public const ONE_DAY = self::ONE_HOUR * 24;
/**
* 7 天
*/
public const SEVEN_DAY = self::ONE_DAY * 7;
/**
* 30 天
*/
public const ONE_MONTH = self::ONE_DAY * 30;
/**
* 365 天
*/
public const ONE_YEAR = self::ONE_DAY * 365;
/**
* @var string
*/
protected static $connection = 'default';
/**
* 缓存默认前缀
* @var string
*/
public static $prefix = 'c_wop_';
/** @var \Illuminate\Redis\Connections\PhpRedisConnection $redis */
protected $redis;
/**
* BaseCache constructor.
*/
public function __construct()
{$this->redis = Redis::connection(static::$connection);
}
/**
* @return \Illuminate\Redis\Connections\PhpRedisConnection
*/
public function getRedis()
{return $this->redis;}
/**
* Notes: 格式换 key
*
* @param $format
* @param mixed ...$key
* @return string
*/
public function wrapKey($format, ...$key)
{return static::$prefix . sprintf($format, ...$key);
}
/**
* Notes: HSET 设置缓存
*
* 单个 filed-value (域 - 对) 设置到 hash 表 key 中, 并重置过期时间
* @param $key
* @param $field
* @param $value
* @param $expire
* @return bool
*/
public function hSetExpireReset($key, $field, $value, $expire)
{$result = $this->redis->hset($key, $field, $value);
if ($result) {$this->redis->expire($key, $expire);
return true;
}
return false;
}
/**
* Notes: HMSET 设置缓存
*
* 多个 filed-value (域 - 对) 设置到 hash 表 key 中, 并重置过期时间
* @param $key
* @param array $field
* @param $expire
* @return bool
*/
public function hMsetExpireReset($key, array $field, $expire)
{$result = $this->redis->hmset($key, $field);
if ($result) {$setExipre = $this->redis->expire($key, $expire);
if ($setExipre) {return true;}
return false;
}
return false;
}
}
2. 封装 App\Cache\AppCache.php
<?php
namespace App\Cache;
use WptCommon\Library\Facades\MLogger;
class AppCache extends BaseCache
{
/**
* @var string
*/
public static $prefix = 'c_app_';
/**
* Notes: 设置账号状态 && 应用状态缓存, 重置过期时间
*
* @param $key
* @param array $field
* @param $expire
* @return bool
*/
public function setAppCacheReset($key, array $field, $expire = self::ONE_DAY)
{
$content = [
'key' => $key,
'filed' => $field,
'expire' => $expire
];
$key = $this->wrapKey($key);
$result = $this->hMsetExpireReset($key, $field, $expire);
if ($result) {return true;}
MLogger::info('setAppCacheReset', ' 设置账号状态和应用状态缓存失败 ', $content);
return false;
}
/**
* Notes: 删除应用 key 缓存
*
* @param $key
* @return bool
*/
public function delAppCache($key)
{$key = $this->wrapKey($key);
$result = $this->getRedis()->del($key);
if ($result) {return true;}
MLogger::info('setAppCacheReset', ' 删除应用 key 缓存失败 ', ['key' => $key]);
return false;
}
}
正文完