using Atomx.Data; using Microsoft.Extensions.Caching.Distributed; using System.Text; using System.Text.Json; using System.Threading.Tasks; namespace Atomx.Data.CacheServices { public partial interface ICacheService { /// /// 设置缓存 /// /// /// /// /// 缓存时间,默认8小时 /// Task SetCacheAsync(string key, T value, double time = 8); /// /// 根据指定KEY获取数据 /// /// /// /// Task GetCacheAsync(string key); /// /// 获取指定 key 的缓存List数据 /// /// /// /// Task> GetCacheList(string key); /// /// 清除指定 key 的缓存 /// /// /// Task Remove(string key); /// /// 获取缓存的字符串内容 /// /// /// Task GetCacheString(string key); } public partial class CacheService : ICacheService { readonly DataContext _dbContext; readonly IDistributedCache _cache; public CacheService(DataContext dataContext, IDistributedCache distributedCache) { _dbContext = dataContext; _cache = distributedCache; } public Task Remove(string key) { _cache.Remove(key); return Task.CompletedTask; } public async Task GetCacheString(string key) { return await _cache.GetStringAsync(key); } public T? GetCache(string key) { try { var cacheData = _cache.GetString(key); if (cacheData != null) { try { return JsonSerializer.Deserialize(cacheData); } catch { return default; } } } catch (Exception ex) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine($"无法链接缓存服务,读取缓存数据失败,错误信息:{ex.Message}"); Console.ResetColor(); } return default; } public async Task GetCacheAsync(string key) { try { var cacheData = await _cache.GetStringAsync(key); if (cacheData != null) { try { return JsonSerializer.Deserialize(cacheData); } catch { return default; } } } catch (Exception ex) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine($"无法链接缓存服务,读取缓存数据失败,错误信息:{ex.Message}"); Console.ResetColor(); } return default; } public async Task> GetCacheList(string key) { var cacheData = await _cache.GetStringAsync(key); if (cacheData != null) { try { var data = JsonSerializer.Deserialize>(cacheData); if (data != null) { return data; } } catch { return new List(); } } return new List(); } public void SetCache(string key, T value, double time = 8) { var options = new DistributedCacheEntryOptions(); var minute = time * 60; var timspace = TimeSpan.FromMinutes(minute); options.SetSlidingExpiration(timspace); try { _cache.SetString(key, JsonSerializer.Serialize(value), options); } catch (Exception ex) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine($"无法链接缓存服务,写入缓存数据失败,错误信息:{ex.Message}"); Console.ResetColor(); } } public async Task SetCacheAsync(string key, T value, double time = 8) { var options = new DistributedCacheEntryOptions(); var minute = time * 60; var timspace = TimeSpan.FromMinutes(minute); options.SetSlidingExpiration(timspace); try { await _cache.SetStringAsync(key, JsonSerializer.Serialize(value), options); } catch (Exception ex) { Console.BackgroundColor = ConsoleColor.Red; Console.WriteLine($"无法链接缓存服务,写入缓存数据失败,错误信息:{ex.Message}"); Console.ResetColor(); } } } }