using Furion; using Furion.DependencyInjection; using Microsoft.AspNetCore.DataProtection.KeyManagement; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EzCoreNet.Redis { public class EzCoreNetRedisService : IEzCoreNetRedisService, IScoped { public bool Add(string key, object value, int expireSeconds) { return RedisHelper.Set(key, value, expireSeconds); } public bool DelKey(string key) { RedisHelper.Del(key); return true; } public T? Get(string key) { return RedisHelper.Get(key); } public long GetTtl(string key) { return RedisHelper.Ttl(key); } public bool SetTtl(string key, int ttl) { return RedisHelper.Expire(key, ttl); } /// /// 设置一个键值 /// /// /// /// /// public bool Add(string key, T value, int expireSeconds = -1) { return RedisHelper.Set(key, value, expireSeconds); } public async Task delegateAllKeyWith(string Prefix) { // 使用Scan模式匹配所有符合前缀的key var keys = GetAllKey(Prefix); // 批量删除找到的keys if (keys != null && keys.Count() > 0) { return await RedisHelper.DelAsync(keys.ToArray()); } return 0; // 如果没有找到匹配的key,返回0 } public IEnumerable GetAllKey(string Prefix) { return RedisHelper.Keys(Prefix + "*"); } /// /// 后去一个缓存,如果没有,则从数据库中获取, /// /// /// /// 读取方法 /// 读取的数据库服务 /// /// public T? GetAndRefCacheKey(string key, Func DataFormSql, ISqlSugarClient? dc = null, int? expireSeconds = 3600) { var Data = RedisHelper.Get(key); if (Data == null && DataFormSql != null) { if (dc == null) dc = App.GetService(); Data = DataFormSql.Invoke(dc); // Data = DataFormSql.BeginInvoke(dc,ar=> DataFormSql.EndInvoke(ar),null); if (expireSeconds == null) expireSeconds = -1; if (Data != null) RedisHelper.Set(key, Data, (int)expireSeconds); } return Data; } public long Incrby(string key) { return RedisHelper.IncrBy(key); } public string Get32sn() { string formattedDate = DateTime.Now.ToString("yyyyMMdd"); var sn = Incrby($"CreatSnKey:{formattedDate}"); if (sn < 1) { //设置有效期限为24小时 SetTtl($"CreatSnKey:{formattedDate}", 24 * 60 * 60); } string re = "EZCoreCanYinLingShiGon" + formattedDate + sn.ToString(); return re; } /// /// /// /// /// /// /// public async Task TryLock(string LockKey, int expireSeconds = 600, string value = "Lock") { if (await RedisHelper.SetNxAsync(LockKey, value) == true) { if( await RedisHelper.ExpireAsync(LockKey, expireSeconds)==false) return false; return true; } else return false; } /// /// /// /// /// public async Task TryUnLock(string LockKey) { var b= await RedisHelper.DelAsync(LockKey); if(b>0) return true; else return false; } } }