為什麼使用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)等類型。
常用結構
.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這是一個.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下載下來運行一下測試~