星空网 > 软件开发 > ASP.net

缓存技术Redis在C#中的使用及Redis的封装

Redis是一款开源的、高性能的键-值存储(key-value store)。它常被称作是一款数据结构服务器(data structure server)。Redis的键值可以包括字符串(strings)、哈希(hashes)、列表(lists)、集合(sets)和 有序集合(sorted sets)等数据类型。 对于这些数据类型,你可以执行原子操作。例如:对字符串进行附加操作(append);递增哈希中的值;向列表中增加元素;计算集合的交集、并集与差集 等。

    为了获得优异的性能,Redis采用了内存中(in-memory)数据集(dataset)的方式。根据使用场景的不同,你可以每隔一段时间将数据集转存到磁盘上来持久化数据,或者在日志尾部追加每一条操作命令。

    Redis同样支持主从复制(master-slave replication),并且具有非常快速的非阻塞首次同步(non-blocking first synchronization)、网络断开自动重连等功能。同时Redis还具有其它一些特性,其中包括简单的check-and-set机制、pub/sub和配置设置等,以便使得Redis能够表现得更像缓存(cache)。

    Redis还提供了丰富的客户端,以便支持现阶段流行的大多数编程语言。详细的支持列表可以参看Redis官方文档:http://redis.io/clients。Redis自身使用ANSI C来编写,并且能够在不产生外部依赖(external dependencies)的情况下运行在大多数POSIX系统上,例如:Linux、*BSD、OS X和Solaris等。

Redis 由四个可执行文件:redis-benchmark、redis-cli、redis-server、redis-stat 这四个文件,加上一个redis.conf就构成了整个redis的最终可用包。它们的作用如下:

    redis-server:Redis服务器的daemon启动程序
    redis-cli:Redis命令行操作工具。当然,你也可以用telnet根据其纯文本协议来操作
    redis-benchmark:Redis性能测试工具,测试Redis在你的系统及你的配置下的读写性能
    redis-stat:Redis状态检测工具,可以检测Redis当前状态参数及延迟状况

现在就可以启动redis了,redis只有一个启动参数,就是他的配置文件路径。


首选,你先得开启redis-server,否则无法连接服务:

缓存技术Redis在C#中的使用及Redis的封装


打开redis-server:

缓存技术Redis在C#中的使用及Redis的封装



接下来你就可以调用Redis的属性来进行数据的存储及获取:

缓存技术Redis在C#中的使用及Redis的封装



关键性代码:

 

[csharp] view plain copy print?

  1. <span style="color:#000000;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using ServiceStack.Redis;  
  6. using ServiceStack.Redis.Support;  
  7.   
  8. namespace RedisStudy  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {  
  14.             try  
  15.             {  
  16.                 //获取Redis操作接口  
  17.                 IRedisClient Redis = RedisManager.GetClient();  
  18.                 //Hash表操作  
  19.                 HashOperator operators = new HashOperator();  
  20.   
  21.                 //移除某个缓存数据  
  22.                 bool isTrue = Redis.Remove("additemtolist");  
  23.   
  24.                 //将字符串列表添加到redis  
  25.                 List<string> storeMembers = new List<string>() { "韩梅梅", "李雷", "露西" };  
  26.                 storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x));  
  27.                 //得到指定的key所对应的value集合  
  28.                 Console.WriteLine("得到指定的key所对应的value集合:");  
  29.                 var members = Redis.GetAllItemsFromList("additemtolist");  
  30.                 members.ForEach(s => Console.WriteLine("additemtolist :" + s));  
  31.                 Console.WriteLine("");  
  32.   
  33.                 // 获取指定索引位置数据  
  34.                 Console.WriteLine("获取指定索引位置数据:");  
  35.                 var item = Redis.GetItemFromList("additemtolist", 2);  
  36.                 Console.WriteLine(item);  
  37.   
  38.                 Console.WriteLine("");  
  39.   
  40.                 //将数据存入Hash表中  
  41.                 Console.WriteLine("Hash表数据存储:");  
  42.                 UserInfo userInfos = new UserInfo() { UserName = "李雷", Age = 45 };  
  43.                 var ser = new ObjectSerializer();    //位于namespace ServiceStack.Redis.Support;  
  44.                 bool results = operators.Set<byte[]>("userInfosHash", "userInfos", ser.Serialize(userInfos));  
  45.                 byte[] infos = operators.Get<byte[]>("userInfosHash", "userInfos");  
  46.                 userInfos = ser.Deserialize(infos) as UserInfo;  
  47.                 Console.WriteLine("name=" + userInfos.UserName + "   age=" + userInfos.Age);  
  48.   
  49.                 Console.WriteLine("");  
  50.   
  51.                 //object序列化方式存储  
  52.                 Console.WriteLine("object序列化方式存储:");  
  53.                 UserInfo uInfo = new UserInfo() { UserName = "张三", Age = 12 };  
  54.                 bool result = Redis.Set<byte[]>("uInfo", ser.Serialize(uInfo));  
  55.                 UserInfo userinfo2 = ser.Deserialize(Redis.Get<byte[]>("uInfo")) as UserInfo;  
  56.                 Console.WriteLine("name=" + userinfo2.UserName + "   age=" + userinfo2.Age);  
  57.   
  58.                 Console.WriteLine("");  
  59.   
  60.                 //存储值类型数据  
  61.                 Console.WriteLine("存储值类型数据:");  
  62.                 Redis.Set<int>("my_age", 12);//或Redis.Set("my_age", 12);  
  63.                 int age = Redis.Get<int>("my_age");  
  64.                 Console.WriteLine("age=" + age);  
  65.   
  66.                 Console.WriteLine("");  
  67.   
  68.                 //序列化列表数据  
  69.                 Console.WriteLine("列表数据:");  
  70.                 List<UserInfo> userinfoList = new List<UserInfo> {  
  71.                 new UserInfo{UserName="露西",Age=1,Id=1},  
  72.                 new UserInfo{UserName="玛丽",Age=3,Id=2},  
  73.             };  
  74.                 Redis.Set<byte[]>("userinfolist_serialize", ser.Serialize(userinfoList));  
  75.                 List<UserInfo> userList = ser.Deserialize(Redis.Get<byte[]>("userinfolist_serialize")) as List<UserInfo>;  
  76.                 userList.ForEach(i =>  
  77.                 {  
  78.                     Console.WriteLine("name=" + i.UserName + "   age=" + i.Age);  
  79.                 });  
  80.                 //释放内存  
  81.                 Redis.Dispose();  
  82.                 operators.Dispose();  
  83.                 Console.ReadKey();  
  84.             }  
  85.             catch (Exception ex)  
  86.             {  
  87.                 Console.WriteLine(ex.Message.ToString());  
  88.                 Console.WriteLine("Please open the redis-server.exe ");  
  89.                 Console.ReadKey();  
  90.             }  
  91.         }  
  92.     }  
  93. }</span>  


RedisManager类:

 

[csharp] view plain copy print?

  1. <span style="color:#000000;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using ServiceStack.Redis;  
  6.   
  7. namespace RedisStudy  
  8. {  
  9.     /// <summary>  
  10.     /// RedisManager类主要是创建链接池管理对象的  
  11.     /// </summary>  
  12.     public class RedisManager  
  13.     {  
  14.         /// <summary>  
  15.         /// redis配置文件信息  
  16.         /// </summary>  
  17.         private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"];  
  18.         private static PooledRedisClientManager _prcm;  
  19.   
  20.         /// <summary>  
  21.         /// 静态构造方法,初始化链接池管理对象  
  22.         /// </summary>  
  23.         static RedisManager()  
  24.         {  
  25.             CreateManager();  
  26.         }  
  27.   
  28.         /// <summary>  
  29.         /// 创建链接池管理对象  
  30.         /// </summary>  
  31.         private static void CreateManager()  
  32.         {  
  33.             _prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath });  
  34.         }  
  35.   
  36.           
  37.         private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)  
  38.         {  
  39.             //WriteServerList:可写的Redis链接地址。  
  40.             //ReadServerList:可读的Redis链接地址。  
  41.             //MaxWritePoolSize:最大写链接数。  
  42.             //MaxReadPoolSize:最大读链接数。  
  43.             //AutoStart:自动重启。  
  44.             //LocalCacheTime:本地缓存到期时间,单位:秒。  
  45.             //RecordeLog:是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项。  
  46.             //RedisConfigInfo类是记录redis连接信息,此信息和配置文件中的RedisConfig相呼应  
  47.   
  48.             // 支持读写分离,均衡负载   
  49.             return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig  
  50.             {  
  51.                 MaxWritePoolSize = 5, // “写”链接池链接数   
  52.                 MaxReadPoolSize = 5, // “读”链接池链接数   
  53.                 AutoStart = true,  
  54.             });  
  55.         }  
  56.   
  57.         private static IEnumerable<string> SplitString(string strSource, string split)  
  58.         {  
  59.             return strSource.Split(split.ToArray());  
  60.         }  
  61.   
  62.         /// <summary>  
  63.         /// 客户端缓存操作对象  
  64.         /// </summary>  
  65.         public static IRedisClient GetClient()  
  66.         {  
  67.             if (_prcm == null)  
  68.             {  
  69.                 CreateManager();  
  70.             }  
  71.             return _prcm.GetClient();  
  72.         }  
  73.   
  74.     }  
  75. }</span>  


RedisOperatorBase类:

 

[csharp] view plain copy print?

  1. <span style="color:#000000;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using ServiceStack.Redis;  
  6.   
  7. namespace RedisStudy  
  8. {  
  9.     /// <summary>  
  10.     /// RedisOperatorBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存  
  11.     /// </summary>  
  12.     public abstract class RedisOperatorBase : IDisposable  
  13.     {  
  14.         protected IRedisClient Redis { get; private set; }  
  15.         private bool _disposed = false;  
  16.         protected RedisOperatorBase()  
  17.         {  
  18.             Redis = RedisManager.GetClient();  
  19.         }  
  20.         protected virtual void Dispose(bool disposing)  
  21.         {  
  22.             if (!this._disposed)  
  23.             {  
  24.                 if (disposing)  
  25.                 {  
  26.                     Redis.Dispose();  
  27.                     Redis = null;  
  28.                 }  
  29.             }  
  30.             this._disposed = true;  
  31.         }  
  32.         public void Dispose()  
  33.         {  
  34.             Dispose(true);  
  35.             GC.SuppressFinalize(this);  
  36.         }  
  37.         /// <summary>  
  38.         /// 保存数据DB文件到硬盘  
  39.         /// </summary>  
  40.         public void Save()  
  41.         {  
  42.             Redis.Save();  
  43.         }  
  44.         /// <summary>  
  45.         /// 异步保存数据DB文件到硬盘  
  46.         /// </summary>  
  47.         public void SaveAsync()  
  48.         {  
  49.             Redis.SaveAsync();  
  50.         }  
  51.     }  
  52. }</span>  


HashOperator类:

 

[csharp] view plain copy print?

  1. <span style="color:#000000;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using ServiceStack.Text;  
  6.   
  7. namespace RedisStudy  
  8. {  
  9.     /// <summary>  
  10.     /// HashOperator类,是操作哈希表类。继承自RedisOperatorBase类  
  11.     /// </summary>  
  12.     public class HashOperator : RedisOperatorBase  
  13.     {  
  14.         public HashOperator() : base() { }  
  15.         /// <summary>  
  16.         /// 判断某个数据是否已经被缓存  
  17.         /// </summary>  
  18.         public bool Exist<T>(string hashId, string key)  
  19.         {  
  20.             return Redis.HashContainsEntry(hashId, key);  
  21.         }  
  22.         /// <summary>  
  23.         /// 存储数据到hash表  
  24.         /// </summary>  
  25.         public bool Set<T>(string hashId, string key, T t)  
  26.         {  
  27.             var value = JsonSerializer.SerializeToString<T>(t);  
  28.             return Redis.SetEntryInHash(hashId, key, value);  
  29.         }  
  30.         /// <summary>  
  31.         /// 移除hash中的某值  
  32.         /// </summary>  
  33.         public bool Remove(string hashId, string key)  
  34.         {  
  35.             return Redis.RemoveEntryFromHash(hashId, key);  
  36.         }  
  37.         /// <summary>  
  38.         /// 移除整个hash  
  39.         /// </summary>  
  40.         public bool Remove(string key)  
  41.         {  
  42.             return Redis.Remove(key);  
  43.         }  
  44.         /// <summary>  
  45.         /// 从hash表获取数据  
  46.         /// </summary>  
  47.         public T Get<T>(string hashId, string key)  
  48.         {  
  49.             string value = Redis.GetValueFromHash(hashId, key);  
  50.             return JsonSerializer.DeserializeFromString<T>(value);  
  51.         }  
  52.         /// <summary>  
  53.         /// 获取整个hash的数据  
  54.         /// </summary>  
  55.         public List<T> GetAll<T>(string hashId)  
  56.         {  
  57.             var result = new List<T>();  
  58.             var list = Redis.GetHashValues(hashId);  
  59.             if (list != null && list.Count > 0)  
  60.             {  
  61.                 list.ForEach(x =>  
  62.                 {  
  63.                     var value = JsonSerializer.DeserializeFromString<T>(x);  
  64.                     result.Add(value);  
  65.                 });  
  66.             }  
  67.             return result;  
  68.         }  
  69.         /// <summary>  
  70.         /// 设置缓存过期  
  71.         /// </summary>  
  72.         public void SetExpire(string key, DateTime datetime)  
  73.         {  
  74.             Redis.ExpireEntryAt(key, datetime);  
  75.         }  
  76.     }  
  77. }</span>  


UserInfo类:

 

[csharp] view plain copy print?

  1. <span style="color:#000000;">using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace RedisStudy  
  7. {  
  8.     [Serializable]  
  9.     public class UserInfo  
  10.     {  
  11.         public int Id;  
  12.         public string UserName;  
  13.         public int Age;  
  14.     }  
  15. }</span>  


app.config配置:

[csharp] view plain copy print?

  1. <?"1.0"?>  
  2. <configuration>  
  3. <startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup>  
  4.   <appSettings>  
  5.     <add key="RedisPath" value="127.0.0.1:6379"/>  
  6.   </appSettings>  
  7. </configuration>  






以上是Redis操作的封装类,直接拿来调用即可。




原标题:缓存技术Redis在C#中的使用及Redis的封装

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

非洲国际海运:https://www.goluckyvip.com/tag/97407.html
宁波到法国海运:https://www.goluckyvip.com/tag/97408.html
菲律宾海运多少钱一立方:https://www.goluckyvip.com/tag/97409.html
Shopify跟卖:https://www.goluckyvip.com/tag/9741.html
海运到菲律宾多少钱一方:https://www.goluckyvip.com/tag/97410.html
海运菲律宾费用:https://www.goluckyvip.com/tag/97411.html
深圳有没有比较好玩的景点 深圳有没有比较好玩的景点推荐一下:https://www.vstour.cn/a/366175.html
长治婚庆女司仪和主持人:https://www.vstour.cn/a/366176.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流