1.介绍
转载:http://blog.csdn.net/qiujialongjjj/article/details/16945569
Redis是一个开源的使用ANSI C语言编写的、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库。Redis的出现,很大程序上补偿了memcached这类Key-Value存储的不足,在部分场合可以对关系数据库起到很好的补充作用。最近想学习下NoSql方面的东西,就找Redis来作为学习的入口。先从Git下载最新的32/64位安装包(地址),根据自己的实际情况进行下载安装。我的是64位的机器,将解压后的文件放在“F:\TDDOWNLOAD\Redis\redis-2.4.5-win32-win64\64bit”。如图:
原作者的代码示例:http://download.csdn.net/detail/qiujialongjjj/6613377
2.服务开启
上面我们已经将服务拷贝到了“F:\TDDOWNLOAD\Redis\redis-2.4.5-win32-win64\64bit”,其中redis-server.exe为服务端程序。双击运行。
可以将此服务设置为windows服务,下载Redis服务安装软件,安装即可。安装后,在服务中找到此服务,将其设置为“自动”启动即可。
再回到“F:\TDDOWNLOAD\Redis\redis-2.4.5-win32-win64\64bit”下,找到redis-cli.exe文件,它是Redis客户端程序。
打开,输入:set zhuiyi 123456,即在Redis中插入了一条key为zhuiyi,value为123456的数据,继续输入:get zhuiyi,即获得zhuiyi的值。
如果想知道Redis中一共保存了多少条数据,即可用:key * 来查询。
服务算是连接上了。
3.程序配置
安装好Redis服务之后,就可以从中读取数据,写入数据以及其它的操作了。首先我们需要在Web.config文件对服务进行配置。
<?xml version="1.0" encoding="utf-8"?> <!-- 有关如何配置 ASP.NET 应用程序的详细信息,请访问 http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <configSections> <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --> <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> <section name="RedisConfig" type="RedisDemo.RedisConfigInfo, RedisDemo"/> </configSections> <RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60" MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false"> </RedisConfig> <connectionStrings> <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" /> </connectionStrings> </configuration>
有了以上的信息还不够用,我们还需要C#代码来读取配置节点的值,并进行操作。获取Redis配置的程序如下:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Configuration;
6:
7: namespace RedisDemo
8: {
9: /// <summary>
10: /// Redis配置节点读取
11: /// </summary>
12: public sealed class RedisConfigInfo : ConfigurationSection
13: {
14: public static RedisConfigInfo GetConfig()
15: {
16: RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
17: return section;
18: }
19:
20: public static RedisConfigInfo GetConfig(string sectionName)
21: {
22: RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
23: if (section == null)
24: throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
25: return section;
26: }
27: /// <summary>
28: /// 可写的Redis链接地址
29: /// </summary>
30: [ConfigurationProperty("WriteServerList", IsRequired = false)]
31: public string WriteServerList
32: {
33: get
34: {
35: return (string)base["WriteServerList"];
36: }
37: set
38: {
39: base["WriteServerList"] = value;
40: }
41: }
42:
43:
44: /// <summary>
45: /// 可读的Redis链接地址
46: /// </summary>
47: [ConfigurationProperty("ReadServerList", IsRequired = false)]
48: public string ReadServerList
49: {
50: get
51: {
52: return (string)base["ReadServerList"];
53: }
54: set
55: {
56: base["ReadServerList"] = value;
57: }
58: }
59:
60:
61: /// <summary>
62: /// 最大写链接数
63: /// </summary>
64: [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)]
65: public int MaxWritePoolSize
66: {
67: get
68: {
69: int _maxWritePoolSize = (int)base["MaxWritePoolSize"];
70: return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5;
71: }
72: set
73: {
74: base["MaxWritePoolSize"] = value;
75: }
76: }
77:
78:
79: /// <summary>
80: /// 最大读链接数
81: /// </summary>
82: [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)]
83: public int MaxReadPoolSize
84: {
85: get
86: {
87: int _maxReadPoolSize = (int)base["MaxReadPoolSize"];
88: return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5;
89: }
90: set
91: {
92: base["MaxReadPoolSize"] = value;
93: }
94: }
95:
96:
97: /// <summary>
98: /// 自动重启
99: /// </summary>
100: [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)]
101: public bool AutoStart
102: {
103: get
104: {
105: return (bool)base["AutoStart"];
106: }
107: set
108: {
109: base["AutoStart"] = value;
110: }
111: }
112:
113:
114:
115: /// <summary>
116: /// 本地缓存到期时间,单位:秒
117: /// </summary>
118: [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)]
119: public int LocalCacheTime
120: {
121: get
122: {
123: return (int)base["LocalCacheTime"];
124: }
125: set
126: {
127: base["LocalCacheTime"] = value;
128: }
129: }
130:
131:
132: /// <summary>
133: /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项
134: /// </summary>
135: [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)]
136: public bool RecordeLog
137: {
138: get
139: {
140: return (bool)base["RecordeLog"];
141: }
142: set
143: {
144: base["RecordeLog"] = value;
145: }
146: }
147:
148: }
149: }
Redis管理类代码:
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using ServiceStack.Redis;
6:
7: namespace RedisDemo
8: {
9: /// <summary>
10: /// Redis配置文件管理
11: /// </summary>
12: public class RedisManager
13: {
14: /// <summary>
15: /// redis配置文件信息
16: /// </summary>
17: private static RedisConfigInfo redisConfigInfo = RedisConfigInfo.GetConfig();
18:
19: private static PooledRedisClientManager prcm;
20:
21: /// <summary>
22: /// 静态构造方法,初始化链接池管理对象
23: /// </summary>
24: static RedisManager()
25: {
26: CreateManager();
27: }
28:
29:
30: /// <summary>
31: /// 创建链接池管理对象
32: /// </summary>
33: private static void CreateManager()
34: {
35: string[] writeServerList = SplitString(redisConfigInfo.WriteServerList, ",");
36: string[] readServerList = SplitString(redisConfigInfo.ReadServerList, ",");
37:
38: prcm = new PooledRedisClientManager(readServerList, writeServerList,
39: new RedisClientManagerConfig
40: {
41: MaxWritePoolSize = redisConfigInfo.MaxWritePoolSize,
42: MaxReadPoolSize = redisConfigInfo.MaxReadPoolSize,
43: AutoStart = redisConfigInfo.AutoStart,
44: });
45: }
46:
47: private static string[] SplitString(string strSource, string split)
48: {
49: return strSource.Split(split.ToArray());
50: }
51:
52: /// <summary>
53: /// 客户端缓存操作对象
54: /// </summary>
55: public static IRedisClient GetClient()
56: {
57: if (prcm == null)
58: CreateManager();
59:
60: return prcm.GetClient();
61: }
62:
63: }
64: }
至此,已经可以正确的读取配置文件了。
4.写入数据
1.保存多条数据
1: /// <summary>
2: /// 保存多条数据
3: /// </summary>
4: protected void btnOpenDB_Click(object sender, EventArgs e)
5: {
6: string redisServicePath = @"F:\TDDOWNLOAD\Redis\redis-2.4.5-win32-win64\64bit\redis-server.exe";
7: System.Diagnostics.Process.Start(redisServicePath);//此处为Redis的存储路径 "D:\\redis\\redis-server.exe"
8: lblShow.Text = "Redis已经打开!";
9:
10: using (var redisClient = RedisManager.GetClient())
11: {
12: var user = redisClient.GetTypedClient<User>();
13:
14: if (user.GetAll().Count > 0)
15: {
16: user.DeleteAll();
17: }
18:
19: var userOne = new User
20: {
21: Id = user.GetNextSequence(),
22: Name = "userOne",
23: Job = new Job { Position = ".NET" }
24: };
25:
26: var userTwo = new User
27: {
28: Id = user.GetNextSequence(),
29: Name = "userTwo",
30: Job = new Job { Position = ".NET" }
31: };
32:
33: var userThree = new User
34: {
35: Id = user.GetNextSequence(),
36: Name = "userThree",
37: Job = new Job { Position = ".NET" }
38: };
39:
40: var userFour = new User
41: {
42: Id = user.GetNextSequence(),
43: Name = "userFour",
44: Job = new Job { Position = "Android" }
45: };
46:
47: var userToStore = new List<User> { userOne, userTwo, userThree, userFour };
48: user.StoreAll(userToStore);
49:
50: lblShow.Text = string.Format("目前共有{0}人", user.GetAll().Count.ToString());
51: }
52: }
2.保存单条数据
1: /// <summary>
2: /// 写入单条数据
3: /// </summary>
4: protected void btnInsert_Click(object sender, EventArgs e)
5: {
6: if (!string.IsNullOrEmpty(txtName.Text) && !string.IsNullOrEmpty(txtPosition.Text))
7: {
8: using (var redisClient = RedisManager.GetClient())
9: {
10: var user = redisClient.GetTypedClient<User>();
11:
12: var newUser = new User
13: {
14: Id = user.GetNextSequence(),
15: Name = txtName.Text,
16: Job = new Job { Position = txtPosition.Text }
17: };
18: var userList = new List<User> { newUser };
19: user.StoreAll(userList);
20:
21: btnSetValue_Click(null, null);
22: }
23: }
24: }
3.删除数据
1:
2: /// <summary>
3: /// 删除单条数据
4: /// </summary>
5: protected void btnDel_Click(object sender, EventArgs e)
6: {
7: if (!string.IsNullOrEmpty(txtRedisId.Text))
8: {
9: using (var redisClient = RedisManager.GetClient())
10: {
11: var user = redisClient.GetTypedClient<User>();
12: var newUser = new User
13: {
14: Id = user.GetAll().Count,
15: Name = txtName.Text,
16: Job = new Job { Position = txtPosition.Text }
17: };
18: //user.Delete(newUser);//删除最后一条数据
19: //user.DeleteById(txtRedisId.Text);//删除指定ID的数据
20: //user.DeleteByIds(txtRedisId.Text.ToList());//删除多条数据
21: user.DeleteAll();//删除所有数据
22: btnSetValue_Click(null, null);
23: }
24: }
25: }
4.查询数据
1.通过linq匹配来查询数据
1: /// <summary>
2: /// 查询数据
3: /// </summary>
4: protected void btnSearch_Click(object sender, EventArgs e)
5: {
6: if (!string.IsNullOrEmpty(txtScreenPosition.Text))
7: {
8: using (var redisClient = RedisManager.GetClient())
9: {
10: var user = redisClient.GetTypedClient<User>();
11: var userList = user.GetAll().Where(x => x.Job.Position.Contains(txtScreenPosition.Text)).ToList();
12:
13: if (userList.Count > 0)
14: {
15: var htmlStr = string.Empty;
16: foreach (var u in userList)
17: {
18: htmlStr += "<li>ID=" + u.Id + " 姓名:" + u.Name + " 所在部门:" + u.Job.Position + "</li>";
19: }
20: lblPeople.Text = htmlStr;
21: }
22:
23: lblShow.Text = "筛选后共有:" + userList.Count.ToString() + "人!";
24: }
25: }
26: }
2.通过Key来查询数据
1.显示所有key
1: /// <summary>
2: /// 显示所有keys
3: /// </summary>
4: protected void btnSearchKeys_Click(object sender, EventArgs e)
5: {
6: using (var redisClient = RedisManager.GetClient())
7: {
8: var userKeyList = redisClient.GetAllKeys();
9: if (userKeyList.Count > 0)
10: {
11: var htmlStr = string.Empty;
12: foreach (var u in userKeyList)
13: {
14: htmlStr += string.Format("<li>key={0}</li>", u);
15: }
16:
17: lblPeople.Text = htmlStr;
18: }
19: }
20: }
seq:User 用来纵当前类型User的ID自增序列,用作对象唯一ID,也就是使用GetNextSequence()函数可以获得当前数据库最新的ID的原因了。
ids:User 同一类型User中所有对象ID的列表,相当于一个索引,包含了所有同为类型User的ID;由于维护了这样一个分组信息,所以很容易实现GetAll<User>()的功能。
urn:User:1 这才是保存user对象的key。
在redis-cli.exe中输入get urn:User:1 得到json类型的数据。至此,我们可以通过key来查询数据了。
2.使用key来查询数据
1:
2: /// <summary>
3: /// 根据key查询数据
4: /// </summary>
5: protected void btnSearchDataByKey_Click(object sender, EventArgs e)
6: {
7: using (var redisClient = RedisManager.GetClient())
8: {
9: var keyValue = string.Empty;
10: try
11: {
12: var user = redisClient.GetTypedClient<User>();
13: var value = user.GetValue(txtKey.Text);
14: keyValue += "ID=" + value.Id + " 姓名:" + value.Name + " 所在部门:" + value.Job.Position;
15: }
16: catch (Exception ex)
17: {
18: keyValue += ex.ToString();
19: }
20:
21: lblPeople.Text = keyValue.ToString();
22: }
23: }