Redis学习笔记(2) string 类型值存取
在Redis学习笔记(1)中,我们提到Redis是属于key/value存储结构,value存储的类型有string(字符串)、list(链表)、set(集合)和zset(有序集合)。在接下去的学习中,我们将学习value值的存储。那么我们先学习比较简单的存储类型:String型。说明:由于采用的平台是.net,Redis的客户端选用 ServiceStack.Redis。
1、新建一个名为RedisByString控制台项目。添加项目完成后,通过nuget 查找servicestack.redis。如图1
图1 查找servicestack.redis
添加完成后,在项目引用中多了4如图2红色标记的引用。
图2 servicestack.redis引用
2、ServiceStack.Redis的使用
Redis增加、查看 string 类型的值主要是通过 RedisByString类实现。具体代码如下。
1///
2 /// 表示 string 类型值存储
3 ///
4 public static class RedisByString
5 {
6 ///
7 /// 初始化Redis客户端
8 ///
9 private static RedisClient redisClient = new RedisClient("127.0.0.1");
10
11 ///
12 /// 增加string类型值到Redis服务端
13 ///
14 ///
15 /// 返回value值
16 public static bool PushString(string value)
17 {
18 return redisClient.Set(
19 "name", value);
20 }
21 ///
22 /// 获取key为Name的值
23 ///
24 /// 返回value值
25 public static string PullString()
26 {
27 return redisClient.GetValue("name");
28
29 }
30 ///
31 /// 删除指定的值
32 ///
33 ///
34 public static bool DeleteString()
35 {
36 return redisClient.Remove("name");
37 }
38
39 }
在控制台程序调用我们定义的方法,代码如下:
class Program
{
static void Main(string[] args)
{
///插入一条记录
var pushResult=RedisByString.PushString("hello world myfriend");
Console.WriteLine(pushResult == true ? "增加记录成功!" : "增加记录失败!");
//获取记录
var pullResult = RedisByString.PullString();
Console.WriteLine("key为name的value值为:"+pullResult);
Console.ReadLine();
}
}
输入结果如图3:
图3 测试结果
测试成功!
页:
[1]