// 大名科技(天津)有限公司版权所有 电话:18020030720 QQ:515096995
//
// 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
using NewLife.Caching.Models;
namespace Admin.NET.Core.Service;
///
/// 系统缓存服务
///
[ApiDescriptionSettings(Order = 400)]
public class SysCacheService : IDynamicApiController, ISingleton
{
private readonly ICache _cache;
private readonly CacheOptions _cacheOptions;
public SysCacheService(ICache cache, IOptions cacheOptions)
{
_cache = cache;
_cacheOptions = cacheOptions.Value;
}
///
/// 获取缓存键名集合
///
///
[DisplayName("获取缓存键名集合")]
public List GetKeyList()
{
return _cache == Cache.Default
? _cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList()
: ((FullRedis)_cache).Search($"{_cacheOptions.Prefix}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
}
///
/// 增加缓存
///
///
///
///
[NonAction]
public bool Set(string key, object value)
{
if (string.IsNullOrWhiteSpace(key)) return false;
return _cache.Set($"{_cacheOptions.Prefix}{key}", value);
}
///
/// 增加缓存并设置过期时间
///
///
///
///
///
[NonAction]
public bool Set(string key, object value, TimeSpan expire)
{
if (string.IsNullOrWhiteSpace(key)) return false;
return _cache.Set($"{_cacheOptions.Prefix}{key}", value, expire);
}
///
/// 获取缓存
///
///
///
///
[NonAction]
public T Get(string key)
{
return _cache.Get($"{_cacheOptions.Prefix}{key}");
}
///
/// 删除缓存
///
///
///
[ApiDescriptionSettings(Name = "Delete"), HttpPost]
[DisplayName("删除缓存")]
public int Remove(string key)
{
return _cache.Remove($"{_cacheOptions.Prefix}{key}");
}
///
/// 检查缓存是否存在
///
/// 键
///
[NonAction]
public bool ExistKey(string key)
{
return _cache.ContainsKey($"{_cacheOptions.Prefix}{key}");
}
///
/// 根据键名前缀删除缓存
///
/// 键名前缀
///
[ApiDescriptionSettings(Name = "DeleteByPreKey"), HttpPost]
[DisplayName("根据键名前缀删除缓存")]
public int RemoveByPrefixKey(string prefixKey)
{
var delKeys = _cache == Cache.Default
? _cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).ToArray()
: ((FullRedis)_cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).ToArray();
return _cache.Remove(delKeys);
}
///
/// 根据键名前缀获取键名集合
///
/// 键名前缀
///
[DisplayName("根据键名前缀获取键名集合")]
public List GetKeysByPrefixKey(string prefixKey)
{
return _cache == Cache.Default
? _cache.Keys.Where(u => u.StartsWith($"{_cacheOptions.Prefix}{prefixKey}")).Select(u => u[_cacheOptions.Prefix.Length..]).ToList()
: ((FullRedis)_cache).Search($"{_cacheOptions.Prefix}{prefixKey}*", int.MaxValue).Select(u => u[_cacheOptions.Prefix.Length..]).ToList();
}
///
/// 获取缓存值
///
///
///
[DisplayName("获取缓存值")]
public object GetValue(string key)
{
return _cache == Cache.Default
? _cache.Get