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;
}
}