SqlSugarCache.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Microsoft.Extensions.Caching.Memory;
  2. namespace Admin.NET.Core;
  3. /// <summary>
  4. /// SqlSugar二级缓存
  5. /// </summary>
  6. public class SqlSugarCache : ICacheService, ISingleton, IDisposable
  7. {
  8. private static readonly Lazy<IMemoryCache> lazyCache = new(() => new MemoryCache(new MemoryCacheOptions()));
  9. public static IMemoryCache _cache => lazyCache.Value;
  10. public void Add<V>(string key, V value)
  11. {
  12. _cache.Set(key, value);
  13. }
  14. public void Add<V>(string key, V value, int cacheDurationInSeconds)
  15. {
  16. _cache.Set(key, value, TimeSpan.FromSeconds(cacheDurationInSeconds));
  17. }
  18. public bool ContainsKey<V>(string key)
  19. {
  20. return _cache.TryGetValue(key, out _);
  21. }
  22. public V Get<V>(string key)
  23. {
  24. return _cache.Get<V>(key);
  25. }
  26. public IEnumerable<string> GetAllKey<V>()
  27. {
  28. const BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
  29. var entries = _cache.GetType().GetField("_entries", flags).GetValue(_cache);
  30. var cacheItems = entries as IDictionary;
  31. var keys = new List<string>();
  32. if (cacheItems == null) return keys;
  33. foreach (DictionaryEntry cacheItem in cacheItems)
  34. {
  35. keys.Add(cacheItem.Key.ToString());
  36. }
  37. return keys;
  38. }
  39. public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
  40. {
  41. if (!_cache.TryGetValue<V>(cacheKey, out V value))
  42. {
  43. value = create();
  44. _cache.Set(cacheKey, value, TimeSpan.FromSeconds(cacheDurationInSeconds));
  45. }
  46. return value;
  47. }
  48. public void Remove<V>(string key)
  49. {
  50. _cache.Remove(key);
  51. }
  52. public void Dispose()
  53. {
  54. _cache.Dispose();
  55. }
  56. }