ASP.net MVC redis完整示例(含集合,哈希,sortedset)
(核心部分原创,转载请保留链接)
1:下载redis for windows or linux安装并开启服务,并在vs的工具菜单下安装nuget(本文采用windows版本)
http://www.fanli7.net/a/caozuoxitong/Windows/20150318/497842.html(redis安装和开启)
http://www.cnblogs.com/chsword/archive/2011/09/14/nuget_install_operatepackage.html(nuget安装)
2:建立asp.net mvc4项目(internet app)
3:通过nuget 图形界面或者命令行安装redis(其实可以拷贝stackservice.redis.dll等几个相关文件)(要么,命令行安装,要么选择.net3.5再改回来(.net 4),要么图形界面不要选那个黑色的redis c#,要么拷贝dll)才能成功安装.http://www.cnblogs.com/kissdodog/p/3570984.html(redis for VS安装与配置,注:原文有错,要选那个蓝色的而不是黑色的,或者使用nuget命令行安装)
4:添加引用:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceStack.Redis;
using System.Collections;
using ServiceStack.Common;
4:替换HomeController类中的Index方法:
public ActionResult Index()
{
RedisClientManagerConfig RedisConfig = new RedisClientManagerConfig();
RedisConfig.AutoStart = true;
RedisConfig.MaxReadPoolSize = 60;
RedisConfig.MaxWritePoolSize = 60;
PooledRedisClientManager prcm = new PooledRedisClientManager(new List<string>() { "127.0.0.1" }, new List<string>() { "127.0.0.1" }, RedisConfig);
using (IRedisClient RClient = prcm.GetClient())
{
RClient.Add("p2", "Hello world,");
}
using (IRedisClient RClient = prcm.GetClient())
{
RClient.Get<string>("p2");
}
using (IRedisClient RClient = prcm.GetClient())
{
var set = RClient.Sets["Set"];
set.Add("bill");
set.Add("bob");
set.Add("jeremey");
var otherSet = RClient.Sets["OtherSet"];
otherSet.Add("bill");
otherSet.Add("jeb");
otherSet.Add("kermin");
List<string> keys = RClient.GetAllKeys();
IEnumerator myie = set.GetEnumerator();
myie.Reset();
string text = string.Empty;//重置
while (myie.MoveNext())
{
text += myie.Current.ToString() + ", ";
}
var hash = RClient.Hashes["myhash"];
hash.Add("key1", "value1");
hash.Add("key2", "value2");
hash.Add("key3", "value3");
IEnumerator ie = hash.GetEnumerator();
string hashtext = string.Empty;
while (ie.MoveNext())
{
hashtext += ie.Current.ToString() + ", ";
}
}
var sortset=RClient.SortedSets["mysortedset1"];
sortset.Add("hello");
sortset.Add("mello");
sortset.Add("aello");
RClient.Add("myself1",sortset);
dynamic result = RClient.GetValue("myself1");
var child = result[0];
Response.Write(hashtext);
return Content("");
/* 大家对比下细节看看呢,上面操作的是副本,即便再次增加,内存中的内容也不会更新,而注释掉的就不一样了.而且,明显看书,是排序过的
RClient.Remove("myself1");
var sortset=RClient.SortedSets["mysortedset1"];
sortset.Add("hello");
sortset.Add("mello");
sortset.Add("aello");
sortset.Add("123");
RClient.Add("myself1",sortset);
dynamic result = RClient.GetValue("myself1").GetEnumerator();
string resulttext = string.Empty;
result.Reset();
while (result.MoveNext())
{
resulttext += result.Current.ToString() + ", ";
}
//下面是发布订阅模型示例和命令行的几个命令示例
using (RedisClient client = new RedisClient("127.0.0.1:6379"))
{
RedisClient client1 = new RedisClient("127.0.0.1:6379");
client1.Subscribe("channel");
client.PublishMessage("channel", "message");
//每一个客户端连接后会发送一条请求同步的命令,服务器于是给他一个快照同步,并继续缓存收到的命令,
//稍后再一起把后续的操作打包给客户端
//最终实现完全同步
client.ZAdd("sortedset1", 45, new byte[] {1,2,3,4,5,6,7,4,3 });
var a= client.ZCard("sortedset1");
var b = client.ZRange("sortedset1", 0, 1);
}
Response.Write(hashtext);/*
}
//测试list的方法,随意放在控制器中,空视图即可
public string RedisList()
{
RedisClient client = new RedisClient("127.0.0.1:6379");
byte[] mylist = new byte[] { 1, 2, 3, 43, 21, 54, 32 };
client.LPush("listid", mylist);
byte[][] result = TestList();
return result.ToString();
}
private byte[][] TestList()
{ RedisClient clientt = new RedisClient("127.0.0.1:6379");
return clientt.LRange("listid", 0, 2);
}
//要和官方手册上的命令行一一对应,可以这样创建链接对象:RedisClient client=new RedisClient("host:port");//此处有五个重载
client.get,mget,set,mset,getset,hset,hget,sadd,sinter ,sinterstore等等都可以用了,亲测通过
//一个更复杂的例子:参照它可以实现和数据库的同步,而且,更重要的是,无需转化,只需组合封装,极为方便
public string testComplexDadaTable()
{
using (RedisClient clientt = new RedisClient("127.0.0.1:6379"))
{
DataTable dt = GetDataTable();
var columns = dt.Columns;
var rows = dt.Rows;
List<DateTime> mydate = new List<DateTime>();
for (int i = 0; i < rows.Count; i++)
{
DateTime test = (rows[i].Field<DateTime>(3));
mydate.Add(test);
}
clientt.Set<List<DateTime>>("mydate", mydate);
}
RedisClient rdc = new RedisClient("127.0.0.1:6379");
var valueComplex = rdc.Get<List<DateTime>>("mydate");
return null; //
clientt.LPush("redis:mysql:10086", null);
}
private DataTable GetDataTable() {
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table; }
//为什么redis存储本质是流,如下示例:
public string testComplexDadaTable()
{
public string testComplexDadaTable()
{
string key = "key";
byte[] bytekey = System.Text.Encoding.Default.GetBytes(key);
using (RedisClient clientt = new RedisClient("127.0.0.1:6379"))
{
DataTable dt = GetDataTable();
var columns = dt.Columns;
var rows = dt.Rows;
List<DateTime> mydate = new List<DateTime>();
List<DataRow> datarow = new List<DataRow>();
Hashtable hashtable = new Hashtable();
for (int i = 0; i < rows.Count; i++)
{ DateTime test = (rows[i].Field<DateTime>(3));
mydate.Add(test);
string testby = test.ToString();
byte[] arrtext = System.Text.Encoding.Default.GetBytes(testby);
clientt.HSet("hashkey", bytekey, arrtext);
if(!hashtable.ContainsKey("key"))
{
hashtable.Add("key", test);
}
} clientt.Get<DataRow>("row");
clientt.Set<List<DateTime>>("mydate", mydate);
}
RedisClient rdc = new RedisClient("127.0.0.1:6379");
var valueComplex = rdc.Get<List<DateTime>>("mydate");
var byteresult = rdc.HGet("hashkey", bytekey);
string constructedString = System.Text.Encoding.Default.GetString(byteresult);
return null;
// clientt.LPush("redis:mysql:10086", null);
}
private DataTable GetDataTable()
{
DataTable table = new DataTable();
table.Columns.Add("Dosage", typeof(int));
table.Columns.Add("Drug", typeof(string));
table.Columns.Add("Patient", typeof(string));
table.Columns.Add("Date", typeof(DateTime));
// Here we add five DataRows.
table.Rows.Add(25, "Indocin", "David", DateTime.Now);
table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now);
table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now);
table.Rows.Add(21, "Combivent", "Janet", DateTime.Now);
table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now);
return table;
}
5:运行
注意:官方dll目前没有提供RedisClientHash类,需要用的话自己要从github拷贝下来加入工程(本实例没有用到),另外说明一点:只是hellworld没意思,所以给出了set示例,hash示例(没有参考任何文档,折腾死),测试大法好.
最后:
http://www.cnblogs.com/stephen-liu74/archive/2012/04/16/2370212.html(命令行示例大全)
http://www.lvtao.net/book/redis.htm(中文手册)
以上过程掌握后,请阅读源代码.