using FreeRedis; using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Text.Json; namespace Common { /// /// Ysredis工具 必须要配置在配置文件中配置redis链接 或指定 /// public class YsRedisHelp { private static string _RedisContext = sysOptionConfig.YsWebconfig.Redis; /// /// Redis 地址 默认使用 sysOptionConfig.YsWebconfig.Redis 配置信息的 /// public static string RedisContext { set { _RedisContext = value; } get { return _RedisContext; } } /// /// rendisDB /// public static RedisClient DbRedis = new RedisClient(RedisContext); /// /// 删除单个键值对 /// /// /// public static long Del(string Key) { return DbRedis.Del(Key); } /// /// 清理redis键值对 /// /// key样式 xxx* *匹配符 public static long RedisClena(string keymodel) { var keylist = DbRedis.Keys(keymodel); return DbRedis.Del(keylist); } /// /// 清理统计redis键值 谨慎清理建议指定特定时间执行一次 /// /// public static long RedisClenaRuncount() { return RedisClena("runcount_*"); } /// ///增加 通过redis统计计数 /// /// public static void RunCountAdd(string key) { key = "runcount_" + key; DbRedis.LPush(key, DateTime.Now.ToTimeStamp()); } /// /// 获取过去分钟内的统计量 /// /// /// 分钟数 /// public static int GetRunCountTime(string key, int TimeMinute) { return GetRunCountTime(key, DateTime.Now.AddMinutes(-TimeMinute)); } /// /// 获取指定时间内的数量 /// /// /// /// public static int GetRunCountTime(string key, DateTime StartTime) { try { key = "runcount_" + key; var _time = StartTime.ToTimeStamp(); var listarry = DbRedis.LRange(key, 0, DbRedis.LLen(key) - 1); if (listarry != null) { return listarry.ToList().ConvertAll(s => long.Parse(s)).Count(s => s >= _time); } else { return 0; } } catch { return 0; } } /// /// redis 缓存写入 /// /// /// /// /// 过期秒数 /// public static bool RedisSet(string Key, T setData, int TimeOut = 0) { var val = ""; if (typeof(T) != typeof(string)) { val = JsonSerializer.Serialize(setData); } else { val = setData.ToString(); } if (TimeOut > 0) { DbRedis.Set(Key, val, TimeOut); } else { DbRedis.Set(Key, val); } return true; } /// /// 读取redis中的对象数据 不存在返回null /// /// /// /// public static T RedisGet(string Key) { var val = DbRedis.Get(Key); if (val.IsNull()) { return default(T); } else { return YsJson.JsonToObject(val); } } } }