2015年3月19日 星期四

Redis筆記-數據類型-Hash 使用範例

介紹簡單的使用
語言:c#
使用函式庫:StackExchange.Redis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//設定連線字串
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect("127.0.0.1:10001"))
{
    // 取得操作介面
    IDatabase cache = conn.GetDatabase();
 
    const string custKey1 = "Key1";
 
    // 先刪除該Key以確保這個key對應資料型態是全新的
    cache.KeyDeleteAsync(custKey1);
 
    // 設定值
    cache.HashSetAsync(custKey1, "abc", "def");
    cache.HashSetAsync(custKey1, "ghi", "jkl");
    cache.HashSetAsync(custKey1, "mno", "pqr");
 
    // 依照custKey1取得對應hash值
    HashEntry[] tResult = cache.HashGetAll(custKey1);
    foreach (HashEntry tHE in tResult)
    {
        Console.WriteLine(tHE.Name + ":" + tHE.Value);
    }
}

我們也可以使用HashSet() 一次設定好Hash的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//設定連線字串
using (ConnectionMultiplexer conn = ConnectionMultiplexer.Connect("127.0.0.1:10001"))
{
    // 取得操作介面
    IDatabase cache = conn.GetDatabase();
 
    const string custKey1 = "Key1";
 
    // 先刪除該Key以確保這個key對應資料型態是全新的
    cache.KeyDeleteAsync(custKey1);
 
    // 設定值
    HashEntry[] hashEntries =
        {
            new HashEntry("abc", "def"),
            new HashEntry("ghi", "jkl"),
            new HashEntry("mno", "pqr"),
        };
    cache.HashSet(custKey1, hashEntries);
 
    // 依照custKey1取得對應hash值
    HashEntry[] tResult = cache.HashGetAll(custKey1);
    foreach (HashEntry tHE in tResult)
    {
        Console.WriteLine(tHE.Name + ":" + tHE.Value);
    }
}

以下為使用搜索範例
1
2
3
4
5
6
7
8
9
10
// 搜索這個key的所有內容
IEnumerable<hashentry> t1 = cache.HashScan(custKey1);
HashEntry[] v1 = t1.ToArray();
                 
Console.WriteLine("==HashScan(custKey1)==");
foreach (HashEntry tHE in v1)
{
    Console.WriteLine(tHE.Name + ":" + tHE.Value);
}
</hashentry>
條件過濾
1
2
3
4
5
6
7
8
9
10
// 加條件的過濾搜索
IEnumerable<hashentry> t2 = cache.HashScan(custKey1, "*h*");
HashEntry[] v2 = t2.ToArray();
 
Console.WriteLine("==HashScan(custKey1,'*h*')==");
foreach (HashEntry tHE in v2)
{
    Console.WriteLine(tHE.Name + ":" + tHE.Value);
}
</hashentry>


沒有留言:

張貼留言