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

 上一篇,《.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,且实现分页。

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Redis常用的数据结构有字符串(string)、哈希(hash)、列表(list)、集合(set)和有序集合(zset)等,其中常用的缓存搜索结果的数据结构是有序集合(zset)。 有序集合(zset)是一种有序的、不重复的数据集合,其中每个成员都关联着一个权重(score),通过权重来进行排序。在搜索引擎中,可以将搜索结果的相关性作为权重,将搜索结果存储在有序集合中,以便进行排序和分页。 具体实现步骤如下: 1. 将搜索结果的相关性作为权重,将搜索结果存储在一个有序集合中。有序集合的成员为搜索结果的ID,权重为搜索结果的相关性。 2. 在搜索引擎中,首先检查缓存中是否存在相应的搜索结果。如果存在,则直接返回缓存结果;否则,进行ES的查询操作,并将查询结果存储到有序集合中。 3. 在从缓存中获取搜索结果时,可以通过有序集合的分页功能,只返回指定页数的搜索结果。可以使用zrange或zrevrange命令来按照权重范围获取搜索结果,使用zrangebyscore或zrevrangebyscore命令来按照权重分值获取搜索结果。 4. 为了保证缓存的实效性,需要设置合适的缓存过期时间,可以根据业务需求和查询频率来动态调整。 总的来说,使用有序集合作为缓存搜索结果的数据结构,可以方便地进行排序和分页,并且可以通过设置合适的缓存过期时间来保证缓存的实效性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值