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-server:

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

关键性代码:

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

RedisManager类:

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


RedisOperatorBase类:

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

HashOperator类:

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

UserInfo类:

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

app.config配置:

  1. <?xml version="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操作的封装类,直接拿来调用即可。

最新文章

  1. Linux目录操作
  2. 数据库的sacle-up和scale-out与sharding技术区分
  3. GCD 多线程同步
  4. TCP与UDP
  5. 51nod1161 Partial Sums
  6. 【打表】HDOJ-2089-不要62
  7. C语言,调试必备的DEBUG宏定义
  8. sdbntrjm57k
  9. underscore.js中的节流函数debounce及trottle
  10. VS2010与SVN
  11. PHP学习笔记之PDO
  12. spring mvc:日志对象logger的复用
  13. swoole结合支持thinkphp 5.0版本
  14. wxpy: 用 Python 玩微信【转】
  15. ThreadPoolExecutor代码解析
  16. Java框架之Struts2(四)
  17. modifyGeoJSON
  18. 获取MyBatis
  19. gradle本地、远程仓库配置
  20. Unity获取指定资源目录下的所有文件

热门文章

  1. 玩转JavaScript OOP[2]&mdash;&mdash;类的实现
  2. iOS开发系列--C语言之构造类型
  3. Alljoyn瘦客户端库介绍(官方文档翻译 下)
  4. 从Knockout到Angular的架构演变
  5. static与并发
  6. windows命令——explorer
  7. iOS开发——高级技术&amp;本地化与国际化详解
  8. SSIS 数据类型和类型转换
  9. c/c++多线程模拟系统资源分配(并通过银行家算法避免死锁产生)
  10. 关于有默认值的字段在用EF做插入操作时的思考(续)