C# Redis实战

时间:2023-03-08 20:32:08

转自  :http://blog.****.net/qiujialongjjj/article/details/16945569

一、初步准备

Redis 是一个开源的使用ANSI C 语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value 数据库。Redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部 分场合可以对关系数据库起到很好的补充作用。
本文主要讲述的是如何使用C#语言来进行Redis分布式缓存的程序编写。首先,需要从github下载最新的32/64位安装(下载地址),解压后根据自己机器的实际情况选择32位或者64位,例如:我机器是64位win7,于是将64bit下所有文件拷贝到D盘根目录下新建文件夹redis中,如图:
C# Redis实战
接下来我们需要在vs中新建一个Redis的测试Demo,并为其添加Redis程序包,如图:
C# Redis实战
至此,Redis分布式编程的准备工作已经完成,可以得到如下示例Demo效果图:
C# Redis实战

二、Redis服务

 在C# Redis实战(一)中我将所有文件拷贝到了D盘redis文件夹下,其中redis-server.exe即为其服务端程序,双击即开始运行,如图
           C# Redis实战
可以将此服务设置为windows系统服务,下载Redis服务安装软件,安装即可。
安装完成在服务中找到此服务,将其设置为自动延迟启动即可。
C# Redis实战
再回到redis文件夹下,找到redis-cli.exe文件,它就是Redis客户端程序。打开,输入:set qiujialong 123
C# Redis实战
即在Redis中插入了一条key为qiujialong,value为123的数据,继续输入:get qiujialong
C# Redis实战
得到value保存的数据123。
如果想知道Redis中一共保存了多少条数据,则可以使用:keys * 来查询:
C# Redis实战
以上即为Redis服务的安装与它的基本操作,再下一篇文章中将讲述如何使用C#来完成Redis分布式缓存的开发。

三、程序配置

C# Redis实战(二)中我们安装好了Redis的系统服务,此时Redis服务已经运行。
现在我们需要让我们的程序能正确读取到Redis服务地址等一系列的配置信息,首先,需要在Web.config文件中添加如下信息:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!--
  3. 有关如何配置 ASP.NET 应用程序的详细信息,请访问
  4. http://go.microsoft.com/fwlink/?LinkId=169433
  5. -->
  6. <configuration>
  7. <configSections>
  8. <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  9. <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  10. <section name="RedisConfig" type="RedisDemo.RedisConfigInfo, RedisDemo"/>
  11. </configSections>
  12. <RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60"
  13. MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false">
  14. </RedisConfig>
  15. <connectionStrings>
  16. <add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-RedisDemo-20131125110945;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-RedisDemo-20131125110945.mdf" />
  17. </connectionStrings>
  18. </configuration>
有了以上信息还不够,还需要用C#代码来读取并且操作,获取Redis配置的程序如下:
  1. public static RedisConfigInfo GetConfig()
  2. {
  3. RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
  4. return section;
  5. }
  6. public static RedisConfigInfo GetConfig(string sectionName)
  7. {
  8. RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
  9. if (section == null)
  10. throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
  11. return section;
  12. }
Redis管理类代码:
  1. /// <summary>
  2. /// redis配置文件信息
  3. /// </summary>
  4. private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig();
  5. private static PooledRedisClientManager prcm;
  6. /// <summary>
  7. /// 静态构造方法,初始化链接池管理对象
  8. /// </summary>
  9. static RedisManager()
  10. {
  11. CreateManager();
  12. }
  13. /// <summary>
  14. /// 创建链接池管理对象
  15. /// </summary>
  16. private static void CreateManager()
  17. {
  18. string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ",");
  19. string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ",");
  20. prcm = new PooledRedisClientManager(readServerList, writeServerList,
  21. new RedisClientManagerConfig
  22. {
  23. MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize,
  24. MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize,
  25. AutoStart = redisConfigInfo.AutoStart,
  26. });
  27. }
  28. private static string[] SplitString(string strSource, string split)
  29. {
  30. return strSource.Split(split.ToArray());
  31. }
  32. /// <summary>
  33. /// 客户端缓存操作对象
  34. /// </summary>
  35. public static IRedisClient GetClient()
  36. {
  37. if (prcm == null)
  38. CreateManager();
  39. return prcm.GetClient();
  40. }
  41. 四、写入数据

    C# Redis实战(三)中我们已经配置好了web.config程序,并且能通过C#代码来读取和管理以上配置信息。
    接下来,就可以进行Redis的数据写入了。Redis中可以用Store和StoreAll分别保存单条和多条数据,C#中具体代码如下:
    1、保存多条数据
    1. protected void btnOpenDB_Click(object sender, EventArgs e)
    2. {
    3. //System.Diagnostics.Process.Start("D:\\redis\\redis-server.exe");
    4. //lblShow.Text = "Redis已经打开!";
    5. using (var redisClient = RedisManager.GetClient())
    6. {
    7. var user = redisClient.GetTypedClient<User>();
    8. if (user.GetAll().Count > 0)
    9. user.DeleteAll();
    10. var qiujialong = new User
    11. {
    12. Id = user.GetNextSequence(),
    13. Name = "qiujialong",
    14. Job = new Job { Position = ".NET" }
    15. };
    16. var chenxingxing = new User
    17. {
    18. Id = user.GetNextSequence(),
    19. Name = "chenxingxing",
    20. Job = new Job { Position = ".NET" }
    21. };
    22. var luwei = new User
    23. {
    24. Id = user.GetNextSequence(),
    25. Name = "luwei",
    26. Job = new Job { Position = ".NET" }
    27. };
    28. var zhourui = new User
    29. {
    30. Id = user.GetNextSequence(),
    31. Name = "zhourui",
    32. Job = new Job { Position = "Java" }
    33. };
    34. var userToStore = new List<User> { qiujialong, chenxingxing, luwei, zhourui };
    35. user.StoreAll(userToStore);
    36. lblShow.Text = "目前共有:" + user.GetAll().Count.ToString() + "人!";
    37. }
    38. }
    2、保存单条数据
    1. protected void btnInsert_Click(object sender, EventArgs e)
    2. {
    3. if (!string.IsNullOrEmpty(txtName.Text) && !string.IsNullOrEmpty(txtPosition.Text))
    4. {
    5. using (var redisClient = RedisManager.GetClient())
    6. {
    7. var user = redisClient.GetTypedClient<User>();
    8. var newUser = new User
    9. {
    10. Id = user.GetNextSequence(),
    11. Name = txtName.Text,
    12. Job = new Job { Position = txtPosition.Text }
    13. };
    14. user.Store(newUser);
    15. if (user.GetAll().Count > 0)
    16. {
    17. var htmlStr = string.Empty;
    18. foreach (var u in user.GetAll())
    19. {
    20. htmlStr += "<li>ID=" + u.Id + "  姓名:" + u.Name + "  所在部门:" + u.Job.Position + "</li>";
    21. }
    22. lblPeople.Text = htmlStr;
    23. }
    24. lblShow.Text = "目前共有:" + user.GetAll().Count.ToString() + "人!";
    25. }
    26. }
    27. }
    效果图:
    C# Redis实战