项目中我们经常遇到一些经常访问的接口,并且更新及时度不是特别高,那么我们可以利用文件来做一些数据请求的缓存。
这里以微信公众号获取粉丝用户列表为例,我们把微信公众号查到的用户先缓存在文件中,这样在翻页时就不需要再重新请求接口。
获取微信粉丝用户
/// <summary> /// 用户列表 /// </summary> /// <returns></returns> public ActionResult UserList() { //页面加载时,将微信拉去用户进行缓存 List<wx_user_info> Users = new List<wx_user_info>(); var OpenList = new WeChat().GetOpenIdList(); if (OpenList.ResponseState) { foreach (var item in OpenList.ResponseData.data.openid) { var backdata = new WeChat().GetUserInfo(item); if (backdata.ResponseState) { Users.Add(backdata.ResponseData); } } var jser = new JavaScriptSerializer(); var json = jser.Serialize(Users.ToArray()); string sRespons = json.ToString(); byte[] byt = System.Text.Encoding.UTF8.GetBytes(sRespons); FileStream fs = new FileStream(Server.MapPath("~/App_Data/Config/weixin.json"), FileMode.OpenOrCreate); fs.Write(byt, 0, byt.Length); fs.Dispose(); fs.Close(); } else { ViewBag.Tip = "系统异常,编号:" + OpenList.ErrorData.errcode + "错误信息:" + OpenList.ErrorData.errmsg; } return View(); }
用户翻页时异步从json文件获取指定条数数据
public ActionResult GetUserList(int? page, int? take) { page = page ?? 1; take = take ?? 5; List<wx_user_info> Users = new List<wx_user_info>(); FileStream fs = new FileStream(Server.MapPath("~/App_Data/Config/weixin.json"), FileMode.Open); byte[] byt = new byte[fs.Length]; fs.Read(byt, 0, byt.Length); Users = JsonConvert.DeserializeObject<List<wx_user_info>>(Encoding.UTF8.GetString(byt)); fs.Dispose(); fs.Close(); ViewBag.Tip = Users.Count() + "人"; ViewBag.TotalPage = Math.Ceiling(((double)Users.Count() / (double)take)); ViewBag.CurrentPage = page; var PageUseras = Users.Where(ua => true); //条件查询 if (!string.IsNullOrWhiteSpace(Request.Form["search_nickname"])) { PageUseras = Users.Where(ua => ua.nickname.Contains(Request.Form["search_nickname"]) || ua.remark.Contains(Request.Form["search_nickname"])); ViewBag.TotalPage = Math.Ceiling(((double)PageUseras.Count() / (double)take)); ViewBag.CurrentPage = page = 1; } //如果本页没有数据直接显示前一页 if (page > 1 && PageUseras.Skip(take.Value * (page.Value - 1)).Take(take.Value).Count() < 1) { ViewBag.CurrentPage = Math.Ceiling(((double)PageUseras.Count() / (double)take)); PageUseras = PageUseras.Skip(take.Value * (page.Value - 2)).Take(take.Value); } else { PageUseras = PageUseras.Skip(take.Value * (page.Value - 1)).Take(take.Value); } return View(PageUseras); }