using System; using System.Collections.Generic; using System.Linq; using System.Text; using Edu.CacheManager.Base; using Edu.Common.Enum; namespace Edu.Cache.App { public class MsgUserRedisCache { /// /// 使用redis第几号库 /// public static readonly int REDIS_DB3 = 3; static readonly RedisHelper redis = new RedisHelper(REDIS_DB3); /// /// 添加用户发送验证码时间记录 /// /// 手机号码 public static bool AddUserSendCodeHistory(string mobileNumber) { string key = Cache.CacheKey.MsgStudent_Send_Code_List + mobileNumber; List codeTimeList = redis.StringGet>(key); if (codeTimeList == null) { codeTimeList = new List(); } codeTimeList.Add(DateTime.Now); TimeSpan ts = GetExpirTime(Common.Config.JwtExpirTime); return redis.StringSet>(key, codeTimeList, ts); } /// /// 设置缓存 /// /// /// /// public static void SetSendCode(string cacheKey, object Data, int JwtExpirTime) { try { TimeSpan ts = GetExpirTime(JwtExpirTime); redis.StringSet(cacheKey, Data, ts); } catch (Exception) { } } /// /// 获取缓存时长 /// /// /// private static TimeSpan GetExpirTime(int JwtExpirTime) { DateTime dt = DateTime.Now; DateTime dt2 = DateTime.Now; TimeSpan ts = dt.AddSeconds(JwtExpirTime) - dt2; return ts; } /// /// 验证是否可以发送验证码 /// /// 手机号码 /// 返回消息 public static bool CheckCanSendCode(string mobileNumber, out string message) { message = ""; //Monitor.Enter和Monitor.Exit string key = string.Concat(CacheKey.MsgStudent_Send_Code_List, mobileNumber); List codeTimeList = redis.StringGet>(key); if (codeTimeList != null) { //计算阿里短信业务限流 codeTimeList = codeTimeList.Where(t => t >= DateTime.Now.AddDays(-1)).ToList(); //去除一天以外的记录 TimeSpan ts = GetExpirTime(Common.Config.JwtExpirTime); redis.StringSet(key, codeTimeList, ts); if (codeTimeList.Count() >= 10) { message = "24小时内不能发送超过10条验证码"; return false; } if (codeTimeList.Where(t => t >= DateTime.Now.AddHours(-1)).Count() >= 5) { message = "1小时内不能发送超过5条验证码"; return false; } if (codeTimeList.Where(t => t >= DateTime.Now.AddMinutes(-1)).Count() >= 1) { message = "1分钟内只能发送1条验证码"; return false; } return true; } else { return true; } } /// /// 获取短信验证码 /// /// 账号Id /// 请求来源 /// public static string GetUserCode(object Id, ApiRequestFromEnum apiRequestFromEnum = ApiRequestFromEnum.WebAdmin) { string code = string.Empty; if (Id != null) { string cacheKey = Id.ToString(); try { code = redis.StringGet(cacheKey); } catch (Exception ex) { Common.Plugin.LogHelper.Write(ex, "GetUserCode"); } } return code; } } }