Redis C# Driver
- StackExchange.Redis StackOverflow 出品
- ServiceStack.Redis 需要商业授权,免费版本限制每小时的查询次数
# 以下是StackExchange.Redis的基本使用方式
- ConnectionMultiplexer
是StackExchange.Redis中的核心类,字面意思是连接多路复用器,表示Redis服务器集群,也可以是单实例,支持同步或异步的方式进行连接,可使用配置文件,可重用并且线程安全。
- IDatabase
几乎所有StackExchange.Redis中操作Redis的方法都在IDatabase中,从ConnectionMultiplexer对象中获取
var redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
# Redis中的五种基本数据类型的操作
类型 | 释义 |
---|---|
string | 字符串 |
hash | 哈希 |
list | 列表 |
set | 集合 |
zset | 有序集合 |
- string 字符串
var redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
var value = "abcdefg";
db.StringSet("stringKey", value);
Console.WriteLine(db.StringGet("stringKey"));
- hash 哈希
var redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
// StackExchange.Redis 类库中的数据类型k-v形式
var hash = new HashEntry[]
{
new HashEntry("1", "a"),
new HashEntry("2", "b"),
new HashEntry("3", "c")
};
db.HashSet("hashKey", hash);
var values = db.HashGet("hashKey", "1");
Console.WriteLine(values);
- list 列表
var redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
db.KeyDelete("listKey");
// RightPush表示在尾部插入, LeftPush表示在头部插入
db.ListRightPush("listKey", "abcdefghi".Select(x => (RedisValue)x.ToString()).ToArray());
db.ListLeftPush("listKey", "jk".Select(x => (RedisValue)x.ToString()).ToArray());
var values = db.ListRange("listKey");
for (int i = 0; i < values.Length; i++)
{
Console.WriteLine(values[i]);
}
// 输出结果为 : kjabcdefghi
- set 集合
var redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
int totalUnfiltered = 0;
int totalFiltered = 0;
for (int i = 0; i < 1000; i++)
{
db.SetAdd("setKey", i);
totalUnfiltered += i;
if (i.ToString().Contains("3"))
{
totalFiltered += i;
}
}
var unfilteredActual = db.SetScan("setKey").Select(x => (int)x).Sum();
Console.WriteLine($"totalUnfiltered:{totalUnfiltered} - unfilteredActual:{unfilteredActual}");
var filteredActual = db.SetScan("setKey", "*3*").Select(x => (int)x).Sum();
Console.WriteLine($"totalFiltered:{totalFiltered} - filteredActual:{filteredActual}");
- zset 有序集合
var redis = ConnectionMultiplexer.Connect("localhost");
IDatabase db = redis.GetDatabase();
db.SortedSetAdd("zsetKey", "a", 1);
db.SortedSetAdd("zsetKey", "b", 2);
db.SortedSetAdd("zsetKey", "c", 3);
var arr = db.SortedSetScan("zsetKey").ToArray();
Console.WriteLine(arr.Any(x => x.Element == "a" && x.Score == 1));
Console.WriteLine(arr.Any(x => x.Element == "b" && x.Score == 2));
Console.WriteLine(arr.Any(x => x.Element == "c" && x.Score == 3));