static void Main(string[] args) { //Config { //var options = new JsonConfigurationHelper().Get<CacheOptions>("Cache", "", true); //if (options == null) // Console.WriteLine("配置文件错误"); } //MemeoryCache { IMemoryCache memory = new MemoryCache(Options.Create(new MemoryCacheOptions())); ICacheHandler MemoryCahce = new MemoryCacheHandler(memory); MemoryCahce.Set("a", "测试内存缓存"); MemoryCahce.Get("a"); Console.WriteLine(MemoryCahce.Get("a")); } //RedisCache { var Redis = new RedisCacheHelper(); ICacheHandler RedisCache = new RedisCacheHandler(Redis); RedisCache.Set("b", "测试Redis缓存"); RedisCache.Get("b"); Console.WriteLine(RedisCache.Get("b")); } }
public ActionResult EditConfig(string config) { var cfg = JsonHelper.FromJson <Dictionary <string, string> >(config); RedisCacheHelper.SetSMSConfig(cfg); return(Json(OperationResult.OK())); }
public ActionResult saveDataInRedis(string senderName, string receiverName, string msginput) { var lstSampleObject = RedisCacheHelper.Get <List <SampleObject> >("redisChat"); if (lstSampleObject == null) { lstSampleObject = new List <SampleObject> { new SampleObject { senderUName = senderName, receiverUName = receiverName, textMsg = msginput } }; } else { lstSampleObject.Add( new SampleObject { senderUName = senderName, receiverUName = receiverName, textMsg = msginput }); } RedisCacheHelper.Set("redisChat", lstSampleObject); return(Json(new { status = true })); }
public IHttpActionResult GetEmployeeById(int id) { RedisKey cacheKey = "employee_" + id; string cacheValue = null; if (Global._enableRedisCache) { cacheValue = RedisCacheHelper.GetValueByKey(cacheKey); } if (cacheValue == null) { try { EmployeeModel model = new EmployeeModel(); var employee = model.GetById(id); //RedisCacheHelper.SetKeyValue(cacheKey, new JavaScriptSerializer().Serialize(employee)); return(Content(HttpStatusCode.OK, employee)); } catch (CDSException cdsEx) { return(Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId))); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, ex)); } } else { return(Ok(JsonConvert.DeserializeObject <Object>(cacheValue))); } }
private void Recive_Client(string msg, string stname) { string[] cmd = msg.Split(','); switch (cmd[0]) { case "ReadName": SendMsgToClient(stname, RedisCacheHelper.Get <string>("OPTest_Name")); break; case "ReadAge": SendMsgToClient(stname, RedisCacheHelper.Get <string>("OPTest_Age")); break; case "WriteName": RedisCacheHelper.Add <string>("OPTest_Name", cmd[1]); SendMsgToClient(stname, "WriteNameOK"); break; case "WriteAge": RedisCacheHelper.Add <string>("OPTest_Age", cmd[1]); SendMsgToClient(stname, "WriteAgeOK"); break; } }
public static object GetProductListNew() { const int cacheTime = 30; const string cacheKey = "product_list"; //缓存标记。 const string cacheSign = cacheKey + "_sign"; var sign = RedisCacheHelper.Get <string>(cacheSign); //获取缓存值 var cacheValue = RedisCacheHelper.Get <string>(cacheKey); if (sign != null) { return(cacheValue); //未过期,直接返回。 } else { RedisCacheHelper.Add(cacheSign, "1", DateTime.Now.AddSeconds(cacheTime)); ThreadPool.QueueUserWorkItem((arg) => { cacheValue = "2222"; //这里一般是 sql查询数据。 RedisCacheHelper.Add(cacheKey, cacheValue, DateTime.Now.AddSeconds(cacheTime * 2)); //日期设缓存时间的2倍,用于脏读。 }); return(cacheValue); } }
/// <summary> /// 注册 /// </summary> /// <param name="csRedis">csRedis</param> public static void Register(CSRedisClient csRedis) { //初始化 RedisHelper RedisHelper.Initialization(csRedis); //初始化 RedisCacheHelper RedisCacheHelper.Initialization(csRedis); }
public IHttpActionResult GetRolesByEmployeeId(int id) { RedisKey cacheKey = "employee_" + id + "_Role"; string cacheValue = RedisCacheHelper.GetValueByKey(cacheKey); if (cacheValue == null) { using (var ctx = new SFDatabaseEntities()) { var roles = ctx.EmployeeInRole .Where(s => s.EmployeeID == id && s.DeletedFlag == false) .Select(s => new EmployeeRoleModels.Detail() { UserRoleId = s.UserRoleID, UserRoleName = s.UserRole.Name }).ToList <EmployeeRoleModels.Detail>(); RedisCacheHelper.SetKeyValue(cacheKey, new JavaScriptSerializer().Serialize(roles)); return(Ok(roles)); } } else { return(Ok(new JavaScriptSerializer().Deserialize <List <Object> >(cacheValue))); } }
/// <summary> /// 清空用户登录信息 /// </summary> private void ClearUserLoginInfo() { var cookie = Request.Cookies["token"]; if (cookie != null) { RedisCacheHelper.RemoveCache(cookie.Value); cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies["token"].Expires = cookie.Expires; } if (!string.IsNullOrEmpty(PageReq.GetSession("UserId"))) { Yinhe.ProcessingCenter.Permissions.AuthManage._().ReleaseCache(int.Parse(PageReq.GetSession("UserId"))); } #region //清除全局author GlobalBase.ReleaseAuthentication(); GlobalBase.ReleaseSysAuthentication(); //新权限缓存清楚 #endregion FormsAuthentication.SignOut(); PageReq.ClearSession(); #region 记录登出日志 dataOp.LogSysBehavior(SysLogType.Logout, HttpContext); #endregion }
public IActionResult SetListComplexObject() { List <SampleObject> lstSampleObject = new List <SampleObject>(); if (RedisCacheHelper.GetDatabase() != null) { lstSampleObject.Add(new SampleObject { Country = "Argentina", Id = 1, Name = "Maradona" }); lstSampleObject.Add(new SampleObject { Country = "Portugal", Id = 2, Name = "Ronaldo" }); lstSampleObject.Add(new SampleObject { Country = "Puskas", Id = 3, Name = "Hungary" }); RedisCacheHelper.Set("test2", lstSampleObject); } return(RedirectToActionPermanent("Index")); }
public List <TransactionRecordModel> GetListLatest(int total) { var list = _transactionRepository.ListLatest(total); RedisCacheHelper.TrySetCache(ConfigDataKey.LatestTransactionListCacheKey, list); return(list); }
public IHttpActionResult GetCompanyById() { int companyId = GetCompanyIdFromToken(); RedisKey cacheKey = "external_company_" + companyId; string cacheValue = RedisCacheHelper.GetValueByKey(cacheKey); if (cacheValue == null) { CompanyModels companyModel = new CompanyModels(); try { CompanyModels.Detail_readonly company = companyModel.getCompanyByIdReadonly(Convert.ToInt32(companyId.ToString())); RedisCacheHelper.SetKeyValue(cacheKey, JsonConvert.SerializeObject(company)); return(Ok(company)); } catch (Exception ex) { StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex); string logAPI = "[Get] " + Request.RequestUri.ToString(); Startup._sfAppLogger.Error(logAPI + logMessage); return(InternalServerError()); } } else { return(Ok(new JavaScriptSerializer().Deserialize <Object>(cacheValue))); } }
public void RemovePromotionSku(string redisNo, string spu, string sku) { var model = CacheHelper.AutoCache <List <RedisPromotionSpuModel> >( "SFO2O.SJ_" + redisNo, "", () => { return(new List <RedisPromotionSpuModel>()); }); var spuModel = model.FirstOrDefault(p => p.Spu == spu); if (spuModel != null) { spuModel.AddTime = DateTime.Now; var skuModel = spuModel.Skus.FirstOrDefault(p => p.sku == sku); if (skuModel != null) { spuModel.Skus.Remove(skuModel); } } if (spuModel.Skus.Count == 0) { model.Remove(spuModel); } RedisCacheHelper.Add("SFO2O.SJ_" + redisNo, model, 30); }
public override void OnConfigureServices(ServiceConfigurationContext context) { context.Services.ConfigureDynamicProxy(o => { //添加AOP的配置 }); var RedisConfiguration = context.Configuration.GetSection("Redis"); context.Services.Configure <RedisOption>(RedisConfiguration); RedisOption redisOption = RedisConfiguration.Get <RedisOption>(); if (redisOption != null && redisOption.Enable) { var options = new RedisCacheOptions { InstanceName = redisOption.InstanceName, Configuration = redisOption.Connection }; var redis = new RedisCacheHelper(options, redisOption.Database); context.Services.AddSingleton(redis); context.Services.AddSingleton <ICacheHelper>(redis); } else { context.Services.AddMemoryCache(); context.Services.AddScoped <ICacheHelper, MemoryCacheHelper>(); } context.Services.Configure <QiNiuOssModel>(context.Configuration.GetSection("QiNiuOss")); context.Services.AddScoped <QiniuCloud>(); }
public ActionResult EditConfig() { var id = RedisCacheHelper.Get <int?>(RedisCacheHelper.EnterpriseMemberTypeId); ViewBag.MemberTypeId = id.HasValue ? id.Value.ToString() : string.Empty; return(PartialView()); }
public void RedisRemove() { RedisCacheHelper.Remove("kim2"); string str = RedisCacheHelper.Get <string>("kim2"); Assert.AreEqual(null, str); }
public async Task <string> GetRestaurantMenuItems(List <RestaurantMenu> menus, int _restaurantID, string pref = "BURGER") { string data = string.Empty; List <List <MenuDetails> > _menuDetails = new List <List <MenuDetails> >(); foreach (var menu in menus) { data = await GetDataAsync(ConfigurationManager.AppSettings["MenuByIdURL"] + menu.Id); Menu _menu = JsonConvert.DeserializeObject <Menu>(data); var menuItemsWithPref = _menu.MenuItemGroups.SelectMany( x => x.MenuItems .Where(y => y.Name.ToUpper().Contains(pref.ToUpper())) .Select(y => new MenuDetails { RestaurantID = _restaurantID, MenuItemId = y.Id, MenuItemName = y.Name, MenuName = menu.Name, DeliveryTypeCode = menu.DeliveryTypeCode }) ).ToList(); _menuDetails.Add((List <MenuDetails>)menuItemsWithPref); } //Creating the Cache Key as RestaurantID+PREF //For the assignment i am not converting this value to fixed lennth hash key string cacheKey = string.Format("{0}{1}", _restaurantID.ToString(), pref.ToUpper()); RedisCacheHelper.Set(GetCacheKey(_restaurantID, pref), _menuDetails); return(JsonConvert.SerializeObject(_menuDetails));; }
/// <summary> /// 获取行业类型描述列表 /// </summary> /// <param name="key"></param> /// <returns></returns> public static IList <DicsModel> GetDicsInfoByKey(string key) { try { // 全部的Dics IList <DicsModel> lstDics = RedisCacheHelper.Get <List <DicsModel> >(keyDicsInfo); if (lstDics == null || lstDics.Where(p => String.IsNullOrWhiteSpace(p.KeyName)).Count() > 0) { lstDics = new DicsBLL().GetAllDicsInfo(); RedisCacheHelper.Add(keyDicsInfo, lstDics, 60); } // 根据DicsType 获取相关的字典属性 var result = (from n in lstDics where n.DicType == key && n.LanguageVersion == (int)LanguageEnum.TraditionalChinese select n).ToList <DicsModel>(); return(result); } catch { return(null); } }
/// <summary> /// 删除任务 /// </summary> /// <param name="orderId"></param> /// <param name="taskId"></param> /// <returns></returns> public bool removeTask(String orderId, String taskId) { bool relationDeleted = new RedisCacheHelper().SetRemove(orderId + TASK, taskId); bool dataDeleted = new RedisCacheHelper().KeyDelete(taskId); return(relationDeleted && dataDeleted); }
public static IList <DicsModel> GetDicsInfoByKeyAllLanguage(string key) { try { // 全部的Dics IList <DicsModel> lstDics = RedisCacheHelper.Get <List <DicsModel> >(keyDicsInfo); if (lstDics == null) { lstDics = new DicsBLL().GetAllDicsInfo(); RedisCacheHelper.Add(keyDicsInfo, lstDics, 60); } // 根据DicsType 获取相关的字典属性 var result = (from n in lstDics where n.DicType == key select n).ToList <DicsModel>(); return(result); } catch { return(null); } }
public IHttpActionResult GetRolesByEmployeeId(int id) { RedisKey cacheKey = "employee_" + id + "_Role"; string cacheValue = null; if (Global._enableRedisCache) { cacheValue = RedisCacheHelper.GetValueByKey(cacheKey); } if (cacheValue == null) { try { EmployeeInRoleModel model = new EmployeeInRoleModel(); model.GetAllByEmployeeId(id); return(Content(HttpStatusCode.OK, model.GetAllByEmployeeId(id))); } catch (CDSException cdsEx) { return(Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId))); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, ex)); } } else { return(Content(HttpStatusCode.OK, JsonConvert.DeserializeObject <List <Object> >(cacheValue))); } }
public async Task <ActionResult> Chat(string id) { var receiverObject = await UserManager.Users.SingleOrDefaultAsync(a => a.Id == id); ViewBag.receiverName = receiverObject.UserName; var currentLoggedUser = await UserManager.FindByIdAsync(User.Identity.GetUserId()); ViewBag.SenderName = currentLoggedUser.UserName; ViewBag.currentLoggedUserName = currentLoggedUser.UserName; //Retrieve messages of loggedIn/Current User and receiver messages var lstSampleObject = RedisCacheHelper.Get <List <SampleObject> >("redisChat"); List <SampleObject> chatList = new List <SampleObject>(); if (lstSampleObject != null) { foreach (var items in lstSampleObject) { if ((items.senderUName == currentLoggedUser.UserName && items.receiverUName == receiverObject.UserName) || (items.senderUName == receiverObject.UserName && items.receiverUName == currentLoggedUser.UserName) ) { chatList.Add(items); } } } return(View(chatList)); }
// GET: IoT public async Task <ActionResult> Index() { List <Incident> incidents; using (var client = IncidentApiHelper.GetIncidentAPIClient()) { int CACHE_EXPIRATION_SECONDS = 60; //Check Cache string cachedData = string.Empty; if (RedisCacheHelper.UseCachedDataSet(Settings.REDISCCACHE_KEY_INCIDENTDATA, out cachedData)) { incidents = JsonConvert.DeserializeObject <List <Incident> >(cachedData); } else { //If stale refresh var results = await client.IncidentOperations.GetAllIncidentsAsync(); Newtonsoft.Json.Linq.JArray ja = (Newtonsoft.Json.Linq.JArray)results; incidents = ja.ToObject <List <Incident> >(); RedisCacheHelper.AddtoCache(Settings.REDISCCACHE_KEY_INCIDENTDATA, incidents, CACHE_EXPIRATION_SECONDS); } } return(View(incidents)); }
public dynamic GetAuthorizationCode(string code, string state, string clientId, string redirectUri = "") { string redisCode = RedisCacheHelper.Get <string>(tenantId, "GetCode" + clientId) ?? ""; returnData.Note = state; if (string.IsNullOrEmpty(redisCode)) { returnData.Massage = "code过期"; return(returnData); } if (!redisCode.Equals(code)) { returnData.Massage = "code有误"; return(returnData); } string accesstoken = Guid.NewGuid().ToString("N"); returnData.Massage = accesstoken; RedisCacheHelper.Add(tenantId, "GetAuthorizationCode" + clientId, accesstoken, DateTime.Now.AddMinutes(accesstokenValidTime)); RedisCacheHelper.Remove(tenantId, "GetCode" + clientId); if (!string.IsNullOrEmpty(redirectUri)) { HttpContext.Current.Response.Redirect(redirectUri + "?code=" + code + "&state=" + state, true); } return(returnData); }
public ConsumerInfo GetConsumerInfo(string consumerId) { var key = "ConsumerInfo_" + consumerId; ConsumerInfo result = null; if (RedisCacheHelper.Exists(key)) { result = RedisCacheHelper.GetCache <ConsumerInfo>(key); } if (result == null) { var doc = dataOp.FindOneByQuery(MQConsumerInfo, Query.EQ("consumerId", consumerId)); var ip = doc.String("ip"); var queueType = doc.String("queueType"); var id = doc.String("consumerId"); var isStart = doc.Int("isStart"); var lastStartTime = doc.Date("lastStartTime"); var lastEndTime = doc.Date("lastEndTime"); var lastExecTime = doc.Date("lastExecTime"); result = new ConsumerInfo() { consumerId = id, ip = ip, isStart = isStart, lastEndTime = lastEndTime, lastExecTime = lastExecTime, lastStartTime = lastStartTime, queueType = queueType }; RedisCacheHelper.SetCache(key, result, DateTime.Now.AddDays(30)); } return(result); }
public IHttpActionResult EditFormData(int id, [FromBody] CompanyModels.Update company) { JavaScriptSerializer js = new JavaScriptSerializer(); string logForm = "Form : " + js.Serialize(company); string logAPI = "[Put] " + Request.RequestUri.ToString(); if (!ModelState.IsValid || company == null) { Startup._sfAppLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm); return(BadRequest("Invalid data")); } try { CompanyModels companyModel = new CompanyModels(); companyModel.updateCompany(id, company); RedisCacheHelper.DeleteCompanyCache(id); return(Ok("Success")); } catch (Exception ex) { StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex); logMessage.AppendLine(logForm); Startup._sfAppLogger.Error(logAPI + logMessage); return(InternalServerError(ex)); } }
/// <summary> /// 获取用户信息 /// </summary> /// <param name="userInfo"></param> /// <returns></returns> public LoginInfoModel GetUserInfo(LoginInfoModel userInfo) { if (userInfo == null || userInfo.Id < 1) { return(null); } var key = CacheMenuListKey + userInfo.Id; var model = RedisCacheHelper.Get <LoginInfoModel>(key); if (model != null) { return(model); } List <int> authorityList = new List <int>(); userInfo.MenuList = GetMenuList(userInfo.UserId, ref authorityList); if (authorityList != null && authorityList.Any()) { userInfo.BusinessPermissionList = authorityList.Select(p => p).Cast <EnumBusinessPermission>().ToList(); } else { userInfo.BusinessPermissionList = new List <EnumBusinessPermission>(); } if (userInfo.MenuList == null) { userInfo.MenuList = new List <SysMenuModel>(); } RedisCacheHelper.AddSet(CacheMenuListKey + userInfo.Id, userInfo, new TimeSpan(0, 0, 10)); return(userInfo); }
public ActionResult GetEmployeeInfo(int storeId) { var storeIds = _storeContract.QueryManageStoreId(AuthorityHelper.OperatorId.Value); if (storeIds == null || storeIds.Count <= 0 || !storeIds.Contains(storeId)) { return(Json(OperationResult.Error("权限不足"))); } var key = storeId.ToString(); var storeEntry = RedisCacheHelper.GetValueFromHash <StoreCacheEntry>(RedisCacheHelper.KEY_ALL_STORE, key); if (storeEntry == null) { return(Json(OperationResult.Error("店铺信息未找到"))); } var data = _adminContract.Administrators.Where(x => x.IsDeleted == false && x.IsEnabled == true) .Where(x => x.DepartmentId.Value == storeEntry.DepartmentId.Value) .Select(a => new { a.JobPosition.JobPositionName, a.Member.MobilePhone, a.Member.UserPhoto, a.Member.RealName }).ToList() .Select(a => new { a.JobPositionName, a.MobilePhone, UserPhoto = string.IsNullOrEmpty(a.UserPhoto) ? string.Empty : WebUrl + a.UserPhoto, a.RealName }).ToList(); return(Json(new OperationResult(OperationResultType.Success, string.Empty, data))); }
public IHttpActionResult GetCompanyById(int id) { RedisKey cacheKey = "company_" + id; string cacheValue = null; if (Global._enableRedisCache) { cacheValue = RedisCacheHelper.GetValueByKey(cacheKey); } if (cacheValue == null) { CompanyModel companyModel = new CompanyModel(); try { CompanyModel.Format_Detail company = companyModel.GetById(id); //RedisCacheHelper.SetKeyValue(cacheKey, JsonConvert.SerializeObject(company)); return(Content(HttpStatusCode.OK, company)); } catch (CDSException cdsEx) { return(Content(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId))); } catch (Exception ex) { return(Content(HttpStatusCode.InternalServerError, ex)); } } else { return(Content(HttpStatusCode.OK, JsonConvert.DeserializeObject(cacheValue))); } }
public HttpResponseMessage GetAllowDomainByCompanyId(int id) { RedisKey cacheKey = "company_" + id + "_allowDomain"; string cacheValue = null; if (Global._enableRedisCache) { cacheValue = RedisCacheHelper.GetValueByKey(cacheKey); } if (cacheValue == null) { CompanyModel companyModel = new Models.CompanyModel(); try { CompanyModel.Format_Detail company = companyModel.GetById(id); //RedisCacheHelper.SetKeyValue(cacheKey, new JavaScriptSerializer().Serialize(company)); return(Request.CreateResponse(HttpStatusCode.OK, company.AllowDomain)); } catch (CDSException cdsEx) { return(Request.CreateResponse(HttpStatusCode.BadRequest, CDSException.GetCDSErrorMessageByCode(cdsEx.ErrorId))); } catch (Exception ex) { return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex)); } } else { return(Request.CreateResponse(HttpStatusCode.OK, JsonConvert.DeserializeObject <CompanyModel.Format_Detail>(cacheValue).AllowDomain)); } }
// i dont know how to use the As<T> method //[Fact] public void should_add_null_string_if_value_is_null_moq() { //ClientManagerMock = new Mock<IRedisClientsManager>(); //var cacheMock = new Mock<ICacheClient>(); //RedisClientMock = cacheMock.As<IRedisClient>(); var cacheMock = RedisClientMock.As<ICacheClient>(); var cacheClient = new RedisCacheHelper(); //RedisClientMock.As<ICacheClient>(); Mock.Get<ICacheClient>(cacheMock.Object).Setup(x => x.Add(DEFAULT_KEY, RedisCacheHelper.NULL_DATA)).Returns(true); //setup ClientManagerMock.Setup(x => x.GetClient()).Returns(RedisClientMock.Object); //var cacheClient = RedisClientMock as Mock<ICacheClient>; cacheMock.Setup(x => x.Add(DEFAULT_KEY, It.Is<String>(m => m.EqualsOrdinalIgnoreCase(RedisCacheHelper.NULL_DATA)))).Returns(true); //RedisClientMock.Setup(x => x.IncrementValue(It.IsAny<string>())); RedisCacheHelper._redisClientManager = ClientManagerMock.Object; // call service cacheClient.AddNullableData(DEFAULT_KEY, default(String), 20); //verify //cacheMock.Verify(x => x.Add(DEFAULT_KEY, It.Is<String>(m => m.EqualsOrdinalIgnoreCase(RedisCacheHelper.NULL_DATA)))); cacheMock.Verify(x => x.Add<String>(DEFAULT_KEY, It.Is<String>(m => m.EqualsOrdinalIgnoreCase(RedisCacheHelper.NULL_DATA))), Times.Once()); // for the redisfact uts RedisCacheHelper._redisClientManager = null; }