using CSRedis; using DS.Module.Core; using DS.Module.RedisModule; using SqlSugar; using Microsoft.Extensions.DependencyInjection; namespace DS.Module.SqlSugar { /// /// 用官网二级缓存的案列ServiceStack自己改写的 /// Redis缓存 /// public class SqlSugarCsRedisCache : ICacheService { //private static CSRedisClient _client; private static readonly object _lockObj = new object(); //注意:SugarRedis 不要扔到构造函数里面, 一定要单例模式 private readonly IServiceProvider _serviceProvider; private readonly IRedisService redisService; public SqlSugarCsRedisCache(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; redisService = _serviceProvider.GetRequiredService(); //RedisHelper.Initialization(csRedis); } public void Add(string key, V value) { RedisHelper.Set(key, value); } public void Add(string key, V value, int cacheDurationInSeconds) { RedisHelper.Set(key, value, cacheDurationInSeconds); } public bool ContainsKey(string key) { return RedisHelper.Exists(key); } public V Get(string key) { return RedisHelper.Get(key); } public IEnumerable GetAllKey() { //性能注意: 只查sqlsugar用到的key return RedisHelper.Keys("cache:SqlSugarDataCache.*"); //个人封装问题,key前面会带上cache:缓存前缀,请根据实际情况自行修改 ,如果没有去掉前缀或者使用最下面.如果不确定,可以用最下面前面都加通配符的做法 // return RedisHelper.Keys("SqlSugarDataCache.*"); // return RedisHelper.Keys("*SqlSugarDataCache.*"); } public V GetOrCreate(string cacheKey, Func create, int cacheDurationInSeconds = int.MaxValue) { if (this.ContainsKey(cacheKey)) { var result = this.Get(cacheKey); if (result == null) { return create(); } else { return result; } } else { var result = create(); this.Add(cacheKey, result, cacheDurationInSeconds); return result; } } public void Remove(string key) { RedisHelper.Del(key); } } }