FreeRedis
基于 .NET 的 Redis 用戶端,支援 .NET Core 2.1+、.NET Framework 4.0+ 以及 Xamarin。
特點
- • 🌈 所有方法名與 redis-cli 保持一緻
- • 🌌 支援 Redis 叢集(服務端要求 3.2 及以上版本)
- • ⛳ 支援 Redis 哨兵模式
- • 🎣 支援主從分離(Master-Slave)
- • 📡 支援釋出訂閱(Pub-Sub)
- • 📃 支援 Redis Lua 腳本
- • 💻 支援管道(Pipeline)
- • 📰 支援事務
- • 🌴 支援 GEO 指令(服務端要求 3.2 及以上版本)
- • 🌲 支援 STREAM 類型指令(服務端要求 5.0 及以上版本)
- • ⚡ 支援本地緩存(Client-side-cahing,服務端要求 6.0 及以上版本)
- • 🌳 支援 Redis 6 的 RESP3 協定
快速入門
public static RedisClient cli = new RedisClient("127.0.0.1:6379,password=123,defaultDatabase=13");
//cli.Serialize = obj => JsonConvert.SerializeObject(obj);
//cli.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
cli.Notice += (s, e) => Console.WriteLine(e.Log); //列印指令日志
cli.Set("key1", "value1");
cli.MSet("key1", "value1", "key2", "value2");
string value1 = cli.Get("key1");
string[] vals = cli.MGet("key1", "key2");
支援 STRING、HASH、LIST、SET、ZSET、BITMAP、HyperLogLog、GEO、Stream 以及布隆過濾器等。
參數 | 預設值 | 說明 |
protocol | RESP2 | 若使用 RESP3 協定,你需要 Redis 6.0 環境 |
user | <empty> | Redis 服務端使用者名,要求 Redis 6.0 環境 |
password | <empty> | Redis 服務端密碼 |
defaultDatabase | Redis 服務端資料庫 | |
max poolsize | 100 | 連接配接池最大連接配接數 |
min poolsize | 5 | 連接配接池最小連接配接數 |
idleTimeout | 20000 | 連接配接池中元素的空閑時間(機關為毫秒 ms),适用于連接配接到遠端伺服器 |
connectTimeout | 10000 | 連接配接逾時,機關為毫秒(ms) |
receiveTimeout | 10000 | 接收逾時,機關為毫秒(ms) |
sendTimeout | 10000 | 發送逾時,機關為毫秒(ms) |
encoding | utf-8 | 字元串字元集 |
retry | 協定發生錯誤時,重試執行的次數 | |
ssl | false | 啟用加密傳輸 |
name | <empty> | 連接配接名,使用 CLIENT LIST 指令檢視 |
prefix | <empty> | 前辍,所有方法都會附帶此前辍,cli.Set(prefix + "key", 111); |
IPv6: [fe80::b164:55b3:4b4f:7ce6%15]:6379
//FreeRedis.DistributedCache
//services.AddSingleton<IDistributedCache>(new FreeRedis.DistributedCache(cli));
Master-Slave (讀寫分離)
public static RedisClient cli = new RedisClient(
"127.0.0.1:6379,password=123,defaultDatabase=13",
"127.0.0.1:6380,password=123,defaultDatabase=13",
"127.0.0.1:6381,password=123,defaultDatabase=13"
);
var value = cli.Get("key1");
寫入時連接配接 127.0.0.1:6379,讀取時随機連接配接 6380 6381
Redis Sentinel (哨兵高可用)
public static RedisClient cli = new RedisClient(
"mymaster,password=123",
new [] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" },
true //是否讀寫分離
);
Redis Cluster (叢集)
假如你有一個 Redis Cluster 叢集,其中有三個主節點(7001-7003)、三個從節點(7004-7006),則連接配接此叢集的代碼:
public static RedisClient cli = new RedisClient(
new ConnectionStringBuilder[] { "192.168.0.2:7001", "192.168.0.2:7002", "192.168.0.2:7003" }
);
Client-side-cahing (本地緩存)
服務端要求 6.0 及以上版本
cli.UseClientSideCaching(new ClientSideCachingOptions
{
//本地緩存的容量
Capacity = 3,
//過濾哪些鍵能被本地緩存
KeyFilter = key => key.StartsWith("Interceptor"),
//檢查長期未使用的緩存
CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(2)
});
Subscribe (訂閱)
using (cli.Subscribe("abc", ondata)) //wait .Dispose()
{
Console.ReadKey();
}
void ondata(string channel, string data) =>
Console.WriteLine($"{channel} -> {data}");
xadd + xreadgroup:
using (cli.SubscribeStream("stream_key", ondata)) //wait .Dispose()
{
Console.ReadKey();
}
void ondata(Dictionary<string, string> streamValue) =>
Console.WriteLine(JsonConvert.SerializeObject(streamValue));
// NoAck xpending
cli.XPending("stream_key", "FreeRedis__group", "-", "+", 10);
lpush + blpop:
using (cli.SubscribeList("list_key", ondata)) //wait .Dispose()
{
Console.ReadKey();
}
void ondata(string listValue) =>
Console.WriteLine(listValue);
Scripting (腳本)
var r1 = cli.Eval("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
new[] { "key1", "key2" }, "first", "second") as object[];
var r2 = cli.Eval("return {1,2,{3,'Hello World!'}}") as object[];
cli.Eval("return redis.call('set',KEYS[1],'bar')",
new[] { Guid.NewGuid().ToString() })
Pipeline (管道)
using (var pipe = cli.StartPipe())
{
pipe.IncrBy("key1", 10);
pipe.Set("key2", );
pipe.Get("key1");
object[] ret = pipe.EndPipe();
Console.WriteLine(ret[0] + ", " + ret[2]);
}
Transaction (事務)
using (var tran = cli.Multi())
{
tran.IncrBy("key1", 10);
tran.Set("key2", );
tran.Get("key1");
object[] ret = tran.Exec();
Console.WriteLine(ret[0] + ", " + ret[2]);
}
GetDatabase (切庫)
using (var db = cli.GetDatabase(10))
{
db.Set("key1", 10);
var val1 = db.Get("key1");
}
Scan (掃描)
支援叢集模式
foreach (var keys in cli.Scan("*", 10, ))
{
Console.WriteLine(string.Join(", ", keys));
}
項目位址
項目位址:https://github.com/2881099/FreeRedis