码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2019-09-30 14:55:47      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:cti   url   net   exception   inf   mes   service   cli   enum   

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

技术图片
  1 public class RedisHelper
  2     {
  3         #region 基本用户名密码,使用配置文件
  4         /// <summary>
  5         /// 写入redis服务器的ip+port
  6         /// </summary>
  7         public static string WriteServerList = ConfigurationManager.AppSettings["WriteServerList"];
  8         /// <summary>
  9         /// 读取服务器的ip +port
 10         /// </summary>
 11         public static string ReadServerList = ConfigurationManager.AppSettings["ReadServerList"];
 12         /// <summary>
 13         /// 服务器的密码
 14         /// </summary>
 15         public static string Password = ConfigurationManager.AppSettings["Password"];
 16  
 17         #endregion
 18  
 19         #region Resid基础连接设置
 20  
 21       
 22         /// <summary>
 23         /// redis程序池
 24         /// </summary>
 25         private static PooledRedisClientManager _redisprcm;
 26  
 27         /// <summary>
 28         /// 连接
 29         /// </summary>
 30         private static void CreateManager()
 31         {
 32             try
 33             {
 34                 string[] writeServerList = redisSplitString(WriteServerList, ",");
 35                 string[] readServerList = redisSplitString(ReadServerList, ",");
 36  
 37  
 38                 _redisprcm = new PooledRedisClientManager(readServerList, writeServerList,
 39                                        new RedisClientManagerConfig
 40                                        {
 41                                            MaxWritePoolSize = 60,
 42                                            MaxReadPoolSize = 5,
 43                                            AutoStart = true,
 44                                        });
 45                 //如果服务端有密码则设置
 46                 string pwd = Password;
 47                 if (!string.IsNullOrEmpty(pwd))
 48                 {
 49                     _redisprcm.GetClient().Password = pwd;
 50                 }
 51  
 52             }
 53             catch (Exception ex)
 54             {
 55  
 56                 _redisprcm = null;
 57             }
 58  
 59  
 60         }
 61  
 62         private static string[] redisSplitString(string strSource, string split)
 63         {
 64             return strSource.Split(split.ToArray());
 65         }
 66  
 67  
 68         /// <summary>
 69         /// 设置redis操作对象
 70         /// </summary>
 71         /// <returns></returns>
 72         public static IRedisClient GetClient()
 73         {
 74             if (_redisprcm == null)
 75                 CreateManager();
 76  
 77  
 78             return _redisprcm.GetClient();
 79         }
 80         /// <summary>
 81         /// 默认缓存10分钟
 82         /// </summary>
 83         public static TimeSpan expiresIn = TimeSpan.FromMinutes(10);
 84  
 85         #endregion
 86  
 87         #region Object T类型
 88  
 89  
 90         /// <summary>
 91         /// 写入
 92         /// </summary>
 93         /// <typeparam name="T"></typeparam>
 94         /// <param name="key"></param>
 95         /// <param name="value"></param>
 96         /// <param name="redisClient"></param>
 97         /// <param name="expirIn"></param>
 98         /// <returns></returns>
 99         public static bool Set<T>(string key, T value, IRedisClient redisClient, TimeSpan? expirIn = null)
100         {
101             bool flag = false;
102             try
103             {
104                 if (string.IsNullOrEmpty(expirIn.ToString()))
105                 {
106                     expirIn = expiresIn;
107                 }
108                 redisClient.Set<T>(key, value, expirIn);
109                 flag = true;
110             }
111             catch (Exception)
112             {
113                 flag = false;
114  
115             }
116             return flag;
117         }
118  
119         /// <summary>
120         /// 读取
121         /// </summary>
122         /// <typeparam name="T"></typeparam>
123         /// <param name="key"></param>
124         /// <param name="redisClient"></param>
125         /// <returns></returns>
126         public static T Get<T>(string key, IRedisClient redisClient)
127         {
128             T Y = default(T);
129             try
130             {
131                 Y = redisClient.Get<T>(key);
132             }
133             catch (Exception EX)
134             {
135                 Y = default(T);
136  
137             }
138             return Y;
139         }
140  
141         #endregion
142  
143         #region string 字符串类型操作
144         /// <summary>
145         /// 设置string
146         /// </summary>
147         /// <param name="key"></param>
148         /// <param name="value"></param>
149         /// <param name="expiry"></param>
150         /// <returns></returns>
151         public static bool StringSet(string key, string value, IRedisClient redisClient, TimeSpan? expiry = default(TimeSpan?))
152         {
153             bool flag = true;
154             try
155             {
156                 redisClient.Set(key, value, expiry);
157                 flag = true;
158             }
159             catch (Exception ex)
160             {
161                 flag = false;
162             }
163             return flag;
164         }
165  
166         /// <summary>
167         /// 读取string类型
168         /// </summary>
169         /// <param name="key"></param>
170         /// <returns></returns>
171         public static string getValueString(string key, IRedisClient redisClient)
172         {
173             string value = redisClient.GetValue(key);
174             return value;
175         }
176  
177         #endregion
178  
179         #region 删除缓存
180  
181         /// <summary>
182         /// 删除key
183         /// </summary>
184         /// <param name="key"></param>
185         /// <returns></returns>
186         public static bool Remove(string key, IRedisClient redisClient)
187         {
188             return redisClient.Remove(key);
189         }
190         #endregion
191  
192         #region 释放内存
193         /// <summary>
194         /// 释放资源
195         /// </summary>
196         public static void Dispose(IRedisClient redisClient)
197         {
198             if (redisClient != null)
199             {
200                 redisClient.Dispose();
201                 redisClient = null;
202             }
203             //强制垃圾回收
204             GC.Collect();
205  
206         }
207         #endregion
208     }
View Code

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; }
 
    }
View Code

  2.2 前台展示

技术图片
 1 @using PagedList.Mvc;
 2 @{
 3     ViewBag.Title = "Index";
 4     //PagedList.IPagedList<RedisMVC.Model.UserName> userModel =PagedList.PagedList<ViewBag.User>;
 5  
 6     PagedList.IPagedList<Redis数据缓存_二_List集合的使用与分页展示.Models.UserInfoModel> userModel =
 7         (PagedList.IPagedList<Redis数据缓存_二_List集合的使用与分页展示.Models.UserInfoModel>)ViewBag.User;
 8 }
 9 <h2>数据展示</h2>
10 <table>
11   
12    
13  
14     @{
15  
16         foreach (var item in userModel)
17         {
18             <tr>
19                 <td>
20                      @item.Nmae  
21                 </td>
22                 <td>
23                     @item.Age
24                 </td>
25                 <td>
26                     @item.Bir
27                 </td>
28                 <td>
29                     @item.Adddate
30                 </td>
31             </tr>
32         }
33     }
34 </table>
35      <div>
36         <span style="font-size:20px;color:blue;">
37             每页 @userModel.PageSize 条记录,共 @userModel.PageCount 页,当前第 @userModel.PageNumber 页
38          </span>
39          @Html.PagedListPager(userModel, page => Url.Action("Index", new { page }))
40      </div>
41  
42  
View Code

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="" />

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

标签:cti   url   net   exception   inf   mes   service   cli   enum   

原文地址:https://www.cnblogs.com/lzzsf/p/11612493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!