public async Task TestCache() { var distributedCache = GetService <IDistributedCache>(); var binarySerializer = GetService <IBinarySerializer>(); var inMemoryCacheHelper = new DistributedCacheHelper(distributedCache, binarySerializer); inMemoryCacheHelper.Remove("prueba"); var id = Guid.NewGuid(); var contador = 0; Func <Task <Guid> > funcionGeneraValor = () => { contador++; return(Task.FromResult(id)); }; var savingAndGetting = inMemoryCacheHelper.GetOrCreateAsync("prueba", funcionGeneraValor); var getting = inMemoryCacheHelper.GetOrCreateAsync("prueba", funcionGeneraValor); Assert.Equal(id, await savingAndGetting); Assert.Equal(id, await getting); Assert.Equal(1, contador); inMemoryCacheHelper.Remove("prueba"); var n3 = await inMemoryCacheHelper.GetOrCreateAsync("prueba", funcionGeneraValor); Assert.Equal(id, n3); Assert.Equal(2, contador); }
public override List <CacheKeyMapDescriptor> GetCacheKeyMapList(Cachelimit cacheLimit, DateTime?startDate, DateTime?endDate) { List <CacheKeyMapDescriptor> lstMap = new List <CacheKeyMapDescriptor>(); try { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); if (cacheLimit == Cachelimit.ByExpireDate) { var query = Query.And( Query.EQ("Cachelimit", cacheLimit), Query.EQ("ExpireDate", startDate), Query.EQ("ExpireDate", endDate) ); lstMap = collection.Find(query).ToList(); } else { var query = Query.And( Query.EQ("Cachelimit", cacheLimit) ); lstMap = collection.Find(query).ToList(); } return(lstMap); } catch (Exception ex) { return(lstMap); } }
public override void AddCacheKeyMap(CacheKeyMapDescriptor request) { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); if (collection != null) { try { var query = Query.And(Query.EQ("CacheKey", request.CacheKey)); collection.Remove(query); } catch (Exception ex) { } WriteConcernResult res = collection.Save(request); if (request.Cachelimit != Cachelimit.Forever) { TimeSpan timespan = request.ExpireDate.Subtract(DateTime.Now); if (!collection.IndexExists(new IndexKeysBuilder().Ascending("ExpireDate"))) { collection.EnsureIndex(new IndexKeysBuilder().Ascending("ExpireDate"), IndexOptions.SetTimeToLive(timespan)); } } } }
///// <summary> /////设置value ///// </summary> ///// <typeparam name="T"></typeparam> ///// <param name="key"></param> ///// <param name="value"></param> ///// <param name="expireDate"></param> //private override bool SetValue<T>(string key, T value, DateTime expireDate) //{ // try // { // string cacheId = CacheIdGeneratorManger.Instance.GenerateCacheId(); // OnOperating("开始写入值:starting:key:" + key + ",cacheId:" + cacheId + ",value:" + JsonConvert.SerializeObject(value) + ",expireDate:" + expireDate); // MongoDBCacheEntity cache = new MongoDBCacheEntity(); // cache.ApplicationName = this.pApplicationName; // cache.CacheId = cacheId; // cache.Created = DateTime.Now; // cache.CacheKey = key; // cache.ExpireDate = expireDate; // cache.CacheSta = CacheStatus.Effective; // cache.CacheValue = JsonConvert.SerializeObject(value); // MongoCollection<MongoDBCacheEntity> collection = DistributedCacheHelper.GetMongoDBCollection(cacheId); // if (collection != null) // { // try // { // var query = Query.And(Query.EQ("CacheKey", key)); // collection.Remove(query); // } // catch(Exception ex) // { } // WriteConcernResult res = collection.Save(cache); // OnOperating("写入完成end:key:" + key + ",cacheId:" + cacheId + ",result:" + res.Ok + "," + res.ErrorMessage); // if (res.Ok)//成功后 // { // CacheKeyMapManger.Instance.AddCacheKeyMap(key, cacheId, expireDate); // return true; // } // } // return false; // } // catch(Exception ex) // { // OnOperating("写入Excption:key:" + key + ",exception:" + JsonConvert.SerializeObject(ex)); // return false; // } //} /// <summary> /// 设置缓存 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="value"></param> /// <param name="cacheLimit"></param> /// <returns></returns> public override bool SetValue <T>(string key, T value, Cachelimit cacheLimit, DateTime?expireDate) { try { string cacheId = CacheIdGeneratorManger.Instance.GenerateCacheId(); OnOperating("开始写入值:starting:key:" + key + ",cacheId:" + cacheId + ",value:" + JsonConvert.SerializeObject(value) + ",cacheLimit:" + cacheLimit.ToString()); MongoDBCacheEntity cache = new MongoDBCacheEntity(); cache.ApplicationName = this.pApplicationName; cache.CacheId = cacheId; cache.Created = DateTime.Now; cache.CacheKey = key; cache.ExpireDate = cacheLimit == Cachelimit.Forever ? Convert.ToDateTime("2099-12-30") : (cacheLimit == Cachelimit.CurrentDay ? Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59") : Convert.ToDateTime(expireDate)); cache.CacheSta = CacheStatus.Effective; cache.CacheValue = JsonConvert.SerializeObject(value); if (cacheLimit == Cachelimit.ByExpireDate) { } MongoCollection <MongoDBCacheEntity> collection = DistributedCacheHelper.GetMongoDBCollection(cacheId, cacheLimit); if (collection != null) { try { var query = Query.And(Query.EQ("CacheKey", key)); collection.Remove(query); } catch (Exception ex) { } WriteConcernResult res = collection.Save(cache); TimeSpan timespan = cache.ExpireDate.Subtract(DateTime.Now); if (cacheLimit != Cachelimit.Forever) { if (!collection.IndexExists(new IndexKeysBuilder().Ascending("ExpireDate"))) { collection.EnsureIndex(new IndexKeysBuilder().Ascending("ExpireDate"), IndexOptions.SetTimeToLive(timespan)); } } OnOperating("写入完成end:key:" + key + ",cacheId:" + cacheId + ",result:" + res.Ok + "," + res.ErrorMessage); if (res.Ok)//成功后 { CacheKeyMapManger.Instance.AddCacheKeyMap(key, cacheId, expireDate, cacheLimit); return(true); } } return(false); } catch (Exception ex) { OnOperating("写入Excption:key:" + key + ",exception:" + JsonConvert.SerializeObject(ex)); return(false); } }
/// <summary> /// App首页瀑布流文章 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <returns></returns> public async Task <ActionResult> SelectArticleForAppHomePage(int pageIndex = 1, int pageSize = 30) { var dic = new Dictionary <string, object>(); try { var versionNumber = Request.Headers.Get("VersionCode"); var version = Request.Headers.Get("version"); var pager = new PagerModel { CurrentPage = pageIndex, PageSize = pageSize }; List <DiscoveryModel> articles = null; using (var reclient = CacheHelper.CreateCacheClient("SelectArticleForAppHomePage")) { var result = await reclient.GetOrSetAsync("AppHomePage/" + pageIndex + "/" + pageSize, () => DiscoverBLL.SelectArticleForAppHomePage(pager), TimeSpan.FromHours(2)); if (result.Value != null) { articles = result.Value; } else { articles = await DiscoverBLL.SelectArticleForAppHomePage(pager); } } pager.TotalItem = 100; dic.Add("Code", "1"); dic.Add("TotalPage", pager.TotalPage); dic.Add("TotalCount", pager.TotalItem); var articleShowMode = await DistributedCacheHelper.SelectArticleShowMode(); dic.Add("Articles", articles.Select(article => new { ArticleId = article.PKID, Image = JsonConvert.DeserializeObject <List <ShowImageModel> >(article.ShowImages).FirstOrDefault().BImage, Title = article.SmallTitle, ArticleShowMode = articleShowMode, //ContentUrl = ((string.IsNullOrEmpty(versionNumber) == false && (string.Compare(versionNumber, "50") < 0) || // (string.IsNullOrEmpty(version) == false && string.Compare(version, "iOS 3.4.5") < 0))) ? article.ContentUrl : DiscoverySite + "/Article/Detail?Id=" + article.RelatedArticleId, //URL = ((string.IsNullOrEmpty(versionNumber) == false && (string.Compare(versionNumber, "50") < 0) || // (string.IsNullOrEmpty(version) == false && string.Compare(version, "iOS 3.4.5") < 0))) ? article.ContentUrl : DiscoverySite + "/Article/Detail?Id=" + article.RelatedArticleId ContentUrl = (articleShowMode == "New" || article.Type == 5) ? DomainConfig.FaXian + " /react/findDetail/?bgColor=%23ffffff&textColor=%23333333&id=" + article.PKID : article.ContentUrl, URL = (articleShowMode == "New" || article.Type == 5) ? DomainConfig.FaXian + "/react/findDetail/?bgColor=%23ffffff&textColor=%23333333&id=" + article.PKID : article.ContentUrl })); } catch (Exception ex) { WebLog.LogException("App首页瀑布流文章", ex); dic.Clear(); dic.Add("Code", "0"); } return(Json(dic, JsonRequestBehavior.AllowGet)); }
private MongoDBCacheEntity GetMongoDBEntity(CacheKeyMapDescriptor cacheKeyMap) { try { MongoCollection <MongoDBCacheEntity> collection = DistributedCacheHelper.GetMongoDBCollection(cacheKeyMap.CacheId, cacheKeyMap.Cachelimit); var query2 = Query.And( Query.EQ("_id", cacheKeyMap.CacheId) //Query.GT("Expires", DateTime.Now), // Query.EQ("CacheSta", "1") //Query.EQ("ApplicationName", pApplicationName) ); return(collection.FindOne(query2)); } catch (Exception ex) { OnOperating("GetMongoDBEntity异常,excption:" + JsonConvert.SerializeObject(ex)); return(null); } }
public override CacheKeyMapDescriptor GetCacheKeyMap(string key) { try { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); var query = Query.And(Query.EQ("CacheKey", key)); CacheKeyMapDescriptor cacheKeyMap = collection.FindOne(query); if (cacheKeyMap == null) { return(cacheKeyMap); } return(cacheKeyMap); } catch (Exception ex) { return(null); } }
public override bool DeleteCacheKeyMap(CacheExpire cacheExpire) { try { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); switch (cacheExpire) { case CacheExpire.All: collection.FindAll().ToList().ForEach(x => { DeleteCacheKeyMap(x); }); break; case CacheExpire.Expired: var query = Query.And(Query.LTE("ExpireDate", DateTime.Now)); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); break; case CacheExpire.NoExpired: { var query2 = Query.And(Query.GT("ExpireDate", DateTime.Now)); collection.Find(query2).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } break; default: break; } return(true); } catch (Exception ex) { return(false); } }
/// <summary> /// 删除value /// </summary> /// <param name="key"></param> /// <returns></returns> public override bool DeleteValue(string key, bool isClearOtherExpire) { try { CacheKeyMapDescriptor cacheKeyMap = EnsureKeyExist(key, true); if (cacheKeyMap == null) { return(false); } OnOperating("开始删除值:starting:key:" + key + ",cacheId:" + cacheKeyMap.CacheId); MongoCollection <MongoDBCacheEntity> collection = DistributedCacheHelper.GetMongoDBCollection(cacheKeyMap.CacheId, cacheKeyMap.Cachelimit); var query2 = Query.And( Query.EQ("_id", cacheKeyMap.CacheId) ); WriteConcernResult res = collection.Remove(query2);//移除文档 //清空过期的集合数据 if (res.Ok) { bool r = CacheKeyMapManger.Instance.DeleteCacheKeyMap(key); if (isClearOtherExpire) { DistributedCacheHelper.ClearExpireData(cacheKeyMap); } if (r) { OnOperating("删除值完成:end:key:" + key + ",cacheId:" + cacheKeyMap.CacheId + ",result:" + res.Ok + "," + res.ErrorMessage); return(true); } OnOperating("删除值失败:end:key:" + key + ",cacheId:" + cacheKeyMap.CacheId + ",result:" + res.Ok + "," + res.ErrorMessage); return(false); } OnOperating("删除值完成:end:key:" + key + ",cacheId:" + cacheKeyMap.CacheId + ",result:" + res.Ok + "," + res.ErrorMessage); return(false); } catch (Exception ex) { OnOperating("删除值异常:key:" + key + ",exception:" + JsonConvert.SerializeObject(ex)); return(false); } }
public override List <CacheKeyMapDescriptor> GetCacheKeyMapList(CacheExpire cacheExpire) { List <CacheKeyMapDescriptor> lstMap = new List <CacheKeyMapDescriptor>(); try { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); switch (cacheExpire) { case CacheExpire.All: lstMap = collection.FindAll().ToList(); break; case CacheExpire.Expired: { var query = Query.And( Query.LTE("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } break; case CacheExpire.NoExpired: { var query = Query.And( Query.GT("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } break; default: break; } return(lstMap); } catch (Exception ex) { return(lstMap); } }
/// <summary> /// 查询问答板块中的热门问答 /// </summary> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="dic"></param> /// <returns></returns> private async Task GetPopularQAndAForQuestionBrand(int pageIndex, int pageSize, Dictionary <string, object> dic) { var popularQuestion = await DistributedCacheHelper.SelectPopularAnswers(new PagerModel { CurrentPage = pageIndex, PageSize = pageSize }); dic.Add("Code", "1"); var timeLineList = new List <object>(); if (popularQuestion?.Item2 != null) { foreach (var question in popularQuestion.Item2) { //if (question.UserIdentity > 0) // continue; Tuhu.Service.Member.Models.UserObjectModel userInfo = null; if (!(question.UserIdentity > 0)) { userInfo = HttpClientHelper.SelectUserInfoByUserId(question.BestAnswererUserId); } timeLineList.Add(new { PKID = question.PKID, FirstAttentionUserId = question.BestAnswererUserId, UserId = question.BestAnswererUserId, Content = question.Content, AnswerId = question.BestAnswerId, AnswerContent = question.BestAnswerContent, CommentImage = question.CommentImage, UserHead = userInfo?.HeadImage == null ? (question.UserIdentity > 0 ? question.BestAnswererHead : GetDefaultUserHeadByUserGrade(string.Empty)) : (userInfo.HeadImage.Contains("http") ? userInfo.HeadImage : DomainConfig.ImageSite + userInfo.HeadImage), UserName = userInfo == null ? (question.UserIdentity > 0 ? question.BestAnswerer : "途虎用户") : (ArticleController.GetUserName(userInfo.Nickname)), Type = question.BestAnswerId > 0 ? 3 : 4, UserIdentity = question.UserIdentity, Praise = question.Praise }); } } dic.Add("Data", new { TimeLineList = timeLineList }); }
public override bool DeleteCacheKeyMap(CacheKeyMapDescriptor request) { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); if (collection != null) { try { var query = Query.And(Query.EQ("CacheKey", request.CacheKey)); WriteConcernResult res = collection.Remove(query); if (res.Ok) { return(true); } return(false); } catch (Exception ex) { return(false); } } return(false); }
public async Task <ActionResult> SelectArticleInfo(string articleId, string userId, int?selectType) { var dic = new Dictionary <string, object>(); try { var articles = await DiscoverBLL.SelectArticleInfo(articleId, userId); var versionNumber = Request.Headers.Get("VersionCode"); var version = Request.Headers.Get("version"); var articleShowMode = await DistributedCacheHelper.SelectArticleShowMode(); //默认返回单条信息 if (selectType.HasValue == false) { var articleInfo = articles.FirstOrDefault(); dic.Add("Article", new { PKID = articleInfo.PKID, ArticleShowMode = articleShowMode, //URL = //((string.IsNullOrEmpty(versionNumber) == false && (string.Compare(versionNumber, "50") < 0) || //(string.IsNullOrEmpty(version) == false && string.Compare(version, "iOS 3.4.5") < 0))) ? articleInfo.ContentUrl : DiscoverySite + "/Article/Detail?Id=" + articleInfo.RelatedArticleId, URL = (articleShowMode == "New" || articleInfo.Type == 5) ? DomainConfig.FaXian + "/react/findDetail/?bgColor=%23ffffff&textColor=%23333333&id=" + articleId : articleInfo.ContentUrl, Title = articleInfo.BigTitle, CommentCount = articleInfo.CommentCount, VoteCount = articleInfo.VoteCount, Brief = articleInfo.Brief, SmallTitle = articleInfo.SmallTitle, SmallImage = articleInfo.SmallImage, VoteState = articleInfo.VoteState, PublishDateTime = articleInfo.PublishDateTime.ToShortDateString(), ClickCount = articleInfo.ClickCount, Source = articleInfo.Source }); } else { dic.Add("Article", articles.Select(articleInfo => new { PKID = articleInfo.PKID, URL = articleInfo.ContentUrl, Title = articleInfo.BigTitle, CommentCount = articleInfo.CommentCount, VoteCount = articleInfo.VoteCount, Brief = articleInfo.Brief, SmallTitle = articleInfo.SmallTitle, SmallImage = articleInfo.SmallImage, VoteState = articleInfo.VoteState, PublishDateTime = articleInfo.PublishDateTime.ToShortDateString(), ClickCount = articleInfo.ClickCount, Source = articleInfo.Source })); } dic.Add("Code", "1"); } catch (Exception ex) { WebLog.LogException("查询文章的相关信息(点赞数、评论数)", ex); dic.Clear(); dic.Add("Code", "0"); } return(Json(dic, JsonRequestBehavior.AllowGet)); }
public override List <CacheKeyMapDescriptor> GetCacheKeyMapList(CacheExpire cacheExpire, DateType dateType, DateTime startDate, DateTime endDate) { List <CacheKeyMapDescriptor> lstMap = new List <CacheKeyMapDescriptor>(); try { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); switch (cacheExpire) { case CacheExpire.All: { if (dateType == DateType.CreateTime) { var query = Query.And( Query.GTE("CreateTime", startDate), Query.LTE("CreateTime", endDate) ); lstMap = collection.Find(query).ToList(); } else if (dateType == DateType.ExpireTime) { var query = Query.And( Query.GTE("ExpireDate", startDate), Query.LTE("ExpireDate", endDate) ); lstMap = collection.Find(query).ToList(); } else { lstMap = collection.FindAll().ToList(); } } break; case CacheExpire.Expired: { if (dateType == DateType.CreateTime) { var query = Query.And( Query.GTE("CreateTime", startDate), Query.LTE("CreateTime", endDate), Query.LTE("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } else if (dateType == DateType.ExpireTime) { var query = Query.And( Query.GTE("ExpireDate", startDate), Query.LTE("ExpireDate", endDate), Query.LTE("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } else { var query = Query.And( Query.LTE("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } } break; case CacheExpire.NoExpired: { if (dateType == DateType.CreateTime) { var query = Query.And( Query.GTE("CreateTime", startDate), Query.LTE("CreateTime", endDate), Query.GT("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } else if (dateType == DateType.ExpireTime) { var query = Query.And( Query.GTE("ExpireDate", startDate), Query.LTE("ExpireDate", endDate), Query.GT("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } else { var query = Query.And( Query.GT("ExpireDate", DateTime.Now) ); lstMap = collection.Find(query).ToList(); } } break; default: break; } return(lstMap); } catch (Exception ex) { return(lstMap); } }
public override bool DeleteCacheKeyMap(CacheExpire cacheExpire, DateType dateType, DateTime startDate, DateTime endDate) { try { MongoCollection <CacheKeyMapDescriptor> collection = DistributedCacheHelper.GetMongoDBCacheKeyMapCollection(); startDate = Convert.ToDateTime(startDate.ToString("yyyy-MM-dd") + " 0:00:00"); endDate = Convert.ToDateTime(endDate.ToString("yyyy-MM-dd") + " 23:59:59"); switch (cacheExpire) { case CacheExpire.All: { if (dateType == DateType.CreateTime) { var query = Query.And( Query.GTE("CreateTime", startDate), Query.LTE("CreateTime", endDate) ); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } else { var query = Query.And( Query.GTE("ExpireDate", startDate), Query.LTE("ExpireDate", endDate) ); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } } break; case CacheExpire.Expired: { if (dateType == DateType.CreateTime) { var query = Query.And( Query.GTE("CreateTime", startDate), Query.LTE("CreateTime", endDate), Query.LTE("ExpireDate", DateTime.Now) ); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } else { var query = Query.And( Query.GTE("ExpireDate", startDate), Query.LTE("CreateTime", endDate), Query.LTE("ExpireDate", DateTime.Now) ); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } } break; case CacheExpire.NoExpired: { if (dateType == DateType.CreateTime) { var query = Query.And( Query.GTE("CreateTime", startDate), Query.LTE("CreateTime", endDate), Query.GT("ExpireDate", DateTime.Now) ); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } else { var query = Query.And( Query.GTE("ExpireDate", startDate), Query.LTE("CreateTime", endDate), Query.GT("ExpireDate", DateTime.Now) ); collection.Find(query).ToList().ForEach(x => { DeleteCacheKeyMap(x); }); } } break; default: break; } return(true); } catch (Exception ex) { return(false); } }