public string Get(string key) { //从Redis取数据 var result = redisHelper.Get(key); if (result == null) { try { //获取锁 if (Monitor.TryEnter(LockObj)) { //从数据库取数据 result = "Select * From DbTable"; if (result != null) { //写入Redis缓存 redisHelper.Insert(key, result); } //释放锁 Monitor.Exit(LockObj); } else { Thread.Sleep(100); result = redisHelper.Get(key); } } finally { if (Monitor.IsEntered(LockObj)) { Monitor.Exit(LockObj); } } } return(result.ToString()); }
public IActionResult Index() { var cacheKey = "TheTime"; var existingTime = _redis.Get(cacheKey); if (!string.IsNullOrEmpty(existingTime)) { ViewBag.Message = "Fetched from cache : " + existingTime; } else { existingTime = DateTime.Now.ToString(); _redis.Set(cacheKey, existingTime, expirationInSeconds: 30); ViewBag.Message = "Added to cache : " + existingTime; } return(View()); }
public override void OnActionExecuting(HttpActionContext filterContext) { string token = ""; var request = ((HttpContextBase)filterContext.Request.Properties["MS_HttpContext"]).Request; token = request.Headers["token"]; if (string.IsNullOrEmpty(token)) { token = request.Params["token"]; } if (string.IsNullOrEmpty(token)) { filterContext.Response = filterContext.Request.CreateResponse(OutPutData.NewOutPutData("请授权", false)); return; } var JwtDictionary = JwtHelper.ValidateJwtToken(token); if (JwtDictionary == null) { filterContext.Response = filterContext.Request.CreateResponse(OutPutData.NewOutPutData("非法授权", false)); return; } if (string.IsNullOrEmpty(JwtDictionary["UserName"]) || string.IsNullOrEmpty(JwtDictionary["RandomNum"])) { filterContext.Response = filterContext.Request.CreateResponse(OutPutData.NewOutPutData("非法授权", false)); return; } if (!redisHelper.Exist(ConstData.UserLoginJwt + JwtDictionary["UserName"])) { filterContext.Response = filterContext.Request.CreateResponse(OutPutData.NewOutPutData("请重新登陆", false)); return; } var RedisJwtDictionary = JwtHelper.ValidateJwtToken(redisHelper.Get(ConstData.UserLoginJwt + JwtDictionary["UserName"])); if (RedisJwtDictionary["RandomNum"] != JwtDictionary["RandomNum"]) { filterContext.Response = filterContext.Request.CreateResponse(OutPutData.NewOutPutData("您的账号已在其他地方登陆", false)); return; } base.OnActionExecuting(filterContext); }