SqlSugarCache.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. namespace Admin.NET.Core;
  2. /// <summary>
  3. /// SqlSugar二级缓存
  4. /// </summary>
  5. public class SqlSugarCache : ICacheService
  6. {
  7. private static IDistributedCache _cache = App.GetService<IDistributedCache>();
  8. public void Add<V>(string key, V value)
  9. {
  10. _cache.Set(key, Encoding.UTF8.GetBytes(JSON.Serialize(value)));
  11. }
  12. public void Add<V>(string key, V value, int cacheDurationInSeconds)
  13. {
  14. _cache.Set(key, Encoding.UTF8.GetBytes(JSON.Serialize(value)), new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(cacheDurationInSeconds) });
  15. }
  16. public bool ContainsKey<V>(string key)
  17. {
  18. return _cache.Get(key) != null;
  19. }
  20. public V Get<V>(string key)
  21. {
  22. var res = _cache.Get(key);
  23. return res == null ? default : JSON.Deserialize<V>(Encoding.UTF8.GetString(res));
  24. }
  25. public IEnumerable<string> GetAllKey<V>()
  26. {
  27. const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
  28. var entries = _cache.GetType().GetField("_entries", flags)?.GetValue(_cache);
  29. var cacheItems = entries?.GetType().GetProperty("Keys").GetValue(entries) as ICollection<object>;
  30. return cacheItems == null ? new List<string>() : cacheItems.Select(u => u.ToString()).ToList();
  31. }
  32. public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
  33. {
  34. if (!ContainsKey<V>(cacheKey))
  35. return JSON.Deserialize<V>(Encoding.UTF8.GetString(_cache.Get(cacheKey)));
  36. var result = create();
  37. Add(cacheKey, result, cacheDurationInSeconds);
  38. return result;
  39. }
  40. public void Remove<V>(string key)
  41. {
  42. _cache.Remove(key);
  43. }
  44. }