namespace Admin.NET.Core; /// /// SqlSugar二级缓存 /// public class SqlSugarCache : ICacheService { private static IDistributedCache _cache = App.GetService(); public void Add(string key, V value) { _cache.Set(key, Encoding.UTF8.GetBytes(JSON.Serialize(value))); } public void Add(string key, V value, int cacheDurationInSeconds) { _cache.Set(key, Encoding.UTF8.GetBytes(JSON.Serialize(value)), new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(cacheDurationInSeconds) }); } public bool ContainsKey(string key) { return _cache.Get(key) != null; } public V Get(string key) { var res = _cache.Get(key); return res == null ? default : JSON.Deserialize(Encoding.UTF8.GetString(res)); } public IEnumerable GetAllKey() { const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; var entries = _cache.GetType().GetField("_entries", flags)?.GetValue(_cache); var cacheItems = entries?.GetType().GetProperty("Keys").GetValue(entries) as ICollection; return cacheItems == null ? new List() : cacheItems.Select(u => u.ToString()).ToList(); } public V GetOrCreate(string cacheKey, Func create, int cacheDurationInSeconds = int.MaxValue) { if (!ContainsKey(cacheKey)) return JSON.Deserialize(Encoding.UTF8.GetString(_cache.Get(cacheKey))); var result = create(); Add(cacheKey, result, cacheDurationInSeconds); return result; } public void Remove(string key) { _cache.Remove(key); } }