redis成长之路——(一)

为什么使用redis

Redis适合所有数据in-momory的场景,虽然Redis也提供持久化功能,但实际更多的是一个disk-backed的功能,跟传统意义上的持久化有比较大的差别,那么可能大家就会有疑问,似乎Redis更像一个加强版的Memcached.

上面描述说的过于泛了,很多初次接触的码农可能不明白怎么回事;其实简单来说:如果业务中需要高性能分布式集群等场景的时候,redis就可以派上用场大显身手了!

redis简介

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。

Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

redis成长之路——(一)

常用结构

redis成长之路——(一)

 .net连接redis

StackExchange.Redis是.NET语言中一个高性能的通用redis客户端,一般都基于这个驱动来实现具体的操作业务

github地址:https://github.com/StackExchange/StackExchange.Redis

StackExchange.Redis封装

和ado.net一样,StackExchange.Redis只是一个provider,码农们直接用起来会很麻烦,不光要去理解它里面很多概念,还要根据不同的场景写不能的代码,所以在实际业务中,本人封装了一个drive.redis

github地址:https://github.com/yswenli/RedisDrive/tree/master/Wenli.Drive.Redis

Wenli.Drive.Redis的使用

本人封装的这个drive.redis是基于现有相关项目完善而成的,主要目的就是为码农们方便开展自已的业务,无需去关心中间相当部内容;使用可以参考md文件中的描述:

RedisDrive

RedisDrive这是一个.net 的redis集成驱动,支持单实例、云集群、哨兵等模式的数据操作,支持keys等命令

本驱动基于stackexcnage.redis完成,在此基础上强化使用的简洁性、可靠性

wenli.Drive.Redis使用方法:

1.添加wenli.Drive.Redis引用

2.添加stackexcnage.redis nuget包引用

3.添加Wenli.Drive.Redis、log4net配置节点,添加RedisClient appsettings

app.config(web.config)配置如下: <?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="RedisConfig" type="Wenli.Drive.Redis.RedisConfig, Wenli.Drive.Redis" />
    <section name="SentinelConfig" type="Wenli.Drive.Redis.RedisConfig, Wenli.Drive.Redis" />
    <section name="ClusterConfig" type="Wenli.Drive.Redis.RedisConfig, Wenli.Drive.Redis" />
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  <!--单点模式配置-->
  <RedisConfig Type="0" Masters="127.0.0.1:6379" Slaves="127.0.0.1:6379" DefaultDatabase="0" />
  <!--哨兵模式配置-->
  <SentinelConfig Type="1" Masters="127.0.0.1:26379" ServiceName="mymaster" DefaultDatabase="0" />
  <!--集群模式配置-->
  <ClusterConfig Type="2" Masters="127.0.0.1:16379,127.0.0.1:16380,127.0.0.1:16381" />
  <log4net>
    <logger name="logerror">
      <level value="ERROR" />
      <appender-ref ref="ErrorAppender" />
    </logger>
    <logger name="loginfo">
      <level value="INFO" />
      <appender-ref ref="InfoAppender" />
    </logger>
    <logger name="logdebug">
      <level value="DEBUG" />
      <appender-ref ref="DebugAppender" />
    </logger>
    <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="ErrorLog.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="MaximumFileSize" value="1MB" />
      <param name="RollingStyle" value="Size" />
      <param name="StaticLogFileName" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p %d [%c] %m%n" />
      </layout>
    </appender>
    <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="InfoLog.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="MaximumFileSize" value="1MB" />
      <param name="RollingStyle" value="Size" />
      <param name="StaticLogFileName" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p %d [%c] %m%n" />
      </layout>
    </appender>
    <appender name="DebugAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="DebugLog.log" />
      <param name="AppendToFile" value="true" />
      <param name="MaxSizeRollBackups" value="100" />
      <param name="MaximumFileSize" value="1MB" />
      <param name="RollingStyle" value="Size" />
      <param name="StaticLogFileName" value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%-5p %d [%c] %m%n" />
      </layout>
    </appender>
  </log4net>
  <appSettings>
    <add key="RedisClient" value="Wenli.Drive.Redis.Core.SERedisHelper;Wenli.Drive.Redis,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null" />
  </appSettings>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.6.10.0" newVersion="2.6.10.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Threading.Tasks" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.6.10.0" newVersion="2.6.10.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

实例代码:

class Program
{
static void Main(string[] args)
{
Console.Title = "Wenli.Drive.Redis驱动测试"; Console.WriteLine("Wenli.Drive.Redis test"); Console.WriteLine("输入s 测试哨兵模式,输入c测试cluster模式,M为连续,其它为单实例模式"); while (true)
{ var c = Console.ReadLine(); if (c.ToUpper() == "S")
{
#region sentinel
Console.WriteLine("Wenli.Drive.Redis test 进入哨兵模式---------------------"); using (var redisHelper = RedisHelperBuilder.Build("ClusterConfig"))
{ #region string
Console.ReadLine();
Console.WriteLine("string get/set test"); redisHelper.GetRedisOperation().StringSet("abcabcabc", "123123");
Console.WriteLine("写入key:abcabcabc,value:123123"); var str = redisHelper.GetRedisOperation().StringGet("abcabcabc");
Console.WriteLine("查询key:abcabcabc,value:" + str); redisHelper.GetRedisOperation().KeyDelete("abcabcabc");
Console.WriteLine("移除key:abcabcabc");
#endregion #region hashset
Console.ReadLine();
Console.WriteLine("hashset get/set test");
var testModel = new DemoModel()
{
ID = Guid.NewGuid().ToString("N"),
Age = 18,
Name = "Kitty",
Created = DateTime.Now
}; redisHelper.GetRedisOperation().HashSet<DemoModel>(testModel.Name, testModel.ID, testModel);
Console.WriteLine(string.Format("写入hashid:{0},key:{1}", testModel.Name, testModel.ID)); testModel = redisHelper.GetRedisOperation().HashGet<DemoModel>(testModel.Name, testModel.ID);
Console.WriteLine(string.Format("查询hashid:{0},key:{1}", testModel.Name, testModel.ID)); redisHelper.GetRedisOperation().HashDelete(testModel.Name, testModel.ID);
Console.WriteLine("移除hash");
#endregion #region 队列
Console.ReadLine();
Console.WriteLine("list test"); redisHelper.GetRedisOperation().Enqueue("list", "listvalue");
Console.WriteLine("入队:list,value:listvalue"); Console.WriteLine("list.coumt:" + redisHelper.GetRedisOperation().QueueCount("list")); Console.WriteLine(string.Format("出队:list,value:{0}", redisHelper.GetRedisOperation().Dnqueue("list")));
Console.WriteLine("list.coumt:" + redisHelper.GetRedisOperation().QueueCount("list"));
#endregion #region sortedset
Console.ReadLine();
Console.WriteLine("sortedset test");
Console.WriteLine(string.Format("sortedset add :{0}", redisHelper.GetRedisOperation().SortedSetAdd("sortedset", "sortedset", 0)));
var list = redisHelper.GetRedisOperation().GetSortedSetRangeByRankWithSocres("sortedset", 0, 10000, 1, 9999, true);
Console.WriteLine(string.Format("sortedset getlist :{0}", list));
Console.WriteLine(string.Format("sortedset remove :{0}", redisHelper.GetRedisOperation().RemoveItemFromSortedSet("sortedset", "sortedset")));
#endregion #region pub/sub
Console.ReadLine();
Console.WriteLine("sub/pub test"); Console.WriteLine("订阅频道:happy"); redisHelper.GetRedisOperation().Subscribe("happy", (x, y) =>
{
Console.WriteLine(string.Format("订阅者收到消息;频道:{0},消息:{1}", x, y));
}); Console.WriteLine("发布频道happy 10 条测试消息");
for (int i = 1; i <= 10; i++)
{
redisHelper.GetRedisOperation().Publish("happy", "this is a test message" + i);
Thread.Sleep(400);
}
#endregion
Console.ReadLine();
redisHelper.GetRedisOperation().Unsubscribe("happy"); }
#endregion
}
else if (c.ToUpper() == "C")
{
#region cluster
Console.WriteLine("Wenli.Drive.Redis test 进入集群模式---------------------"); var redisHelper = RedisHelperBuilder.Build("ClusterConfig"); #region string
Console.ReadLine();
Console.WriteLine("string get/set test"); redisHelper.GetRedisOperation().StringSet("abcabcabc", "123123");
Console.WriteLine("写入key:abcabcabc,value:123123"); var str = redisHelper.GetRedisOperation().StringGet("abcabcabc");
Console.WriteLine("查询key:abcabcabc,value:" + str); redisHelper.GetRedisOperation().KeyDelete("abcabcabc");
Console.WriteLine("移除key:abcabcabc");
#endregion #region hashset
Console.ReadLine();
Console.WriteLine("hashset get/set test");
var testModel = new DemoModel()
{
ID = Guid.NewGuid().ToString("N"),
Age = 18,
Name = "Kitty",
Created = DateTime.Now
}; redisHelper.GetRedisOperation().HashSet<DemoModel>(testModel.Name, testModel.ID, testModel);
Console.WriteLine(string.Format("写入hashid:{0},key:{1}", testModel.Name, testModel.ID)); testModel = redisHelper.GetRedisOperation().HashGet<DemoModel>(testModel.Name, testModel.ID);
Console.WriteLine(string.Format("查询hashid:{0},key:{1}", testModel.Name, testModel.ID)); redisHelper.GetRedisOperation().HashDelete(testModel.Name, testModel.ID);
Console.WriteLine("移除hash");
#endregion #region 队列
Console.ReadLine();
Console.WriteLine("list test"); redisHelper.GetRedisOperation().Enqueue("list", "listvalue");
Console.WriteLine("入队:list,value:listvalue"); Console.WriteLine("list.coumt:" + redisHelper.GetRedisOperation().QueueCount("list")); Console.WriteLine(string.Format("出队:list,value:{0}", redisHelper.GetRedisOperation().Dnqueue("list")));
Console.WriteLine("list.coumt:" + redisHelper.GetRedisOperation().QueueCount("list"));
#endregion #region pub/sub
Console.ReadLine();
Console.WriteLine("sub/pub test"); Console.WriteLine("订阅频道:happy"); redisHelper.GetRedisOperation().Subscribe("happy", (x, y) =>
{
Console.WriteLine(string.Format("订阅者收到消息;频道:{0},消息:{1}", x, y));
}); Console.WriteLine("发布频道happy 10 条测试消息");
for (int i = 1; i <= 10; i++)
{
redisHelper.GetRedisOperation().Publish("happy", "this is a test message" + i);
Thread.Sleep(400);
}
#endregion Console.ReadLine(); redisHelper.GetRedisOperation().Unsubscribe("happy");
#endregion
}
else if (c.ToUpper() == "M")
{
#region default redis
Console.WriteLine("Wenli.Drive.Redis test 进入连续测试模式---------------------"); string value = "123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式123123进入连续测试模式"; var td1 = new Thread(new ThreadStart(() =>
{
using (var redisHelper = RedisHelperBuilder.Build("SentinelConfig"))
{
Parallel.For(0, 100000, countIndex =>
{
#region string
Console.WriteLine("string get/set test");
redisHelper.GetRedisOperation().StringSet(countIndex.ToString(), value);
Console.WriteLine("写入key:abcabcabc,value:123123"); var str = redisHelper.GetRedisOperation().StringGet(countIndex.ToString());
Console.WriteLine("查询key:abcabcabc,value:" + str); redisHelper.GetRedisOperation().KeyDelete(countIndex.ToString());
Console.WriteLine("移除key:abcabcabc");
#endregion #region hashset
Console.WriteLine("hashset get/set test");
var testModel = new DemoModel()
{
ID = Guid.NewGuid().ToString("N"),
Age = 18,
Name = "Kitty",
Created = DateTime.Now
}; redisHelper.GetRedisOperation().HashSet<DemoModel>(testModel.Name, testModel.ID, testModel);
Console.WriteLine(string.Format("写入hashid:{0},key:{1}", testModel.Name, testModel.ID)); testModel = redisHelper.GetRedisOperation().HashGet<DemoModel>(testModel.Name, testModel.ID);
Console.WriteLine(string.Format("查询hashid:{0},key:{1}", testModel.Name, testModel.ID)); redisHelper.GetRedisOperation().HashDelete(testModel.Name, testModel.ID);
Console.WriteLine("移除hash");
#endregion });
}
}));
var td2 = new Thread(new ThreadStart(() =>
{
Parallel.For(0, 100000, countIndex =>
{
using (var redisHelper = RedisHelperBuilder.Build("SentinelConfig"))
{
#region string
Console.WriteLine("string get/set test");
redisHelper.GetRedisOperation().StringSet(countIndex.ToString(), value);
Console.WriteLine("写入key:abcabcabc,value:123123"); var str = redisHelper.GetRedisOperation().StringGet(countIndex.ToString());
Console.WriteLine("查询key:abcabcabc,value:" + str); redisHelper.GetRedisOperation().KeyDelete(countIndex.ToString());
Console.WriteLine("移除key:abcabcabc");
#endregion #region hashset
Console.WriteLine("hashset get/set test");
var testModel = new DemoModel()
{
ID = Guid.NewGuid().ToString("N"),
Age = 18,
Name = "Kitty",
Created = DateTime.Now
}; redisHelper.GetRedisOperation().HashSet<DemoModel>(testModel.Name, testModel.ID, testModel);
Console.WriteLine(string.Format("写入hashid:{0},key:{1}", testModel.Name, testModel.ID)); testModel = redisHelper.GetRedisOperation().HashGet<DemoModel>(testModel.Name, testModel.ID);
Console.WriteLine(string.Format("查询hashid:{0},key:{1}", testModel.Name, testModel.ID)); redisHelper.GetRedisOperation().HashDelete(testModel.Name, testModel.ID);
Console.WriteLine("移除hash");
#endregion
}
});
})); td1.Start();
td2.Start(); while (td1.IsAlive || td2.IsAlive)
{
Thread.Sleep(50);
} Console.WriteLine("Wenli.Drive.Redis test 任务已完成!---------------------");
#endregion
}
else
{
#region default redis
Console.WriteLine("Wenli.Drive.Redis test 进入单实例模式---------------------"); var redisHelper = RedisHelperBuilder.Build("RedisConfig"); #region string
Console.ReadLine();
Console.WriteLine("string get/set test"); redisHelper.GetRedisOperation(12).StringSet("abcabcabc", "123123");
Console.WriteLine("写入key:abcabcabc,value:123123"); var str = redisHelper.GetRedisOperation(12).StringGet("abcabcabc");
Console.WriteLine("查询key:abcabcabc,value:" + str); redisHelper.GetRedisOperation(12).KeyDelete("abcabcabc");
Console.WriteLine("移除key:abcabcabc");
#endregion #region hashset
Console.ReadLine();
Console.WriteLine("hashset get/set test");
var testModel = new DemoModel()
{
ID = Guid.NewGuid().ToString("N"),
Age = 18,
Name = "Kitty",
Created = DateTime.Now
}; redisHelper.GetRedisOperation().HashSet<DemoModel>(testModel.Name, testModel.ID, testModel);
Console.WriteLine(string.Format("写入hashid:{0},key:{1}", testModel.Name, testModel.ID)); testModel = redisHelper.GetRedisOperation().HashGet<DemoModel>(testModel.Name, testModel.ID);
Console.WriteLine(string.Format("查询hashid:{0},key:{1}", testModel.Name, testModel.ID)); redisHelper.GetRedisOperation().HashGetAll<DemoModel>(testModel.Name, 1, 1); redisHelper.GetRedisOperation().HashDelete(testModel.Name, testModel.ID);
Console.WriteLine("移除hash");
#endregion #region 队列
Console.ReadLine();
Console.WriteLine("list test"); redisHelper.GetRedisOperation().Enqueue("list", "listvalue");
Console.WriteLine("入队:list,value:listvalue"); Console.WriteLine("list.coumt:" + redisHelper.GetRedisOperation().QueueCount("list")); Console.WriteLine(string.Format("出队:list,value:{0}", redisHelper.GetRedisOperation().Dnqueue("list")));
Console.WriteLine("list.coumt:" + redisHelper.GetRedisOperation().QueueCount("list"));
#endregion #region pub/sub
Console.ReadLine();
Console.WriteLine("sub/pub test"); Console.WriteLine("订阅频道:happy"); redisHelper.GetRedisOperation().Subscribe("happy", (x, y) =>
{
Console.WriteLine(string.Format("订阅者收到消息;频道:{0},消息:{1}", x, y));
}); Console.WriteLine("发布频道happy 10 条测试消息");
for (int i = 1; i <= 10; i++)
{
redisHelper.GetRedisOperation().Publish("happy", "this is a test message" + i);
Thread.Sleep(400);
}
#endregion Console.ReadLine(); redisHelper.GetRedisOperation().Unsubscribe("happy"); #endregion
}
} Console.ReadLine();
}
}

当然也可将https://github.com/yswenli/RedisDrive/tree/master/DriveTest下载下来运行一下测试~

redis成长之路——(一)

redis成长之路——(二)

redis成长之路——(三)

redis成长之路——(四)

redis成长之路——(五)

redis成长之路——(六)

redis成长之路——(七)

转载请标明本文来源:http://www.cnblogs.com/yswenli/p/6235765.html
更多内容欢迎star作者的github:https://github.com/yswenli/RedisDrive
如果发现本文有什么问题和任何建议,也随时欢迎交流~

上一篇:PDO防注入原理分析以及使用PDO的注意事项 (转)


下一篇:MVC路由配置