.net redis数据缓存(二) redis操作List集合带分页

来源:互联网 发布:javascript的数据类型 编辑:程序博客网 时间:2024/06/05 11:33

 上一篇,《.net redis数据缓存(一) redis在Windows环境中的安装是一个简单的入门教程,我相信,看多第一篇的.net猿们对redis入门已经很熟练了,这一篇《net redis数据缓存(二) redis操作List集合带分页》将是一个进阶篇。这一篇我继续用MVC5作为讲解,集合的操作用EF,分页控件我会用PagedList.Mvc这个库类。

1、编写一个简单的redishelper类库,封装ServiceStack.Redis

 

public class RedisHelper    {        #region 基本用户名密码,使用配置文件        /// <summary>        /// 写入redis服务器的ip+port        /// </summary>        public static string WriteServerList = ConfigurationManager.AppSettings["WriteServerList"];        /// <summary>        /// 读取服务器的ip +port        /// </summary>        public static string ReadServerList = ConfigurationManager.AppSettings["ReadServerList"];        /// <summary>        /// 服务器的密码        /// </summary>        public static string Password = ConfigurationManager.AppSettings["Password"];        #endregion        #region Resid基础连接设置              /// <summary>        /// redis程序池        /// </summary>        private static PooledRedisClientManager _redisprcm;        /// <summary>        /// 连接        /// </summary>        private static void CreateManager()        {            try            {                string[] writeServerList = redisSplitString(WriteServerList, ",");                string[] readServerList = redisSplitString(ReadServerList, ",");                _redisprcm = new PooledRedisClientManager(readServerList, writeServerList,                                       new RedisClientManagerConfig                                       {                                           MaxWritePoolSize = 60,                                           MaxReadPoolSize = 5,                                           AutoStart = true,                                       });                //如果服务端有密码则设置                string pwd = Password;                if (!string.IsNullOrEmpty(pwd))                {                    _redisprcm.GetClient().Password = pwd;                }            }            catch (Exception ex)            {                _redisprcm = null;            }        }        private static string[] redisSplitString(string strSource, string split)        {            return strSource.Split(split.ToArray());        }        /// <summary>        /// 设置redis操作对象        /// </summary>        /// <returns></returns>        public static IRedisClient GetClient()        {            if (_redisprcm == null)                CreateManager();            return _redisprcm.GetClient();        }        /// <summary>        /// 默认缓存10分钟        /// </summary>        public static TimeSpan expiresIn = TimeSpan.FromMinutes(10);        #endregion        #region Object T类型        /// <summary>        /// 写入        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="key"></param>        /// <param name="value"></param>        /// <param name="redisClient"></param>        /// <param name="expirIn"></param>        /// <returns></returns>        public static bool Set<T>(string key, T value, IRedisClient redisClient, TimeSpan? expirIn = null)        {            bool flag = false;            try            {                if (string.IsNullOrEmpty(expirIn.ToString()))                {                    expirIn = expiresIn;                }                redisClient.Set<T>(key, value, expirIn);                flag = true;            }            catch (Exception)            {                flag = false;            }            return flag;        }        /// <summary>        /// 读取        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="key"></param>        /// <param name="redisClient"></param>        /// <returns></returns>        public static T Get<T>(string key, IRedisClient redisClient)        {            T Y = default(T);            try            {                Y = redisClient.Get<T>(key);            }            catch (Exception EX)            {                Y = default(T);            }            return Y;        }        #endregion        #region string 字符串类型操作        /// <summary>        /// 设置string        /// </summary>        /// <param name="key"></param>        /// <param name="value"></param>        /// <param name="expiry"></param>        /// <returns></returns>        public static bool StringSet(string key, string value, IRedisClient redisClient, TimeSpan? expiry = default(TimeSpan?))        {            bool flag = true;            try            {                redisClient.Set(key, value, expiry);                flag = true;            }            catch (Exception ex)            {                flag = false;            }            return flag;        }        /// <summary>        /// 读取string类型        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        public static string getValueString(string key, IRedisClient redisClient)        {            string value = redisClient.GetValue(key);            return value;        }        #endregion        #region 删除缓存        /// <summary>        /// 删除key        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        public static bool Remove(string key, IRedisClient redisClient)        {            return redisClient.Remove(key);        }        #endregion        #region 释放内存        /// <summary>        /// 释放资源        /// </summary>        public static void Dispose(IRedisClient redisClient)        {            if (redisClient != null)            {                redisClient.Dispose();                redisClient = null;            }            //强制垃圾回收            GC.Collect();        }        #endregion    }
2、数据展示与分页

     2.1 后台代码

       

 public class HomeController : Controller    {        // GET: Home        public ActionResult Index(int page = 1)        {            PageMassage pagMsg = new PageMassage();            pagMsg.thisPage = page;            pagMsg.thisRow = 15;            if (pagMsg.thisPage <= 0)            {                pagMsg.thisPage = 1;            }            ViewBag.thisPage = pagMsg.thisPage;            //设置string            List<UserInfoModel> user;            using (var cliend = RedisHelper.GetClient())            {                //获取数据                user = new List<UserInfoModel>();                user = RedisHelper.Get<List<UserInfoModel>>("UserName", cliend);                if (user == null)                {                    user = new List<UserInfoModel>();                    //测试1000条数据                    for (int i = 0; i < 1000; i++)                    {                        UserInfoModel uu = new UserInfoModel();                        uu.Id = i + 1;                        uu.Nmae = "李" + i.ToString() + "号";                        uu.Age = 45 + i;                        uu.Sex = new Random().Next(0, 1) == 0 ? "女" : "男";                        uu.Bir = DateTime.Now;                        uu.Adddate = DateTime.Now;                        user.Add(uu);                    }                    //添加緩存                    bool flag = RedisHelper.Set<List<UserInfoModel>>("UserName", user, cliend);                                   }            }            if (pagMsg.thisSeachKey != null)            {                user = user.OrderBy(q => q.Id).Where(q => q.Nmae.Contains(pagMsg.thisSeachKey)).ToList();            }            else            {                user = user.OrderBy(q => q.Id).ToList();            }            ViewBag.User = user.ToPagedList(pagMsg.thisPage, pagMsg.thisRow);            //ViewBag.User = user;            return View();        }    }    public class PageMassage    {        /// <summary>        /// 當前頁        /// </summary>        public int thisPage { get; set; }        /// <summary>        /// 每頁顯示        /// </summary>        public int thisRow { get; set; }        /// <summary>        /// 搜索内容        /// </summary>        public string thisSeachKey { get; set; }    }
    2.2 前台展示

   

@using PagedList.Mvc;@{    ViewBag.Title = "Index";    //PagedList.IPagedList<RedisMVC.Model.UserName> userModel =PagedList.PagedList<ViewBag.User>;    PagedList.IPagedList<Redis数据缓存_二_List集合的使用与分页展示.Models.UserInfoModel> userModel =        (PagedList.IPagedList<Redis数据缓存_二_List集合的使用与分页展示.Models.UserInfoModel>)ViewBag.User;}<h2>数据展示</h2><table>         @{        foreach (var item in userModel)        {            <tr>                <td>                     @item.Nmae                  </td>                <td>                    @item.Age                </td>                <td>                    @item.Bir                </td>                <td>                    @item.Adddate                </td>            </tr>        }    }</table>     <div>        <span style="font-size:20px;color:blue;">            每页 @userModel.PageSize 条记录,共 @userModel.PageCount 页,当前第 @userModel.PageNumber 页         </span>         @Html.PagedListPager(userModel, page => Url.Action("Index", new { page }))     </div>
3.配置文件

 <!--redis写入-->
    <add key="WriteServerList" value="192.168.1.188:6379" />
    <!--redis读取-->
    <add key="ReadServerList" value="192.168.1.188:6379" />
    <!--密码-->
    <add key="Password" value="" />

4.在服务器部署redis

   因为我电脑安装了一个Windows server 2016的虚拟机,所有我就部署在我的虚拟机里面了



特别注意的是,部署到服务器中必须要更改配置文件



打开配置文件,找到bing


这样,在本地用客户端也是可以连接的到的


运行我们的项目,可以在网页和redis管理平台看到如下界面

 网页中的效果




redis中的效果


这样,就缓存了所有的redis,且实现分页。