SqlSugarCache.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证。
  2. //
  3. // 必须在法律法规允许的范围内正确使用,严禁将其用于非法、欺诈、恶意或侵犯他人合法权益的目的。
  4. namespace Admin.NET.Core;
  5. /// <summary>
  6. /// SqlSugar二级缓存
  7. /// </summary>
  8. public class SqlSugarCache : ICacheService
  9. {
  10. /// <summary>
  11. /// 系统缓存服务
  12. /// </summary>
  13. private static readonly SysCacheService _cache = App.GetService<SysCacheService>();
  14. public void Add<V>(string key, V value)
  15. {
  16. _cache.Set($"{CacheConst.SqlSugar}{key}", value);
  17. }
  18. public void Add<V>(string key, V value, int cacheDurationInSeconds)
  19. {
  20. _cache.Set($"{CacheConst.SqlSugar}{key}", value, TimeSpan.FromSeconds(cacheDurationInSeconds));
  21. }
  22. public bool ContainsKey<V>(string key)
  23. {
  24. return _cache.ExistKey($"{CacheConst.SqlSugar}{key}");
  25. }
  26. public V Get<V>(string key)
  27. {
  28. return _cache.Get<V>($"{CacheConst.SqlSugar}{key}");
  29. }
  30. public IEnumerable<string> GetAllKey<V>()
  31. {
  32. return _cache.GetKeysByPrefixKey(CacheConst.SqlSugar);
  33. }
  34. public V GetOrCreate<V>(string key, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
  35. {
  36. return _cache.GetOrAdd<V>($"{CacheConst.SqlSugar}{key}", (cacheKey) =>
  37. {
  38. return create();
  39. }, cacheDurationInSeconds);
  40. }
  41. public void Remove<V>(string key)
  42. {
  43. _cache.Remove(key); // SqlSugar调用Remove方法时,key中已包含了CacheConst.SqlSugar前缀
  44. }
  45. }