diff --git a/Falcon.SugarApi/Cache/IServiceCollectionExtend.cs b/Falcon.SugarApi/Cache/IServiceCollectionExtend.cs index fc8b22f..9bdc583 100644 --- a/Falcon.SugarApi/Cache/IServiceCollectionExtend.cs +++ b/Falcon.SugarApi/Cache/IServiceCollectionExtend.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.StackExchangeRedis; using Microsoft.Extensions.DependencyInjection; +using SqlSugar; using System; namespace Falcon.SugarApi.Cache @@ -22,6 +23,7 @@ namespace Falcon.SugarApi.Cache services.AddStackExchangeRedisCache(configRedis); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); return services; } @@ -36,6 +38,7 @@ namespace Falcon.SugarApi.Cache services.AddDistributedMemoryCache(configAction); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); return services; } } diff --git a/Falcon.SugarApi/Cache/SugarCacheService.cs b/Falcon.SugarApi/Cache/SugarCacheService.cs new file mode 100644 index 0000000..c626e57 --- /dev/null +++ b/Falcon.SugarApi/Cache/SugarCacheService.cs @@ -0,0 +1,79 @@ +using Falcon.SugarApi.JsonSerialize; +using SqlSugar; +using System; +using System.Collections.Generic; + +namespace Falcon.SugarApi.Cache +{ + /// + /// SugarCache的ICacheService实现 + /// + public class SugarCacheService : ICacheService + { + /// + /// 默认缓存时间 + /// + public int DefaultcacheDurationInSeconds { get; set; } = 24 * 60 * 60; + + /// + /// 默认缓冲时间 + /// + protected TimeSpan DefaultTimeSpan => TimeSpan.FromSeconds(DefaultcacheDurationInSeconds); + + /// + /// 构造ICacheService实现 + /// + public SugarCacheService(ISugarCache cache, IJsonSerialize json) { + Cache = cache; + Json = json; + } + + /// + /// 缓冲数据提供器 + /// + public ISugarCache Cache { get; } + /// + /// json序列化 + /// + public IJsonSerialize Json { get; } + + /// + public void Add(string key, V value) => Add(key, value, DefaultcacheDurationInSeconds); + + /// + public void Add(string key, V value, int cacheDurationInSeconds) { + if (value == null) { + return; + } + var str = Json.Serialize(value); + Cache.SetStringValue(key, str, TimeSpan.FromSeconds(cacheDurationInSeconds)); + } + + /// + public bool ContainsKey(string key) { + return Get(key) != null; + } + + /// + public V Get(string key) { + _ = key ?? throw new ArgumentNullException(nameof(key)); + var str = this.Cache.GetStringValue(key); + return str.IsNullOrEmpty() ? default(V) : (V)Json.Deserialize(str, typeof(V)); + } + + /// + public IEnumerable GetAllKey() { + throw new NotImplementedException(); + } + + /// + public V GetOrCreate(string cacheKey, Func create, int cacheDurationInSeconds = int.MaxValue) { + var val = Get(cacheKey) ?? create(); + Add(cacheKey, val); + return val; + } + + /// + public void Remove(string key) => this.Cache.SetStringValue(key, null, DefaultTimeSpan); + } +}