repo_id stringlengths 6 101 | size int64 367 5.14M | file_path stringlengths 2 269 | content stringlengths 367 5.14M |
|---|---|---|---|
2881099/FreeRedis | 20,770 | test/Unit/FreeRedis.Tests/RedisClientTests/StringsTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests
{
public class StringsTests : TestBase
{
[Fact]
public void Append()
{
var key = "TestAppend_null";
cli.Set(key, String);
cli.Append(key, Null);
Assert.Equal(cli.Get(key), String);
key = "TestAppend_string";
cli.Set(key, String);
cli.Append(key, String);
Assert.Equal(cli.Get(key), String + String);
var ms = new MemoryStream();
cli.Get(key, ms);
Assert.Equal(Encoding.UTF8.GetString(ms.ToArray()), String + String);
ms.Close();
key = "TestAppend_bytes";
cli.Set(key, Bytes);
cli.Append(key, Bytes);
Assert.Equal(Convert.ToBase64String(cli.Get<byte[]>(key)), Convert.ToBase64String(Bytes.Concat(Bytes).ToArray()));
}
[Fact]
public void BitCount()
{
cli.Del("TestBitCount");
var key = "TestBitCount";
cli.SetBit(key, 100, true);
cli.SetBit(key, 90, true);
cli.SetBit(key, 80, true);
Assert.Equal(3, cli.BitCount(key, 0, 101));
Assert.Equal(3, cli.BitCount(key, 0, 100));
Assert.Equal(3, cli.BitCount(key, 0, 99));
Assert.Equal(3, cli.BitCount(key, 0, 60));
}
[Fact]
public void BitOp()
{
cli.Del("BitOp1", "BitOp2");
cli.SetBit("BitOp1", 100, true);
cli.SetBit("BitOp2", 100, true);
var r1 = cli.BitOp(BitOpOperation.and, "BitOp3", "BitOp1", "BitOp2");
}
[Fact]
public void BitPos()
{
cli.Del("BitPos1");
cli.SetBit("BitPos1", 100, true);
Assert.Equal(100, cli.BitPos("BitPos1", true));
Assert.Equal(-1, cli.BitPos("BitPos1", true, 1, 100));
}
[Fact]
public void Decr()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(-1, cli.Decr(key));
}
[Fact]
public void DecrBy()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(-10, cli.DecrBy(key, 10));
}
[Fact]
public void Get()
{
var key = "TestGet_null";
cli.Set(key, Null);
Assert.Equal((cli.Get(key))?.ToString() ?? "", Null?.ToString() ?? "");
key = "TestGet_string";
cli.Set(key, String);
Assert.Equal(cli.Get(key), String);
key = "TestGet_bytes";
cli.Set(key, Bytes);
Assert.Equal(cli.Get<byte[]>(key), Bytes);
key = "TestGet_class";
cli.Set(key, Class);
Assert.Equal(JsonConvert.SerializeObject(cli.Get<TestClass>(key)), JsonConvert.SerializeObject(Class));
key = "TestGet_classArray";
cli.Set(key, new[] { Class, Class });
Assert.Equal(2, cli.Get<TestClass[]>(key)?.Length);
Assert.Equal(JsonConvert.SerializeObject(cli.Get<TestClass[]>(key)?.First()), JsonConvert.SerializeObject(Class));
Assert.Equal(JsonConvert.SerializeObject(cli.Get<TestClass[]>(key)?.Last()), JsonConvert.SerializeObject(Class));
}
[Fact]
public void GetBit()
{
cli.Del("GetBit1");
cli.SetBit("GetBit1", 100, true);
Assert.False(cli.GetBit("GetBit1", 10));
Assert.True(cli.GetBit("GetBit1", 100));
}
[Fact]
public void GetRange()
{
var key = "TestGetRange_null";
cli.Set(key, Null);
Assert.Equal("", cli.GetRange(key, 10, 20));
key = "TestGetRange_string";
cli.Set(key, "abcdefg");
Assert.Equal("cde", cli.GetRange(key, 2, 4));
Assert.Equal("abcdefg", cli.GetRange(key, 0, -1));
key = "TestGetRange_bytes";
cli.Set(key, Bytes);
Assert.Equal(Bytes.AsSpan(2, 3).ToArray(), cli.GetRange<byte[]>(key, 2, 4));
Assert.Equal(Bytes, cli.GetRange<byte[]>(key, 0, -1));
}
[Fact]
public void GetSet()
{
cli.Del("GetSet1");
Assert.Null(cli.GetSet("GetSet1", "123456"));
Assert.Equal("123456", cli.GetSet("GetSet1", "123456789"));
}
[Fact]
public void Incr()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(1, cli.Incr(key));
}
[Fact]
public void IncrBy()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(10, cli.IncrBy(key, 10));
}
[Fact]
public void IncrByFloat()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(10.1m, cli.IncrByFloat(key, 10.1m));
}
[Fact]
public void MGet()
{
cli.Set("TestMGet_null1", Null);
cli.Set("TestMGet_string1", String);
cli.Set("TestMGet_bytes1", Bytes);
cli.Set("TestMGet_class1", Class);
cli.Set("TestMGet_null2", Null);
cli.Set("TestMGet_string2", String);
cli.Set("TestMGet_bytes2", Bytes);
cli.Set("TestMGet_class2", Class);
cli.Set("TestMGet_null3", Null);
cli.Set("TestMGet_string3", String);
cli.Set("TestMGet_bytes3", Bytes);
cli.Set("TestMGet_class3", Class);
Assert.Equal(4, cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1").Length);
Assert.Equal("", cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[0]);
Assert.Equal(String, cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[1]);
Assert.Equal(Encoding.UTF8.GetString(Bytes), cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[2]);
Assert.Equal(JsonConvert.SerializeObject(Class), cli.MGet("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[3]);
Assert.Equal(4, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1").Length);
Assert.Equal(new byte[0], cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[0]);
Assert.Equal(Encoding.UTF8.GetBytes(String), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[1]);
Assert.Equal(Bytes, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[2]);
Assert.Equal(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Class)), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[3]);
Assert.Equal(3, cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3").Length);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3")[0]));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3")[1]));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3")[2]));
}
[Fact]
public void MSet()
{
cli.Del("TestMSet_null1", "TestMSet_string1", "TestMSet_bytes1", "TestMSet_class1");
cli.MSet(new Dictionary<string, object> { ["TestMSet_null1"] = Null, ["TestMSet_string1"] = String, ["TestMSet_bytes1"] = Bytes, ["TestMSet_class1"] = Class });
Assert.Equal("", cli.Get("TestMSet_null1"));
Assert.Equal(String, cli.Get("TestMSet_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSet_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSet_class1")));
cli.Del("TestMSet_null1", "TestMSet_string1", "TestMSet_bytes1", "TestMSet_class1");
cli.MSet("TestMSet_null1", Null, "TestMSet_string1", String, "TestMSet_bytes1", Bytes, "TestMSet_class1", Class);
Assert.Equal("", cli.Get("TestMSet_null1"));
Assert.Equal(String, cli.Get("TestMSet_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSet_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSet_class1")));
}
[Fact]
public void MSetNx()
{
cli.Del("TestMSetNx_null", "TestMSetNx_string", "TestMSetNx_bytes", "TestMSetNx_class", "abctest",
"TestMSetNx_null1", "TestMSetNx_string1", "TestMSetNx_bytes1", "TestMSetNx_class1");
Assert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_null"] = Null }));
Assert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_null"] = Null }));
Assert.Equal("", cli.Get("TestMSetNx_null"));
Assert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_string"] = String }));
Assert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_string"] = String }));
Assert.Equal(String, cli.Get("TestMSetNx_string"));
Assert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_bytes"] = Bytes }));
Assert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_bytes"] = Bytes }));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes"));
Assert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_class"] = Class }));
Assert.False(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_class"] = Class }));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSetNx_class")));
cli.Set("abctest", 1);
Assert.False(cli.MSetNx(new Dictionary<string, object> { ["abctest"] = 2, ["TestMSetNx_null1"] = Null, ["TestMSetNx_string1"] = String, ["TestMSetNx_bytes1"] = Bytes, ["TestMSetNx_class1"] = Class }));
Assert.True(cli.MSetNx(new Dictionary<string, object> { ["TestMSetNx_null1"] = Null, ["TestMSetNx_string1"] = String, ["TestMSetNx_bytes1"] = Bytes, ["TestMSetNx_class1"] = Class }));
Assert.Equal(1, cli.Get<int>("abctest"));
Assert.Equal("", cli.Get("TestMSetNx_null1"));
Assert.Equal(String, cli.Get("TestMSetNx_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSetNx_class1")));
cli.Del("TestMSetNx_null", "TestMSetNx_string", "TestMSetNx_bytes", "TestMSetNx_class");
cli.MSetNx("TestMSetNx_null1", Null, "TestMSetNx_string1", String, "TestMSetNx_bytes1", Bytes, "TestMSetNx_class1", Class);
Assert.Equal("", cli.Get("TestMSetNx_null1"));
Assert.Equal(String, cli.Get("TestMSetNx_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSetNx_class1")));
}
[Fact]
public void PSetNx()
{
cli.PSetEx("TestSetNx_null", 10000, Null);
Assert.Equal("", cli.Get("TestSetNx_null"));
cli.PSetEx("TestSetNx_string", 10000, String);
Assert.Equal(String, cli.Get("TestSetNx_string"));
cli.PSetEx("TestSetNx_bytes", 10000, Bytes);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));
cli.PSetEx("TestSetNx_class", 10000, Class);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetNx_class")));
}
[Fact]
public void Set()
{
cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
cli.Set("TestSet_null", Null);
Assert.Equal("", cli.Get("TestSet_null"));
cli.Set("TestSet_string", String);
Assert.Equal(String, cli.Get("TestSet_string"));
cli.Set("TestSet_bytes", Bytes);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));
cli.Set("TestSet_class", Class);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSet_class")));
cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
cli.Set("TestSet_null", Null, 10);
Assert.Equal("", cli.Get("TestSet_null"));
cli.Set("TestSet_string", String, 10);
Assert.Equal(String, cli.Get("TestSet_string"));
cli.Set("TestSet_bytes", Bytes, 10);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));
cli.Set("TestSet_class", Class, 10);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSet_class")));
cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
cli.Set("TestSet_null", Null, true);
Assert.Equal("", cli.Get("TestSet_null"));
cli.Set("TestSet_string", String, true);
Assert.Equal(String, cli.Get("TestSet_string"));
cli.Set("TestSet_bytes", Bytes, true);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));
cli.Set("TestSet_class", Class, true);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSet_class")));
}
[Fact]
public void SetNx()
{
cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
Assert.True(cli.SetNx("TestSetNx_null", Null));
Assert.False(cli.SetNx("TestSetNx_null", Null));
Assert.Equal("", cli.Get("TestSetNx_null"));
Assert.True(cli.SetNx("TestSetNx_string", String));
Assert.False(cli.SetNx("TestSetNx_string", String));
Assert.Equal(String, cli.Get("TestSetNx_string"));
Assert.True(cli.SetNx("TestSetNx_bytes", Bytes));
Assert.False(cli.SetNx("TestSetNx_bytes", Bytes));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));
Assert.True(cli.SetNx("TestSetNx_class", Class));
Assert.False(cli.SetNx("TestSetNx_class", Class));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetNx_class")));
cli.Del("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
Assert.True(cli.SetNx("TestSetNx_null", Null, 10));
Assert.False(cli.SetNx("TestSetNx_null", Null, 10));
Assert.Equal("", cli.Get("TestSetNx_null"));
Assert.True(cli.SetNx("TestSetNx_string", String, 10));
Assert.False(cli.SetNx("TestSetNx_string", String, 10));
Assert.Equal(String, cli.Get("TestSetNx_string"));
Assert.True(cli.SetNx("TestSetNx_bytes", Bytes, 10));
Assert.False(cli.SetNx("TestSetNx_bytes", Bytes, 10));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));
Assert.True(cli.SetNx("TestSetNx_class", Class, 10));
Assert.False(cli.SetNx("TestSetNx_class", Class, 10));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetNx_class")));
}
[Fact]
public void SetXx()
{
cli.Del("TestSetXx_null");
Assert.False(cli.SetXx("TestSetXx_null", Null, 10));
cli.Set("TestSetXx_null", 1, true);
Assert.True(cli.SetXx("TestSetXx_null", Null, 10));
Assert.Equal("", cli.Get("TestSetXx_null"));
cli.Del("TestSetXx_string");
Assert.False(cli.SetXx("TestSetXx_string", String, 10));
cli.Set("TestSetXx_string", 1, true);
Assert.True(cli.SetXx("TestSetXx_string", String, 10));
Assert.Equal(String, cli.Get("TestSetXx_string"));
cli.Del("TestSetXx_bytes");
Assert.False(cli.SetXx("TestSetXx_bytes", Bytes, 10));
cli.Set("TestSetXx_bytes", 1, true);
Assert.True(cli.SetXx("TestSetXx_bytes", Bytes, 10));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetXx_bytes"));
cli.Del("TestSetXx_class");
Assert.False(cli.SetXx("TestSetXx_class", Class, 10));
cli.Set("TestSetXx_class", 1, true);
Assert.True(cli.SetXx("TestSetXx_class", Class, 10));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetXx_class")));
cli.Del("TestSetXx_null");
Assert.False(cli.SetXx("TestSetXx_null", Null, true));
cli.Set("TestSetXx_null", 1, true);
Assert.True(cli.SetXx("TestSetXx_null", Null, true));
Assert.Equal("", cli.Get("TestSetXx_null"));
cli.Del("TestSetXx_string");
Assert.False(cli.SetXx("TestSetXx_string", String, true));
cli.Set("TestSetXx_string", 1, true);
Assert.True(cli.SetXx("TestSetXx_string", String, true));
Assert.Equal(String, cli.Get("TestSetXx_string"));
cli.Del("TestSetXx_bytes");
Assert.False(cli.SetXx("TestSetXx_bytes", Bytes, true));
cli.Set("TestSetXx_bytes", 1, true);
Assert.True(cli.SetXx("TestSetXx_bytes", Bytes, true));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetXx_bytes"));
cli.Del("TestSetXx_class");
Assert.False(cli.SetXx("TestSetXx_class", Class, true));
cli.Set("TestSetXx_class", 1, true);
Assert.True(cli.SetXx("TestSetXx_class", Class, true));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetXx_class")));
}
[Fact]
public void SetBit()
{
cli.Del("SetBit1");
cli.SetBit("SetBit1", 100, true);
Assert.False(cli.GetBit("SetBit1", 10));
Assert.True(cli.GetBit("SetBit1", 100));
}
[Fact]
public void SetEx()
{
cli.Del("TestSetEx_null", "TestSetEx_string", "TestSetEx_bytes", "TestSetEx_class");
cli.SetEx("TestSetEx_null", 10, Null);
Assert.Equal("", cli.Get("TestSetEx_null"));
cli.SetEx("TestSetEx_string", 10, String);
Assert.Equal(String, cli.Get("TestSetEx_string"));
cli.SetEx("TestSetEx_bytes", 10, Bytes);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetEx_bytes"));
cli.SetEx("TestSetEx_class", 10, Class);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetEx_class")));
}
[Fact]
public void SetRange()
{
var key = "TestSetRange_null";
cli.Set(key, Null);
cli.SetRange(key, 10, String);
Assert.Equal(String, cli.GetRange(key, 10, -1));
key = "TestSetRange_string";
cli.Set(key, "abcdefg");
cli.SetRange(key, 2, "yyy");
Assert.Equal("yyy", cli.GetRange(key, 2, 4));
key = "TestSetRange_bytes";
cli.Set(key, Bytes);
cli.SetRange(key, 2, Bytes);
Assert.Equal(Bytes, cli.GetRange<byte[]>(key, 2, Bytes.Length + 2));
}
[Fact]
public void StrLen()
{
var key = "TestStrLen_null";
cli.Set(key, Null);
Assert.Equal(0, cli.StrLen(key));
key = "TestStrLen_string";
cli.Set(key, "abcdefg");
Assert.Equal(7, cli.StrLen(key));
key = "TestStrLen_string";
cli.Set(key, String);
Assert.Equal(15, cli.StrLen(key));
key = "TestStrLen_bytes";
cli.Set(key, Bytes);
Assert.Equal(Bytes.Length, cli.StrLen(key));
}
}
}
|
2881099/FreeRedis | 27,242 | test/Unit/FreeRedis.Tests/RedisClientTests/SortedSetsTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests
{
public class SortedSetsTests : TestBase
{
[Fact]
public void BZPopMin()
{
var key1 = "BZPopMin1" + Guid.NewGuid();
cli.Del(key1);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
var r1 = cli.BZPopMin(key1, 1);
Assert.Equal("member1", r1.member);
Assert.Equal(100.991m, r1.score);
var r2 = cli.BZPopMin(key1, 1);
Assert.Equal("member2", r2.member);
Assert.Equal(100.992m, r2.score);
var r3 = cli.BZPopMin(key1, 1);
Assert.Null(r3);
var key2 = "BZPopMin2" + Guid.NewGuid();
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
cli.ZAdd(key2, 100.991m, "member11");
cli.ZAdd(key2, 100.992m, "member22");
var r4 = cli.BZPopMin(new[] { key1, key2 }, 1);
Assert.Equal(key1, r4.key);
Assert.Equal("member1", r4.value.member);
Assert.Equal(100.991m, r4.value.score);
var r5 = cli.BZPopMin(new[] { key1, key2 }, 1);
Assert.Equal(key1, r5.key);
Assert.Equal("member2", r5.value.member);
Assert.Equal(100.992m, r5.value.score);
var r6 = cli.BZPopMin(new[] { key1, key2 }, 1);
Assert.Equal(key2, r6.key);
Assert.Equal("member11", r6.value.member);
Assert.Equal(100.991m, r6.value.score);
var r7 = cli.BZPopMin(new[] { key1, key2 }, 1);
Assert.Equal(key2, r7.key);
Assert.Equal("member22", r7.value.member);
Assert.Equal(100.992m, r7.value.score);
var r8 = cli.ZPopMin(key1);
Assert.Null(r8);
}
[Fact]
public void BZPopMax()
{
var key1 = "BZPopMax1" + Guid.NewGuid();
cli.Del(key1);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
var r2 = cli.BZPopMax(key1, 1);
Assert.Equal("member2", r2.member);
Assert.Equal(100.992m, r2.score);
var r1 = cli.BZPopMax(key1, 1);
Assert.Equal("member1", r1.member);
Assert.Equal(100.991m, r1.score);
var r3 = cli.BZPopMax(key1, 1);
Assert.Null(r3);
var key2 = "BZPopMax2" + Guid.NewGuid();
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
cli.ZAdd(key2, 100.991m, "member11");
cli.ZAdd(key2, 100.992m, "member22");
var r4 = cli.BZPopMax(new[] { key1, key2 }, 1);
Assert.Equal(key1, r4.key);
Assert.Equal("member2", r4.value.member);
Assert.Equal(100.992m, r4.value.score);
var r5 = cli.BZPopMax(new[] { key1, key2 }, 1);
Assert.Equal(key1, r5.key);
Assert.Equal("member1", r5.value.member);
Assert.Equal(100.991m, r5.value.score);
var r6 = cli.BZPopMax(new[] { key1, key2 }, 1);
Assert.Equal(key2, r6.key);
Assert.Equal("member22", r6.value.member);
Assert.Equal(100.992m, r6.value.score);
var r7 = cli.BZPopMax(new[] { key1, key2 }, 1);
Assert.Equal(key2, r7.key);
Assert.Equal("member11", r7.value.member);
Assert.Equal(100.991m, r7.value.score);
var r8 = cli.ZPopMin(key1);
Assert.Null(r8);
}
[Fact]
public void ZAdd()
{
var key1 = "ZAdd1" + Guid.NewGuid();
cli.Del(key1);
Assert.Equal(1, cli.ZAdd(key1, 100.991m, "member1"));
Assert.Equal(1, cli.ZAdd(key1, 100.992m, "member2"));
Assert.Equal(2, cli.ZAdd(key1, new[] {
new ZMember("member3", 100.993m),
new ZMember("member4", 100.994m)
}));
Assert.Equal(2, cli.ZAdd(key1, 100.995m, "member5", 100.996m, "member6"));
Assert.Equal(3, cli.ZAdd(key1, 100.997m, "member7", 100.998m, "member8", 100.999m, "member9"));
Assert.Equal(2, cli.ZAdd(key1, new[] {
new ZMember("member91", 100.9991m),
new ZMember("member92", 100.9992m)
}, null, false));
Assert.Equal(2, cli.ZAdd(key1, new[] {
new ZMember("member93", 100.999m),
new ZMember("member94", 100.998m)
}, null, true));
Assert.Equal(13, cli.ZCard(key1));
//redis v6.2
//var r16 = cli.ZAdd(key1, new[] {
// new ZMember("member91", 100.9991m),
// new ZMember("member92", 100.9992m)
//}, ZAddThan.gt, false);
//var r17 = cli.ZAdd(key1, new[] {
// new ZMember("member93", 100.999m),
// new ZMember("member94", 100.998m)
//}, ZAddThan.lt, false);
//var r18 = cli.ZAdd(key1, new[] {
// new ZMember("member95", 100.9991m),
// new ZMember("member96", 100.9992m)
//}, ZAddThan.gt, true);
//var r19 = cli.ZAdd(key1, new[] {
// new ZMember("member97", 100.999m),
// new ZMember("member98", 100.998m)
//}, ZAddThan.lt, true);
}
[Fact]
public void ZAddNx()
{
var key1 = "ZAddNx1" + Guid.NewGuid();
cli.Del(key1);
Assert.Equal(1, cli.ZAddNx(key1, 100.991m, "member1"));
Assert.Equal(1, cli.ZAddNx(key1, 100.992m, "member2"));
Assert.Equal(2, cli.ZAddNx(key1, new[] {
new ZMember("member3", 100.993m),
new ZMember("member4", 100.994m)
}));
Assert.Equal(2, cli.ZAddNx(key1, 100.995m, "member5", 100.996m, "member6"));
Assert.Equal(3, cli.ZAddNx(key1, 100.997m, "member7", 100.998m, "member8", 100.999m, "member9"));
Assert.Equal(2, cli.ZAddNx(key1, new[] {
new ZMember("member91", 100.9991m),
new ZMember("member92", 100.9992m)
}, null, false));
Assert.Equal(2, cli.ZAddNx(key1, new[] {
new ZMember("member93", 100.999m),
new ZMember("member94", 100.998m)
}, null, true));
Assert.Equal(13, cli.ZCard(key1));
Assert.Equal(0, cli.ZAddNx(key1, 100.991m, "member1"));
Assert.Equal(0, cli.ZAddNx(key1, 100.992m, "member2"));
Assert.Equal(0, cli.ZAddNx(key1, new[] {
new ZMember("member3", 100.993m),
new ZMember("member4", 100.994m)
}));
Assert.Equal(0, cli.ZAddNx(key1, 100.995m, "member5", 100.996m, "member6"));
Assert.Equal(0, cli.ZAddNx(key1, 100.997m, "member7", 100.998m, "member8", 100.999m, "member9"));
Assert.Equal(0, cli.ZAddNx(key1, new[] {
new ZMember("member91", 100.9991m),
new ZMember("member92", 100.9992m)
}, null, false));
Assert.Equal(0, cli.ZAddNx(key1, new[] {
new ZMember("member93", 100.999m),
new ZMember("member94", 100.998m)
}, null, true));
//redis v6.2
//var r16 = cli.ZAddNx(key1, new[] {
// new ZMember("member91", 100.9991m),
// new ZMember("member92", 100.9992m)
//}, ZAddNxThan.gt, false);
//var r17 = cli.ZAddNx(key1, new[] {
// new ZMember("member93", 100.999m),
// new ZMember("member94", 100.998m)
//}, ZAddNxThan.lt, false);
//var r18 = cli.ZAddNx(key1, new[] {
// new ZMember("member95", 100.9991m),
// new ZMember("member96", 100.9992m)
//}, ZAddNxThan.gt, true);
//var r19 = cli.ZAddNx(key1, new[] {
// new ZMember("member97", 100.999m),
// new ZMember("member98", 100.998m)
//}, ZAddNxThan.lt, true);
}
[Fact]
public void ZAddXx()
{
var key1 = "ZAddXx1" + Guid.NewGuid();
cli.Del(key1);
Assert.Equal(1, cli.ZAdd(key1, 100.991m, "member1"));
Assert.Equal(1, cli.ZAdd(key1, 100.992m, "member2"));
Assert.Equal(2, cli.ZAdd(key1, new[] {
new ZMember("member3", 100.993m),
new ZMember("member4", 100.994m)
}));
Assert.Equal(2, cli.ZAdd(key1, 100.995m, "member5", 100.996m, "member6"));
Assert.Equal(3, cli.ZAdd(key1, 100.997m, "member7", 100.998m, "member8", 100.999m, "member9"));
Assert.Equal(2, cli.ZAdd(key1, new[] {
new ZMember("member91", 100.9991m),
new ZMember("member92", 100.9992m)
}, null, false));
Assert.Equal(2, cli.ZAdd(key1, new[] {
new ZMember("member93", 100.999m),
new ZMember("member94", 100.998m)
}, null, false));
Assert.Equal(13, cli.ZCard(key1));
Assert.Equal(0, cli.ZAddXx(key1, 100.1991m, "member1"));
Assert.Equal(0, cli.ZAddXx(key1, 100.1992m, "member2"));
Assert.Equal(0, cli.ZAddXx(key1, new[] {
new ZMember("member3", 100.1993m),
new ZMember("member4", 100.1994m)
}));
Assert.Equal(0, cli.ZAddXx(key1, 100.995m, "member5", 100.996m, "member6"));
Assert.Equal(0, cli.ZAddXx(key1, 100.997m, "member7", 100.998m, "member8", 100.999m, "member9"));
Assert.Equal(0, cli.ZAddXx(key1, new[] {
new ZMember("member91", 100.19991m),
new ZMember("member92", 100.19992m)
}, null, false));
Assert.Equal(2, cli.ZAddXx(key1, new[] {
new ZMember("member93", 100.1999m),
new ZMember("member94", 100.1998m)
}, null, true));
//redis v6.2
//var r16 = cli.ZAddXx(key1, new[] {
// new ZMember("member91", 100.9991m),
// new ZMember("member92", 100.9992m)
//}, ZAddXxThan.gt, false);
//var r17 = cli.ZAddXx(key1, new[] {
// new ZMember("member93", 100.999m),
// new ZMember("member94", 100.998m)
//}, ZAddXxThan.lt, false);
//var r18 = cli.ZAddXx(key1, new[] {
// new ZMember("member95", 100.9991m),
// new ZMember("member96", 100.9992m)
//}, ZAddXxThan.gt, true);
//var r19 = cli.ZAddXx(key1, new[] {
// new ZMember("member97", 100.999m),
// new ZMember("member98", 100.998m)
//}, ZAddXxThan.lt, true);
}
[Fact]
public void ZCard()
{
var key1 = "ZCard1";
cli.Del(key1);
Assert.Equal(0, cli.ZCard(key1));
Assert.Equal(1, cli.ZAdd(key1, 100.991m, "member1"));
Assert.Equal(0, cli.ZAdd(key1, 100.991m, "member1"));
Assert.Equal(1, cli.ZCard(key1));
}
[Fact]
public void ZCount()
{
var key1 = "ZCount1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(5, cli.ZCount(key1, 0, 12));
Assert.Equal(5, cli.ZCount(key1, 0, 13));
Assert.Equal(5, cli.ZCount(key1, 1, 12));
Assert.Equal(5, cli.ZCount(key1, 1, 13));
Assert.Equal(2, cli.ZCount(key1, 10, 11));
Assert.Equal(5, cli.ZCount(key1, "-inf", "+inf"));
}
[Fact]
public void ZIncrBy()
{
var key1 = "ZIncrBy1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1");
Assert.Equal(1, cli.ZScore(key1, "m1"));
Assert.Equal(3, cli.ZIncrBy(key1, 2, "m1"));
Assert.Equal(3, cli.ZScore(key1, "m1"));
}
[Fact]
public void ZLexCount()
{
var key1 = "ZZLexCount1";
cli.Del(key1);
cli.ZAdd(key1, 0, "a", 0, "b", 0, "c", 0, "d", 0, "e");
cli.ZAdd(key1, 0, "f", 0, "g", 0, "c", 0, "d", 0, "e");
Assert.Equal(7, cli.ZLexCount(key1, "-", "+"));
Assert.Equal(5, cli.ZLexCount(key1, "[b", "[f"));
}
[Fact]
public void ZPopMin()
{
var key1 = "ZPopMin1" + Guid.NewGuid();
cli.Del(key1);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
var r1 = cli.ZPopMin(key1);
Assert.Equal("member1", r1.member);
Assert.Equal(100.991m, r1.score);
var r2 = cli.ZPopMin(key1);
Assert.Equal("member2", r2.member);
Assert.Equal(100.992m, r2.score);
var r3 = cli.ZPopMin(key1);
Assert.Null(r3);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
cli.ZAdd(key1, 100.995m, "member3");
var r4 = cli.ZPopMin(key1, 1);
Assert.Single(r4);
Assert.Equal("member1", r4[0].member);
Assert.Equal(100.991m, r4[0].score);
var r5 = cli.ZPopMin(key1, 2);
Assert.Equal(2, r5.Length);
Assert.Equal("member2", r5[0].member);
Assert.Equal(100.992m, r5[0].score);
Assert.Equal("member3", r5[1].member);
Assert.Equal(100.995m, r5[1].score);
var r6 = cli.ZPopMin(key1);
Assert.Null(r6);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
cli.ZAdd(key1, 100.995m, "member3");
var r7 = cli.ZPopMin(key1, 4);
Assert.Equal(3, r7.Length);
Assert.Equal("member1", r7[0].member);
Assert.Equal(100.991m, r7[0].score);
Assert.Equal("member2", r7[1].member);
Assert.Equal(100.992m, r7[1].score);
Assert.Equal("member3", r7[2].member);
Assert.Equal(100.995m, r7[2].score);
var r8 = cli.ZPopMin(key1);
Assert.Null(r8);
}
[Fact]
public void ZPopMax()
{
var key1 = "ZPopMax1" + Guid.NewGuid();
cli.Del(key1);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
var r1 = cli.ZPopMax(key1);
Assert.Equal("member2", r1.member);
Assert.Equal(100.992m, r1.score);
var r2 = cli.ZPopMax(key1);
Assert.Equal("member1", r2.member);
Assert.Equal(100.991m, r2.score);
var r3 = cli.ZPopMax(key1);
Assert.Null(r3);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
cli.ZAdd(key1, 100.995m, "member3");
var r4 = cli.ZPopMax(key1, 1);
Assert.Single(r4);
Assert.Equal("member3", r4[0].member);
Assert.Equal(100.995m, r4[0].score);
var r5 = cli.ZPopMax(key1, 2);
Assert.Equal(2, r5.Length);
Assert.Equal("member2", r5[0].member);
Assert.Equal(100.992m, r5[0].score);
Assert.Equal("member1", r5[1].member);
Assert.Equal(100.991m, r5[1].score);
var r6 = cli.ZPopMax(key1);
Assert.Null(r6);
cli.ZAdd(key1, 100.991m, "member1");
cli.ZAdd(key1, 100.992m, "member2");
cli.ZAdd(key1, 100.995m, "member3");
var r7 = cli.ZPopMax(key1, 4);
Assert.Equal(3, r7.Length);
Assert.Equal("member3", r7[0].member);
Assert.Equal(100.995m, r7[0].score);
Assert.Equal("member2", r7[1].member);
Assert.Equal(100.992m, r7[1].score);
Assert.Equal("member1", r7[2].member);
Assert.Equal(100.991m, r7[2].score);
var r8 = cli.ZPopMax(key1);
Assert.Null(r8);
}
[Fact]
public void ZRange()
{
var key1 = "ZRange1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRange(key1, 0, 12);
Assert.Equal(5, r1.Length);
Assert.Equal("m1", r1[0]);
Assert.Equal("m2", r1[1]);
Assert.Equal("m10", r1[2]);
Assert.Equal("m11", r1[3]);
Assert.Equal("m12", r1[4]);
var r2 = cli.ZRange(key1, 2, 3);
Assert.Equal(2, r2.Length);
Assert.Equal("m10", r2[0]);
Assert.Equal("m11", r2[1]);
}
[Fact]
public void ZRangeWithScores()
{
var key1 = "ZRangeWithScores1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRangeWithScores(key1, 0, 12);
Assert.Equal(5, r1.Length);
Assert.Equal("m1", r1[0].member);
Assert.Equal("m2", r1[1].member);
Assert.Equal("m10", r1[2].member);
Assert.Equal("m11", r1[3].member);
Assert.Equal("m12", r1[4].member);
Assert.Equal(1, r1[0].score);
Assert.Equal(2, r1[1].score);
Assert.Equal(10, r1[2].score);
Assert.Equal(11, r1[3].score);
Assert.Equal(12, r1[4].score);
var r2 = cli.ZRangeWithScores(key1, 2, 3);
Assert.Equal(2, r2.Length);
Assert.Equal("m10", r2[0].member);
Assert.Equal("m11", r2[1].member);
Assert.Equal(10, r2[0].score);
Assert.Equal(11, r2[1].score);
}
[Fact]
public void ZRangeByLex()
{
var key1 = "ZRangeByLex1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRangeByLex(key1, "-", "+");
Assert.Equal(5, r1.Length);
Assert.Equal("m1", r1[0]);
Assert.Equal("m2", r1[1]);
Assert.Equal("m10", r1[2]);
Assert.Equal("m11", r1[3]);
Assert.Equal("m12", r1[4]);
var r2 = cli.ZRangeByLex(key1, "-", "+", 2, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m10", r2[0]);
Assert.Equal("m11", r2[1]);
}
[Fact]
public void ZRangeByScore()
{
var key1 = "ZRangeByScore1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRangeByScore(key1, "-inf", "+inf");
Assert.Equal(5, r1.Length);
Assert.Equal("m1", r1[0]);
Assert.Equal("m2", r1[1]);
Assert.Equal("m10", r1[2]);
Assert.Equal("m11", r1[3]);
Assert.Equal("m12", r1[4]);
var r2 = cli.ZRangeByScore(key1, 1, 11, 2, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m10", r2[0]);
Assert.Equal("m11", r2[1]);
}
[Fact]
public void ZRangeByScoreWithScores()
{
var key1 = "ZRangeByScoreWithScores1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRangeByScoreWithScores(key1, "-inf", "+inf");
Assert.Equal(5, r1.Length);
Assert.Equal("m1", r1[0].member);
Assert.Equal("m2", r1[1].member);
Assert.Equal("m10", r1[2].member);
Assert.Equal("m11", r1[3].member);
Assert.Equal("m12", r1[4].member);
Assert.Equal(1, r1[0].score);
Assert.Equal(2, r1[1].score);
Assert.Equal(10, r1[2].score);
Assert.Equal(11, r1[3].score);
Assert.Equal(12, r1[4].score);
var r2 = cli.ZRangeByScoreWithScores(key1, 1, 11, 2, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m10", r2[0].member);
Assert.Equal("m11", r2[1].member);
Assert.Equal(10, r2[0].score);
Assert.Equal(11, r2[1].score);
}
[Fact]
public void ZRank()
{
var key1 = "ZRank1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(2, cli.ZRank(key1, "m10"));
}
[Fact]
public void ZRem()
{
var key1 = "ZRem1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(1, cli.ZRem(key1, "m10"));
Assert.Equal(0, cli.ZRem(key1, "m10"));
Assert.Equal(2, cli.ZRem(key1, "m11", "m12"));
Assert.Equal(2, cli.ZRem(key1, "m1", "m2", "m2"));
}
[Fact]
public void ZRemRangeByLex()
{
var key1 = "ZRemRangeByLex1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(5, cli.ZRemRangeByLex(key1, "-", "+"));
}
[Fact]
public void ZRemRangeByRank()
{
var key1 = "ZRemRangeByRank1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(5, cli.ZRemRangeByRank(key1, 0, -1));
}
[Fact]
public void ZRemRangeByScore()
{
var key1 = "ZRemRangeByScore1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(5, cli.ZRemRangeByScore(key1, "-inf", "+inf"));
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(2, cli.ZRemRangeByScore(key1, 10, 11));
}
[Fact]
public void ZRevRange()
{
var key1 = "ZRevRange1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRevRange(key1, 0, 12);
Assert.Equal(5, r1.Length);
Assert.Equal("m12", r1[0]);
Assert.Equal("m11", r1[1]);
Assert.Equal("m10", r1[2]);
Assert.Equal("m2", r1[3]);
Assert.Equal("m1", r1[4]);
var r2 = cli.ZRevRange(key1, 1, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m11", r2[0]);
Assert.Equal("m10", r2[1]);
}
[Fact]
public void ZRevRangeWithScores()
{
var key1 = "ZRevRangeWithScores1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRevRangeWithScores(key1, 0, 12);
Assert.Equal(5, r1.Length);
Assert.Equal("m12", r1[0].member);
Assert.Equal("m11", r1[1].member);
Assert.Equal("m10", r1[2].member);
Assert.Equal("m2", r1[3].member);
Assert.Equal("m1", r1[4].member);
Assert.Equal(12, r1[0].score);
Assert.Equal(11, r1[1].score);
Assert.Equal(10, r1[2].score);
Assert.Equal(2, r1[3].score);
Assert.Equal(1, r1[4].score);
var r2 = cli.ZRevRangeWithScores(key1, 1, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m11", r2[0].member);
Assert.Equal("m10", r2[1].member);
Assert.Equal(11, r2[0].score);
Assert.Equal(10, r2[1].score);
}
[Fact]
public void ZRevRangeByLex()
{
var key1 = "ZRevRangeByLex1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRevRangeByLex(key1, "+", "-");
Assert.Equal(5, r1.Length);
Assert.Equal("m12", r1[0]);
Assert.Equal("m11", r1[1]);
Assert.Equal("m10", r1[2]);
Assert.Equal("m2", r1[3]);
Assert.Equal("m1", r1[4]);
var r2 = cli.ZRevRangeByLex(key1, "+", "-", 2, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m10", r2[0]);
Assert.Equal("m2", r2[1]);
}
[Fact]
public void ZRevRangeByScore()
{
var key1 = "ZRevRangeByScore1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRevRangeByScore(key1, "+inf", "-inf");
Assert.Equal(5, r1.Length);
Assert.Equal("m12", r1[0]);
Assert.Equal("m11", r1[1]);
Assert.Equal("m10", r1[2]);
Assert.Equal("m2", r1[3]);
Assert.Equal("m1", r1[4]);
var r2 = cli.ZRevRangeByScore(key1, 11, 1, 2, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m2", r2[0]);
Assert.Equal("m1", r2[1]);
}
[Fact]
public void ZRevRangeByScoreWithScores()
{
var key1 = "ZRevRangeByScoreWithScores1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
var r1 = cli.ZRevRangeByScoreWithScores(key1, "+inf", "-inf");
Assert.Equal(5, r1.Length);
Assert.Equal("m12", r1[0].member);
Assert.Equal("m11", r1[1].member);
Assert.Equal("m10", r1[2].member);
Assert.Equal("m2", r1[3].member);
Assert.Equal("m1", r1[4].member);
Assert.Equal(12, r1[0].score);
Assert.Equal(11, r1[1].score);
Assert.Equal(10, r1[2].score);
Assert.Equal(2, r1[3].score);
Assert.Equal(1, r1[4].score);
var r2 = cli.ZRevRangeByScoreWithScores(key1, 11, 1, 2, 2);
Assert.Equal(2, r2.Length);
Assert.Equal("m2", r2[0].member);
Assert.Equal("m1", r2[1].member);
Assert.Equal(2, r2[0].score);
Assert.Equal(1, r2[1].score);
}
[Fact]
public void ZRevRank()
{
var key1 = "ZRevRank1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(2, cli.ZRevRank(key1, "m10"));
}
[Fact]
public void ZScore()
{
var key1 = "ZRevRank1";
cli.Del(key1);
cli.ZAdd(key1, 1, "m1", 2, "m2", 10, "m10", 11, "m11", 12, "m12");
Assert.Equal(1, cli.ZScore(key1, "m1"));
Assert.Equal(2, cli.ZScore(key1, "m2"));
Assert.Equal(10, cli.ZScore(key1, "m10"));
Assert.Equal(11, cli.ZScore(key1, "m11"));
Assert.Equal(12, cli.ZScore(key1, "m12"));
}
}
}
|
2881099/FreeRedis | 12,016 | test/Unit/FreeRedis.Tests/RedisClientTests/ListsTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests
{
public class ListsTests : TestBase
{
[Fact]
public void BLPop()
{
Assert.Null(cli.BRPop(new[] { "TestBLPop1", "TestBLPop2" }, 1));
new Thread(() =>
{
Thread.CurrentThread.Join(500);
cli.RPush("TestBLPop1", "testv1");
}).Start();
Assert.Equal("testv1", cli.BRPop(new[] { "TestBLPop1", "TestBLPop2" }, 5)?.value);
new Thread(() =>
{
Thread.CurrentThread.Join(500);
cli.RPush("TestBLPop2", "testv2");
}).Start();
Assert.Equal("testv2", cli.BRPop(new[] { "TestBLPop1", "TestBLPop2" }, 5)?.value);
}
[Fact]
public void BRPop()
{
Assert.Null(cli.BRPop(new[] { "TestBRPop1", "TestBRPop2" }, 1));
new Thread(() =>
{
Thread.CurrentThread.Join(500);
cli.LPush("TestBRPop1", "testv1");
}).Start();
Assert.Equal("testv1", cli.BRPop(new[] { "TestBRPop1", "TestBRPop2" }, 5)?.value);
new Thread(() =>
{
cli.LPush("TestBRPop2", "testv2");
}).Start();
Assert.Equal("testv2", cli.BRPop(new[] { "TestBRPop1", "TestBRPop2" }, 5)?.value);
}
[Fact]
public void BRPopLPush()
{
}
[Fact]
public void LIndex()
{
cli.Del("TestLIndex");
Assert.Equal(8, cli.RPush("TestLIndex", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal(Class.ToString(), cli.LIndex<TestClass>("TestLIndex", 0).ToString());
Assert.Equal(Bytes, cli.LIndex<byte[]>("TestLIndex", 2));
Assert.Equal(String, cli.LIndex("TestLIndex", 4));
Assert.Equal("", cli.LIndex("TestLIndex", 6));
}
[Fact]
public void LInsert()
{
cli.Del("TestLInsertBefore", "TestLInsertAfter");
Assert.Equal(8, cli.RPush("TestLInsertBefore", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal(9, cli.LInsert("TestLInsertBefore", InsertDirection.before, Class, "TestLInsertBefore"));
Assert.Equal("TestLInsertBefore", cli.LIndex("TestLInsertBefore", 0));
Assert.Equal(Class.ToString(), cli.LIndex<TestClass>("TestLInsertBefore", 1).ToString());
Assert.Equal(8, cli.RPush("TestLInsertAfter", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal(9, cli.LInsert("TestLInsertAfter", InsertDirection.after, Class, "TestLInsertAfter"));
Assert.Equal("TestLInsertAfter", cli.LIndex("TestLInsertAfter", 1));
Assert.Equal(Class.ToString(), cli.LIndex<TestClass>("TestLInsertAfter", 0).ToString());
Assert.Equal(Class.ToString(), cli.LIndex<TestClass>("TestLInsertAfter", 2).ToString());
}
[Fact]
public void LLen()
{
cli.Del("TestLLen");
Assert.Equal(8, cli.RPush("TestLLen", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal(8, cli.LLen("TestLLen"));
cli.LTrim("TestLLen", -1, -1);
Assert.Equal(1, cli.LLen("TestLLen"));
}
[Fact]
public void LPop()
{
cli.Del("TestLPop");
Assert.Equal(8, cli.LPush("TestLPop", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal("", cli.LPop("TestLPop"));
Assert.Equal("", cli.LPop("TestLPop"));
Assert.Equal(String, cli.LPop("TestLPop"));
Assert.Equal(String, cli.LPop("TestLPop"));
Assert.Equal(Bytes, cli.LPop<byte[]>("TestLPop"));
Assert.Equal(Bytes, cli.LPop<byte[]>("TestLPop"));
Assert.Equal(Class.ToString(), cli.LPop<TestClass>("TestLPop").ToString());
Assert.Equal(Class.ToString(), cli.LPop<TestClass>("TestLPop").ToString());
}
[Fact]
public void LPos()
{
}
[Fact]
public void LPush()
{
cli.Del("TestLPush");
Assert.Equal(8, cli.LPush("TestLPush", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal(2, cli.LRange("TestLPush", 0, 1).Length);
Assert.Equal("", cli.LRange("TestLPush", 0, 1)[0]);
Assert.Equal("", cli.LRange("TestLPush", 0, 1)[1]);
Assert.Equal(2, cli.LRange("TestLPush", 2, 3).Length);
Assert.Equal(String, cli.LRange("TestLPush", 2, 3)[0]);
Assert.Equal(String, cli.LRange("TestLPush", 2, 3)[1]);
Assert.Equal(2, cli.LRange("TestLPush", 4, 5).Length);
Assert.Equal(Bytes, cli.LRange<byte[]>("TestLPush", 4, 5)[0]);
Assert.Equal(Bytes, cli.LRange<byte[]>("TestLPush", 4, 5)[1]);
Assert.Equal(2, cli.LRange("TestLPush", 6, -1).Length);
Assert.Equal(Class.ToString(), cli.LRange<TestClass>("TestLPush", 6, -1)[0].ToString());
Assert.Equal(Class.ToString(), cli.LRange<TestClass>("TestLPush", 6, -1)[1].ToString());
}
[Fact]
public void LPushX()
{
cli.Del("TestLPushX");
Assert.Equal(0, cli.LPushX("TestLPushX", Null));
Assert.Equal(0, cli.LPushX("TestLPushX", String));
Assert.Equal(0, cli.LPushX("TestLPushX", Bytes));
Assert.Equal(0, cli.LPushX("TestLPushX", Class));
Assert.Equal(1, cli.RPush("TestLPushX", Null));
Assert.Equal(2, cli.LPushX("TestLPushX", Null));
Assert.Equal(3, cli.LPushX("TestLPushX", String));
Assert.Equal(4, cli.LPushX("TestLPushX", Bytes));
Assert.Equal(5, cli.LPushX("TestLPushX", Class));
}
[Fact]
public void LRange()
{
cli.Del("TestLRange");
cli.LPush("TestLRange", Class, Class, Bytes, Bytes, String, String, Null, Null);
Assert.Equal(2, cli.LRange("TestLRange", 0, 1).Length);
Assert.Equal("", cli.LRange("TestLRange", 0, 1)[0]);
Assert.Equal("", cli.LRange("TestLRange", 0, 1)[1]);
Assert.Equal(2, cli.LRange("TestLRange", 2, 3).Length);
Assert.Equal(String, cli.LRange("TestLRange", 2, 3)[0]);
Assert.Equal(String, cli.LRange("TestLRange", 2, 3)[1]);
Assert.Equal(2, cli.LRange("TestLRange", 4, 5).Length);
Assert.Equal(Bytes, cli.LRange<byte[]>("TestLRange", 4, 5)[0]);
Assert.Equal(Bytes, cli.LRange<byte[]>("TestLRange", 4, 5)[1]);
Assert.Equal(2, cli.LRange("TestLRange", 6, -1).Length);
Assert.Equal(Class.ToString(), cli.LRange<TestClass>("TestLRange", 6, -1)[0].ToString());
Assert.Equal(Class.ToString(), cli.LRange<TestClass>("TestLRange", 6, -1)[1].ToString());
}
[Fact]
public void LRem()
{
cli.Del("TestLRem");
Assert.Equal(8, cli.LPush("TestLRem", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal(2, cli.LRem("TestLRem", 0, Class));
Assert.Equal(0, cli.LRem("TestLRem", 0, Class));
Assert.Equal(2, cli.LRem("TestLRem", 0, Bytes));
Assert.Equal(0, cli.LRem("TestLRem", 0, Bytes));
Assert.Equal(2, cli.LRem("TestLRem", 0, String));
Assert.Equal(0, cli.LRem("TestLRem", 0, String));
Assert.Equal(2, cli.LRem("TestLRem", 0, Null));
Assert.Equal(0, cli.LRem("TestLRem", 0, Null));
}
[Fact]
public void LSet()
{
cli.Del("TestLSet");
Assert.Equal(8, cli.RPush("TestLSet", Class, Class, Bytes, Bytes, String, String, Null, Null));
var now = DateTime.Now;
cli.LSet("TestLSet", -1, now);
Assert.Equal(now.ToString(), cli.LIndex<DateTime>("TestLSet", -1).ToString());
}
[Fact]
public void LTrim()
{
cli.Del("TestLTrim");
Assert.Equal(8, cli.RPush("TestLTrim", Class, Class, Bytes, Bytes, String, String, Null, Null));
cli.LTrim("TestLTrim", -1, -1);
Assert.Equal(1, cli.LLen("TestLTrim"));
Assert.Equal("", cli.LRange("TestLTrim", 0, -1)[0]);
}
[Fact]
public void RPop()
{
cli.Del("TestRPop");
Assert.Equal(8, cli.RPush("TestRPop", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal("", cli.RPop("TestRPop"));
Assert.Equal("", cli.RPop("TestRPop"));
Assert.Equal(String, cli.RPop("TestRPop"));
Assert.Equal(String, cli.RPop("TestRPop"));
Assert.Equal(Bytes, cli.RPop<byte[]>("TestRPop"));
Assert.Equal(Bytes, cli.RPop<byte[]>("TestRPop"));
Assert.Equal(Class.ToString(), cli.RPop<TestClass>("TestRPop").ToString());
Assert.Equal(Class.ToString(), cli.RPop<TestClass>("TestRPop").ToString());
}
[Fact]
public void RPopLPush()
{
cli.Del("TestRPopLPush");
Assert.Equal(8, cli.RPush("TestRPopLPush", Class, Class, Bytes, Bytes, String, String, Null, Null));
Assert.Equal("", cli.RPopLPush("TestRPopLPush", "TestRPopLPush"));
Assert.Equal("", cli.RPopLPush("TestRPopLPush", "TestRPopLPush"));
Assert.Equal(String, cli.RPopLPush("TestRPopLPush", "TestRPopLPush"));
Assert.Equal(String, cli.RPopLPush("TestRPopLPush", "TestRPopLPush"));
Assert.Equal(Bytes, cli.RPopLPush<byte[]>("TestRPopLPush", "TestRPopLPush"));
Assert.Equal(Bytes, cli.RPopLPush<byte[]>("TestRPopLPush", "TestRPopLPush"));
Assert.Equal(Class.ToString(), cli.RPopLPush<TestClass>("TestRPopLPush", "TestRPopLPush").ToString());
Assert.Equal(Class.ToString(), cli.RPopLPush<TestClass>("TestRPopLPush", "TestRPopLPush").ToString());
}
[Fact]
public void RPush()
{
cli.Del("TestRPush");
Assert.Equal(8, cli.RPush("TestRPush", Null, Null, String, String, Bytes, Bytes, Class, Class));
Assert.Equal(2, cli.LRange("TestRPush", 0, 1).Length);
Assert.Equal("", cli.LRange("TestRPush", 0, 1)[0]);
Assert.Equal("", cli.LRange("TestRPush", 0, 1)[1]);
Assert.Equal(2, cli.LRange("TestRPush", 2, 3).Length);
Assert.Equal(String, cli.LRange("TestRPush", 2, 3)[0]);
Assert.Equal(String, cli.LRange("TestRPush", 2, 3)[1]);
Assert.Equal(2, cli.LRange("TestRPush", 4, 5).Length);
Assert.Equal(Bytes, cli.LRange<byte[]>("TestRPush", 4, 5)[0]);
Assert.Equal(Bytes, cli.LRange<byte[]>("TestRPush", 4, 5)[1]);
Assert.Equal(2, cli.LRange("TestRPush", 6, -1).Length);
Assert.Equal(Class.ToString(), cli.LRange<TestClass>("TestRPush", 6, -1)[0].ToString());
Assert.Equal(Class.ToString(), cli.LRange<TestClass>("TestRPush", 6, -1)[1].ToString());
}
[Fact]
public void RPushX()
{
cli.Del("TestRPushX");
Assert.Equal(0, cli.RPushX("TestRPushX", Null));
Assert.Equal(0, cli.RPushX("TestRPushX", String));
Assert.Equal(0, cli.RPushX("TestRPushX", Bytes));
Assert.Equal(0, cli.RPushX("TestRPushX", Class));
Assert.Equal(1, cli.RPush("TestRPushX", Null));
Assert.Equal(2, cli.RPushX("TestRPushX", Null));
Assert.Equal(3, cli.RPushX("TestRPushX", String));
Assert.Equal(4, cli.RPushX("TestRPushX", Bytes));
Assert.Equal(5, cli.RPushX("TestRPushX", Class));
}
}
}
|
2881099/FreeRedis | 23,975 | test/Unit/FreeRedis.Tests/RedisClientTests/StringsAsyncTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests
{
public class StringsAsyncTests : TestBase
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var connectionStringBuilder = (ConnectionStringBuilder)Connection.ToString();
connectionStringBuilder.Database = 13;
var r = new RedisClient(connectionStringBuilder);
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
public new static RedisClient cli => _cliLazy.Value;
[Fact]
async public Task AppendAsync()
{
var key = "TestAppend_null";
await cli.SetAsync(key, String);
await cli.AppendAsync(key, Null);
Assert.Equal(await cli.GetAsync(key), String);
key = "TestAppend_string";
await cli.SetAsync(key, String);
await cli.AppendAsync(key, String);
Assert.Equal(await cli.GetAsync(key), String + String);
var ms = new MemoryStream();
await cli.GetAsync(key, ms);
Assert.Equal(Encoding.UTF8.GetString(ms.ToArray()), String + String);
ms.Close();
key = "TestAppend_bytes";
await cli.SetAsync(key, Bytes);
await cli.AppendAsync(key, Bytes);
Assert.Equal(Convert.ToBase64String(cli.Get<byte[]>(key)), Convert.ToBase64String(Bytes.Concat(Bytes).ToArray()));
}
[Fact]
async public Task BitCountAsync()
{
await cli.DelAsync("TestBitCount");
var key = "TestBitCount";
await cli.SetBitAsync(key, 100, true);
await cli.SetBitAsync(key, 90, true);
await cli.SetBitAsync(key, 80, true);
Assert.Equal(3, await cli.BitCountAsync(key, 0, 101));
Assert.Equal(3, await cli.BitCountAsync(key, 0, 100));
Assert.Equal(3, await cli.BitCountAsync(key, 0, 99));
Assert.Equal(3, await cli.BitCountAsync(key, 0, 60));
}
[Fact]
async public Task BitOpAsync()
{
await cli.DelAsync("BitOp1", "BitOp2");
await cli.SetBitAsync("BitOp1", 100, true);
await cli.SetBitAsync("BitOp2", 100, true);
var r1 = await cli.BitOpAsync(BitOpOperation.and, "BitOp3", "BitOp1", "BitOp2");
}
[Fact]
async public Task BitPosAsync()
{
await cli.DelAsync("BitPos1");
await cli.SetBitAsync("BitPos1", 100, true);
Assert.Equal(100, await cli.BitPosAsync("BitPos1", true));
Assert.Equal(-1, await cli.BitPosAsync("BitPos1", true, 1, 100));
}
[Fact]
async public Task DecrAsync()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(-1, await cli.DecrAsync(key));
}
[Fact]
async public Task DecrByAsync()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(-10, await cli.DecrByAsync(key, 10));
}
[Fact]
async public Task GetAsync()
{
var key = "TestGet_null";
await cli.SetAsync(key, Null);
Assert.Equal((await cli.GetAsync(key))?.ToString() ?? "", Null?.ToString() ?? "");
key = "TestGet_string";
await cli.SetAsync(key, String);
Assert.Equal(await cli.GetAsync(key), String);
key = "TestGet_bytes";
await cli.SetAsync(key, Bytes);
Assert.Equal(cli.Get<byte[]>(key), Bytes);
key = "TestGet_class";
await cli.SetAsync(key, Class);
Assert.Equal(JsonConvert.SerializeObject(cli.Get<TestClass>(key)), JsonConvert.SerializeObject(Class));
key = "TestGet_classArray";
await cli.SetAsync(key, new[] { Class, Class });
Assert.Equal(2, cli.Get<TestClass[]>(key)?.Length);
Assert.Equal(JsonConvert.SerializeObject(cli.Get<TestClass[]>(key)?.First()), JsonConvert.SerializeObject(Class));
Assert.Equal(JsonConvert.SerializeObject(cli.Get<TestClass[]>(key)?.Last()), JsonConvert.SerializeObject(Class));
}
[Fact]
async public Task GetBitAsync()
{
await cli.DelAsync("GetBit1");
await cli.SetBitAsync("GetBit1", 100, true);
Assert.False(await cli.GetBitAsync("GetBit1", 10));
Assert.True(await cli.GetBitAsync("GetBit1", 100));
}
[Fact]
async public Task GetRangeAsync()
{
var key = "TestGetRange_null";
await cli.SetAsync(key, Null);
Assert.Equal("", await cli.GetRangeAsync(key, 10, 20));
key = "TestGetRange_string";
await cli.SetAsync(key, "abcdefg");
Assert.Equal("cde", await cli.GetRangeAsync(key, 2, 4));
Assert.Equal("abcdefg", await cli.GetRangeAsync(key, 0, -1));
key = "TestGetRange_bytes";
await cli.SetAsync(key, Bytes);
Assert.Equal(Bytes.AsSpan(2, 3).ToArray(), cli.GetRange<byte[]>(key, 2, 4));
Assert.Equal(Bytes, cli.GetRange<byte[]>(key, 0, -1));
}
[Fact]
async public Task GetSetAsync()
{
await cli.DelAsync("GetSet1");
Assert.Null(await cli.GetSetAsync("GetSet1", "123456"));
Assert.Equal("123456", await cli.GetSetAsync("GetSet1", "123456789"));
}
[Fact]
async public Task IncrAsync()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(1, await cli.IncrAsync(key));
}
[Fact]
async public Task IncrByAsync()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(10, await cli.IncrByAsync(key, 10));
}
[Fact]
async public Task IncrByFloatAsync()
{
var key = Guid.NewGuid().ToString();
Assert.Equal(10.1m, await cli.IncrByFloatAsync(key, 10.1m));
}
[Fact]
async public Task MGetAsync()
{
await cli.SetAsync("TestMGet_null1", Null);
await cli.SetAsync("TestMGet_string1", String);
await cli.SetAsync("TestMGet_bytes1", Bytes);
await cli.SetAsync("TestMGet_class1", Class);
await cli.SetAsync("TestMGet_null2", Null);
await cli.SetAsync("TestMGet_string2", String);
await cli.SetAsync("TestMGet_bytes2", Bytes);
await cli.SetAsync("TestMGet_class2", Class);
await cli.SetAsync("TestMGet_null3", Null);
await cli.SetAsync("TestMGet_string3", String);
await cli.SetAsync("TestMGet_bytes3", Bytes);
await cli.SetAsync("TestMGet_class3", Class);
Assert.Equal(4, (await cli.MGetAsync("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")).Length);
Assert.Equal("", (await cli.MGetAsync("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1"))[0]);
Assert.Equal(String, (await cli.MGetAsync("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1"))[1]);
Assert.Equal(Encoding.UTF8.GetString(Bytes), (await cli.MGetAsync("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1"))[2]);
Assert.Equal(JsonConvert.SerializeObject(Class), (await cli.MGetAsync("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1"))[3]);
Assert.Equal(4, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1").Length);
Assert.Equal(new byte[0], cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[0]);
Assert.Equal(Encoding.UTF8.GetBytes(String), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[1]);
Assert.Equal(Bytes, cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[2]);
Assert.Equal(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(Class)), cli.MGet<byte[]>("TestMGet_null1", "TestMGet_string1", "TestMGet_bytes1", "TestMGet_class1")[3]);
Assert.Equal(3, cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3").Length);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3")[0]));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3")[1]));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.MGet<TestClass>("TestMGet_class1", "TestMGet_class2", "TestMGet_class3")[2]));
}
[Fact]
async public Task MSetAsync()
{
await cli.DelAsync("TestMSet_null1", "TestMSet_string1", "TestMSet_bytes1", "TestMSet_class1");
await cli.MSetAsync(new Dictionary<string, object> { ["TestMSet_null1"] = Null, ["TestMSet_string1"] = String, ["TestMSet_bytes1"] = Bytes, ["TestMSet_class1"] = Class });
Assert.Equal("", await cli.GetAsync("TestMSet_null1"));
Assert.Equal(String, await cli.GetAsync("TestMSet_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSet_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSet_class1")));
await cli.DelAsync("TestMSet_null1", "TestMSet_string1", "TestMSet_bytes1", "TestMSet_class1");
await cli.MSetAsync("TestMSet_null1", Null, "TestMSet_string1", String, "TestMSet_bytes1", Bytes, "TestMSet_class1", Class);
Assert.Equal("", await cli.GetAsync("TestMSet_null1"));
Assert.Equal(String, await cli.GetAsync("TestMSet_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSet_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSet_class1")));
}
[Fact]
async public Task MSetNxAsync()
{
await cli.DelAsync("TestMSetNx_null", "TestMSetNx_string", "TestMSetNx_bytes", "TestMSetNx_class", "abctest",
"TestMSetNx_null1", "TestMSetNx_string1", "TestMSetNx_bytes1", "TestMSetNx_class1");
Assert.True(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_null"] = Null }));
Assert.False(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_null"] = Null }));
Assert.Equal("", await cli.GetAsync("TestMSetNx_null"));
Assert.True(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_string"] = String }));
Assert.False(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_string"] = String }));
Assert.Equal(String, await cli.GetAsync("TestMSetNx_string"));
Assert.True(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_bytes"] = Bytes }));
Assert.False(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_bytes"] = Bytes }));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes"));
Assert.True(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_class"] = Class }));
Assert.False(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_class"] = Class }));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSetNx_class")));
await cli.SetAsync("abctest", 1);
Assert.False(await cli.MSetNxAsync(new Dictionary<string, object> { ["abctest"] = 2, ["TestMSetNx_null1"] = Null, ["TestMSetNx_string1"] = String, ["TestMSetNx_bytes1"] = Bytes, ["TestMSetNx_class1"] = Class }));
Assert.True(await cli.MSetNxAsync(new Dictionary<string, object> { ["TestMSetNx_null1"] = Null, ["TestMSetNx_string1"] = String, ["TestMSetNx_bytes1"] = Bytes, ["TestMSetNx_class1"] = Class }));
Assert.Equal(1, cli.Get<int>("abctest"));
Assert.Equal("", await cli.GetAsync("TestMSetNx_null1"));
Assert.Equal(String, await cli.GetAsync("TestMSetNx_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSetNx_class1")));
await cli.DelAsync("TestMSetNx_null", "TestMSetNx_string", "TestMSetNx_bytes", "TestMSetNx_class");
await cli.MSetNxAsync("TestMSetNx_null1", Null, "TestMSetNx_string1", String, "TestMSetNx_bytes1", Bytes, "TestMSetNx_class1", Class);
Assert.Equal("", await cli.GetAsync("TestMSetNx_null1"));
Assert.Equal(String, await cli.GetAsync("TestMSetNx_string1"));
Assert.Equal(Bytes, cli.Get<byte[]>("TestMSetNx_bytes1"));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestMSetNx_class1")));
}
[Fact]
async public Task PSetNxAsync()
{
await cli.PSetExAsync("TestSetNx_null", 10000, Null);
Assert.Equal("", await cli.GetAsync("TestSetNx_null"));
await cli.PSetExAsync("TestSetNx_string", 10000, String);
Assert.Equal(String, await cli.GetAsync("TestSetNx_string"));
await cli.PSetExAsync("TestSetNx_bytes", 10000, Bytes);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));
await cli.PSetExAsync("TestSetNx_class", 10000, Class);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetNx_class")));
}
[Fact]
async public Task SetAsync()
{
await cli.DelAsync("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
await cli.SetAsync("TestSet_null", Null);
Assert.Equal("", await cli.GetAsync("TestSet_null"));
await cli.SetAsync("TestSet_string", String);
Assert.Equal(String, await cli.GetAsync("TestSet_string"));
await cli.SetAsync("TestSet_bytes", Bytes);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));
await cli.SetAsync("TestSet_class", Class);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSet_class")));
await cli.DelAsync("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
await cli.SetAsync("TestSet_null", Null, 10);
Assert.Equal("", await cli.GetAsync("TestSet_null"));
await cli.SetAsync("TestSet_string", String, 10);
Assert.Equal(String, await cli.GetAsync("TestSet_string"));
await cli.SetAsync("TestSet_bytes", Bytes, 10);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));
await cli.SetAsync("TestSet_class", Class, 10);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSet_class")));
await cli.DelAsync("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
await cli.SetAsync("TestSet_null", Null, true);
Assert.Equal("", await cli.GetAsync("TestSet_null"));
await cli.SetAsync("TestSet_string", String, true);
Assert.Equal(String, await cli.GetAsync("TestSet_string"));
await cli.SetAsync("TestSet_bytes", Bytes, true);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSet_bytes"));
await cli.SetAsync("TestSet_class", Class, true);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSet_class")));
}
[Fact]
async public Task SetNxAsync()
{
await cli.DelAsync("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
Assert.True(await cli.SetNxAsync("TestSetNx_null", Null));
Assert.False(await cli.SetNxAsync("TestSetNx_null", Null));
Assert.Equal("", await cli.GetAsync("TestSetNx_null"));
Assert.True(await cli.SetNxAsync("TestSetNx_string", String));
Assert.False(await cli.SetNxAsync("TestSetNx_string", String));
Assert.Equal(String, await cli.GetAsync("TestSetNx_string"));
Assert.True(await cli.SetNxAsync("TestSetNx_bytes", Bytes));
Assert.False(await cli.SetNxAsync("TestSetNx_bytes", Bytes));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));
Assert.True(await cli.SetNxAsync("TestSetNx_class", Class));
Assert.False(await cli.SetNxAsync("TestSetNx_class", Class));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetNx_class")));
await cli.DelAsync("TestSetNx_null", "TestSetNx_string", "TestSetNx_bytes", "TestSetNx_class");
Assert.True(await cli.SetNxAsync("TestSetNx_null", Null, 10));
Assert.False(await cli.SetNxAsync("TestSetNx_null", Null, 10));
Assert.Equal("", await cli.GetAsync("TestSetNx_null"));
Assert.True(await cli.SetNxAsync("TestSetNx_string", String, 10));
Assert.False(await cli.SetNxAsync("TestSetNx_string", String, 10));
Assert.Equal(String, await cli.GetAsync("TestSetNx_string"));
Assert.True(await cli.SetNxAsync("TestSetNx_bytes", Bytes, 10));
Assert.False(await cli.SetNxAsync("TestSetNx_bytes", Bytes, 10));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetNx_bytes"));
Assert.True(await cli.SetNxAsync("TestSetNx_class", Class, 10));
Assert.False(await cli.SetNxAsync("TestSetNx_class", Class, 10));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetNx_class")));
}
[Fact]
async public Task SetXxAsync()
{
await cli.DelAsync("TestSetXx_null");
Assert.False(await cli.SetXxAsync("TestSetXx_null", Null, 10));
await cli.SetAsync("TestSetXx_null", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_null", Null, 10));
Assert.Equal("", await cli.GetAsync("TestSetXx_null"));
await cli.DelAsync("TestSetXx_string");
Assert.False(await cli.SetXxAsync("TestSetXx_string", String, 10));
await cli.SetAsync("TestSetXx_string", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_string", String, 10));
Assert.Equal(String, await cli.GetAsync("TestSetXx_string"));
await cli.DelAsync("TestSetXx_bytes");
Assert.False(await cli.SetXxAsync("TestSetXx_bytes", Bytes, 10));
await cli.SetAsync("TestSetXx_bytes", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_bytes", Bytes, 10));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetXx_bytes"));
await cli.DelAsync("TestSetXx_class");
Assert.False(await cli.SetXxAsync("TestSetXx_class", Class, 10));
await cli.SetAsync("TestSetXx_class", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_class", Class, 10));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetXx_class")));
await cli.DelAsync("TestSetXx_null");
Assert.False(await cli.SetXxAsync("TestSetXx_null", Null, true));
await cli.SetAsync("TestSetXx_null", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_null", Null, true));
Assert.Equal("", await cli.GetAsync("TestSetXx_null"));
await cli.DelAsync("TestSetXx_string");
Assert.False(await cli.SetXxAsync("TestSetXx_string", String, true));
await cli.SetAsync("TestSetXx_string", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_string", String, true));
Assert.Equal(String, await cli.GetAsync("TestSetXx_string"));
await cli.DelAsync("TestSetXx_bytes");
Assert.False(await cli.SetXxAsync("TestSetXx_bytes", Bytes, true));
await cli.SetAsync("TestSetXx_bytes", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_bytes", Bytes, true));
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetXx_bytes"));
await cli.DelAsync("TestSetXx_class");
Assert.False(await cli.SetXxAsync("TestSetXx_class", Class, true));
await cli.SetAsync("TestSetXx_class", 1, true);
Assert.True(await cli.SetXxAsync("TestSetXx_class", Class, true));
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetXx_class")));
}
[Fact]
async public Task SetBitAsync()
{
await cli.DelAsync("SetBit1");
await cli.SetBitAsync("SetBit1", 100, true);
Assert.False(await cli.GetBitAsync("SetBit1", 10));
Assert.True(await cli.GetBitAsync("SetBit1", 100));
}
[Fact]
async public Task SetExAsync()
{
await cli.DelAsync("TestSetEx_null", "TestSetEx_string", "TestSetEx_bytes", "TestSetEx_class");
await cli.SetExAsync("TestSetEx_null", 10, Null);
Assert.Equal("", await cli.GetAsync("TestSetEx_null"));
await cli.SetExAsync("TestSetEx_string", 10, String);
Assert.Equal(String, await cli.GetAsync("TestSetEx_string"));
await cli.SetExAsync("TestSetEx_bytes", 10, Bytes);
Assert.Equal(Bytes, cli.Get<byte[]>("TestSetEx_bytes"));
await cli.SetExAsync("TestSetEx_class", 10, Class);
Assert.Equal(JsonConvert.SerializeObject(Class), JsonConvert.SerializeObject(cli.Get<TestClass>("TestSetEx_class")));
}
[Fact]
async public Task SetRangeAsync()
{
var key = "TestSetRange_null";
await cli.SetAsync(key, Null);
await cli.SetRangeAsync(key, 10, String);
Assert.Equal(String, await cli.GetRangeAsync(key, 10, -1));
key = "TestSetRange_string";
await cli.SetAsync(key, "abcdefg");
await cli.SetRangeAsync(key, 2, "yyy");
Assert.Equal("yyy", await cli.GetRangeAsync(key, 2, 4));
key = "TestSetRange_bytes";
await cli.SetAsync(key, Bytes);
await cli.SetRangeAsync(key, 2, Bytes);
Assert.Equal(Bytes, cli.GetRange<byte[]>(key, 2, Bytes.Length + 2));
}
[Fact]
async public Task StrLenAsync()
{
var key = "TestStrLen_null";
await cli.SetAsync(key, Null);
Assert.Equal(0, await cli.StrLenAsync(key));
key = "TestStrLen_string";
await cli.SetAsync(key, "abcdefg");
Assert.Equal(7, await cli.StrLenAsync(key));
key = "TestStrLen_string";
await cli.SetAsync(key, String);
Assert.Equal(15, await cli.StrLenAsync(key));
key = "TestStrLen_bytes";
await cli.SetAsync(key, Bytes);
Assert.Equal(Bytes.Length, await cli.StrLenAsync(key));
}
}
}
|
2881099/FreeRedis | 13,173 | test/Unit/FreeRedis.Tests/RedisClientTests/KeysTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests
{
public class KeysTests : TestBase
{
[Fact]
public void Del()
{
var keys = Enumerable.Range(0, 10).Select(a => Guid.NewGuid().ToString()).ToArray();
cli.MSet(keys.ToDictionary(a => a, a => (object)a));
Assert.Equal(10, cli.Del(keys));
}
[Fact]
public void Dump()
{
cli.Del("TestDump_null2", "TestDump_string2", "TestDump_bytes2", "TestDump_class2");
cli.MSet("TestDump_null1", base.Null, "TestDump_string1", base.String, "TestDump_bytes1", base.Bytes, "TestDump_class1", base.Class);
cli.Restore("TestDump_null2", cli.Dump("TestDump_null1"));
Assert.Equal(cli.Get("TestDump_null2"), cli.Get("TestDump_null1"));
cli.Restore("TestDump_string2", cli.Dump("TestDump_string1"));
Assert.Equal(cli.Get("TestDump_string2"), cli.Get("TestDump_string1"));
cli.Restore("TestDump_bytes2", cli.Dump("TestDump_bytes1"));
Assert.Equal(cli.Get<byte[]>("TestDump_bytes2"), cli.Get<byte[]>("TestDump_bytes1"));
cli.Restore("TestDump_class2", cli.Dump("TestDump_class1"));
Assert.Equal(cli.Get<TestClass>("TestDump_class2").ToString(), cli.Get<TestClass>("TestDump_class1").ToString());
}
[Fact]
public void Exists()
{
cli.Del("TestExists_null1");
Assert.False(cli.Exists("TestExists_null1"));
cli.Set("TestExists_null1", 1);
Assert.True(cli.Exists("TestExists_null1"));
Assert.Equal(1, cli.Del("TestExists_null1"));
Assert.False(cli.Exists("TestExists_null1"));
}
[Fact]
public void Expire()
{
cli.MSet("TestExpire_null1", base.Null, "TestExpire_string1", base.String, "TestExpire_bytes1", base.Bytes, "TestExpire_class1", base.Class);
Assert.True(cli.Expire("TestExpire_null1", 10));
Assert.Equal(10, cli.Ttl("TestExpire_null1"));
Assert.True(cli.Expire("TestExpire_string1", 60 * 60));
Assert.Equal(60 * 60, cli.Ttl("TestExpire_string1"));
}
[Fact]
public void ExpireAt()
{
cli.MSet("TestExpireAt_null1", base.Null, "TestExpireAt_string1", base.String, "TestExpireAt_bytes1", base.Bytes, "TestExpireAt_class1", base.Class);
Assert.True(cli.ExpireAt("TestExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
Assert.InRange(cli.Ttl("TestExpireAt_null1"), 9, 20);
Assert.True(cli.ExpireAt("TestExpireAt_string1", DateTime.UtcNow.AddHours(1)));
Assert.InRange(cli.Ttl("TestExpireAt_string1"), 60 * 60 - 10, 60 * 60 + 10);
}
[Fact]
public void Keys()
{
cli.MSet("TestKeys_null1", base.Null, "TestKeys_string1", base.String, "TestKeys_bytes1", base.Bytes, "TestKeys_class1", base.Class);
Assert.Equal(4, cli.Keys("TestKeys_*").Length);
}
[Fact]
public void Migrate()
{
}
[Fact]
public void Move()
{
cli.MSet("TestMove_null1", base.Null, "TestMove_string1", base.String, "TestMove_bytes1", base.Bytes, "TestMove_class1", base.Class);
using (var sh = cli.GetDatabase(11))
{
sh.Del("TestMove_string1");
}
Assert.True(cli.Move("TestMove_string1", 11));
Assert.False(cli.Exists("TestMove_string1"));
using (var sh = cli.GetDatabase(11))
{
Assert.Equal(base.String, sh.Get("TestMove_string1"));
}
cli.Set("TestMove_string1", base.String);
Assert.False(cli.Move("TestMove_string1", 11)); //target exists
Assert.Equal(base.String, cli.Get("TestMove_string1"));
using (var sh = cli.GetDatabase(11))
{
Assert.Equal(base.String, sh.Get("TestMove_string1"));
sh.Del("TestMove_string1");
}
}
[Fact]
public void ObjectRefCount()
{
cli.MSet("TestObjectRefCount_null1", base.Null, "TestObjectRefCount_string1", base.String, "TestObjectRefCount_bytes1", base.Bytes, "TestObjectRefCount_class1", base.Class);
Assert.True(cli.Exists("TestObjectRefCount_string1"));
cli.Get("TestObjectRefCount_string1");
Assert.Null(cli.ObjectRefCount("TestObjectRefCount_bytes11"));
Assert.Equal(1, cli.ObjectRefCount("TestObjectRefCount_string1"));
}
[Fact]
public void ObjectIdleTime()
{
var key1 = "ObjectIdleTime1";
cli.LPush(key1, "hello world");
Assert.Equal(0, cli.ObjectIdleTime(key1));
}
[Fact]
public void ObjectEncoding()
{
var key1 = "ObjectEncoding1";
cli.LPush(key1, "ObjectEncoding1_val1");
Assert.Equal("quicklist", cli.ObjectEncoding(key1));
}
[Fact]
public void ObjectFreq()
{
var key1 = "ObjectFreq1";
cli.Set(key1, "test1");
cli.Get(key1);
//Assert.True(cli.ObjectFreq(key1) > 0);
Assert.Null(cli.ObjectFreq(key1 + "_no_such_key"));
}
[Fact]
public void Presist()
{
cli.MSet("TestPersist_null1", base.Null, "TestPersist_string1", base.String, "TestPersist_bytes1", base.Bytes, "TestPersist_class1", base.Class);
Assert.True(cli.Expire("TestPersist_null1", 10));
Assert.Equal(10, cli.Ttl("TestPersist_null1"));
Assert.True(cli.Expire("TestPersist_string1", 60 * 60));
Assert.Equal(60 * 60, cli.Ttl("TestPersist_string1"));
Assert.True(cli.Persist("TestPersist_null1"));
Assert.False(cli.Persist("TestPersist_null11"));
Assert.True(cli.Persist("TestPersist_string1"));
Assert.False(cli.Persist("TestPersist_string11"));
Assert.Equal(-1, cli.Ttl("TestPersist_null1"));
Assert.Equal(-1, cli.Ttl("TestPersist_string1"));
}
[Fact]
public void PExpire()
{
cli.MSet("TestPExpire_null1", base.Null, "TestPExpire_string1", base.String, "TestPExpire_bytes1", base.Bytes, "TestPExpire_class1", base.Class);
Assert.True(cli.PExpire("TestPExpire_null1", 10000));
//Assert.InRange(cli.PTtl("TestPExpire_null1"), 9000, 10000);
Assert.True(cli.PExpire("TestPExpire_string1", 60 * 60));
//Assert.InRange(cli.PTtl("TestPExpire_string1"), 1000 * 60 * 60 - 1000, 1000 * 60 * 60);
}
[Fact]
public void PExpireAt()
{
cli.MSet("TestPExpireAt_null1", base.Null, "TestPExpireAt_string1", base.String, "TestPExpireAt_bytes1", base.Bytes, "TestPExpireAt_class1", base.Class);
Assert.True(cli.ExpireAt("TestPExpireAt_null1", DateTime.UtcNow.AddSeconds(10)));
Assert.InRange(cli.PTtl("TestPExpireAt_null1"), 9000, 20000);
Assert.True(cli.ExpireAt("TestPExpireAt_string1", DateTime.UtcNow.AddHours(1)));
Assert.InRange(cli.PTtl("TestPExpireAt_string1"), 1000 * 60 * 60 - 10000, 1000 * 60 * 60 + 10000);
}
[Fact]
public void PTtl()
{
cli.MSet("TestPTtl_null1", base.Null, "TestPTtl_string1", base.String, "TestPTtl_bytes1", base.Bytes, "TestPTtl_class1", base.Class);
Assert.True(cli.PExpire("TestPTtl_null1", 1000));
Assert.InRange(cli.PTtl("TestPTtl_null1"), 500, 1000);
Assert.InRange(cli.PTtl("TestPTtl_null11"), long.MinValue, -1);
}
[Fact]
public void RandomKey()
{
cli.MSet("TestRandomKey_null1", base.Null, "TestRandomKey_string1", base.String, "TestRandomKey_bytes1", base.Bytes, "TestRandomKey_class1", base.Class);
Assert.NotNull(cli.RandomKey());
}
[Fact]
public void Rename()
{
cli.MSet("TestRename_null1", base.Null, "TestRename_string1", base.String, "TestRename_bytes1", base.Bytes, "TestRename_class1", base.Class);
Assert.Equal(base.String, cli.Get("TestRename_string1"));
cli.Rename("TestRename_string1", "TestRename_string11");
Assert.False(cli.Exists("TestRename_string1"));
Assert.Equal(base.String, cli.Get("TestRename_string11"));
cli.Rename("TestRename_class1", "TestRename_string11");
Assert.False(cli.Exists("TestRename_class1"));
Assert.Equal(base.Class.ToString(), cli.Get<TestClass>("TestRename_string11").ToString());
}
[Fact]
public void RenameNx()
{
cli.Del("TestRenameNx_string11", "TestRename_string11");
cli.MSet("TestRenameNx_null1", base.Null, "TestRenameNx_string1", base.String, "TestRenameNx_bytes1", base.Bytes, "TestRenameNx_class1", base.Class);
Assert.Equal(base.String, cli.Get("TestRenameNx_string1"));
Assert.True(cli.RenameNx("TestRenameNx_string1", "TestRenameNx_string11"));
Assert.False(cli.Exists("TestRenameNx_string1"));
Assert.Equal(base.String, cli.Get("TestRenameNx_string11"));
Assert.True(cli.RenameNx("TestRenameNx_class1", "TestRename_string11"));
Assert.False(cli.Exists("TestRenameNx_class1"));
Assert.Equal(base.Class.ToString(), cli.Get<TestClass>("TestRename_string11").ToString());
}
[Fact]
public void Restore()
{
cli.Del("TestRestore_null2", "TestRestore_string2", "TestRestore_bytes2", "TestRestore_class2");
cli.MSet("TestRestore_null1", base.Null, "TestRestore_string1", base.String, "TestRestore_bytes1", base.Bytes, "TestRestore_class1", base.Class);
cli.Restore("TestRestore_null2", cli.Dump("TestRestore_null1"));
Assert.Equal(cli.Get("TestRestore_null2"), cli.Get("TestRestore_null1"));
cli.Restore("TestRestore_string2", cli.Dump("TestRestore_string1"));
Assert.Equal(cli.Get("TestRestore_string2"), cli.Get("TestRestore_string1"));
cli.Restore("TestRestore_bytes2", cli.Dump("TestRestore_bytes1"));
Assert.Equal(cli.Get<byte[]>("TestRestore_bytes2"), cli.Get<byte[]>("TestRestore_bytes1"));
cli.Restore("TestRestore_class2", cli.Dump("TestRestore_class1"));
Assert.Equal(cli.Get<TestClass>("TestRestore_class2").ToString(), cli.Get<TestClass>("TestRestore_class1").ToString());
}
[Fact]
public void Scan()
{
for (var a = 0; a < 11; a++)
cli.Set(Guid.NewGuid().ToString(), a);
var keys = new List<string>();
foreach (var rt in cli.Scan("*", 2, null))
{
keys.AddRange(rt);
}
}
[Fact]
public void HScan()
{
cli.Del("HScan01");
for (var a = 0; a < 11; a++)
cli.HSet("HScan01", Guid.NewGuid().ToString(), a);
var keys = new List<KeyValuePair<string, string>>();
foreach (var rt in cli.HScan("HScan01", "*", 2))
{
keys.AddRange(rt);
}
Assert.Equal(11, keys.Count);
}
[Fact]
public void Sort()
{
var key1 = "Sort1";
cli.LPush(key1, 1, 2, 10);
cli.Set("bar1", "bar1");
cli.Set("bar2", "bar2");
cli.Set("bar10", "bar10");
cli.Set("car1", "car1");
cli.Set("car2", "car2");
cli.Set("car10", "car10");
var r1 = cli.Sort(key1, getPatterns: new[] { "car*", "bar*" }, collation: Collation.desc, alpha: true);
var r2 = cli.Sort(key1, getPatterns: new[] { "car*", "bar*" }, offset: 1, count:5, collation: Collation.desc, alpha: true);
}
[Fact]
public void Touch()
{
}
[Fact]
public void Ttl()
{
cli.MSet("TestTtl_null1", base.Null, "TestTtl_string1", base.String, "TestTtl_bytes1", base.Bytes, "TestTtl_class1", base.Class);
Assert.True(cli.Expire("TestTtl_null1", 10));
Assert.InRange(cli.Ttl("TestTtl_null1"), 5, 10);
Assert.InRange(cli.Ttl("TestTtl_null11"), long.MinValue, -1);
}
[Fact]
public void Type()
{
cli.MSet("TestType_null1", base.Null, "TestType_string1", base.String, "TestType_bytes1", base.Bytes, "TestType_class1", base.Class);
Assert.Equal(KeyType.none, cli.Type("TestType_string111111111123"));
Assert.Equal(KeyType.@string, cli.Type("TestType_string1"));
}
[Fact]
public void UnLink()
{
}
[Fact]
public void Wait()
{
}
}
}
|
2881099/FreeRedis | 20,614 | test/Unit/FreeRedis.Tests/RedisClientTests/ModulesTests/RediSearchTests.cs | using FreeRedis.RediSearch;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests.Other
{
public class RediSearchTests : TestBase
{
protected static ConnectionStringBuilder Connection = new ConnectionStringBuilder()
{
Host = "8.154.26.119:63791",
MaxPoolSize = 10,
Protocol = RedisProtocol.RESP2,
ClientName = "FreeRedis",
//FtDialect = 4,
FtLanguage = "chinese"
};
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var r = new RedisClient(Connection);
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
public static RedisClient cli => _cliLazy.Value;
[FtDocument("index_post", Prefix = "blog:post:")]
class TestDoc
{
[FtKey]
public int Id { get; set; }
[FtTextField("title22", Weight = 5.0)]
public string Title { get; set; }
[FtTextField("category22")]
public string Category { get; set; }
[FtTextField("content22", Weight = 1.0, NoIndex = true)]
public string Content { get; set; }
[FtTagField("tags22")]
public string Tags { get; set; }
[FtNumericField("views")]
public int Views { get; set; }
[FtGeoField("location")]
public string Location { get; set; }
[FtGeoShapeField("shape", System = CoordinateSystem.FLAT)]
public string Shape { get; set; }
}
[FtDocument("index_post100", Prefix = "blog:post:")]
class TagMapArrayIndex
{
[FtKey]
public int Id { get; set; }
[FtTextField("title", Weight = 5.0)]
public string Title { get; set; }
[FtTextField("category")]
public string Category { get; set; }
[FtTextField("content", Weight = 1.0, NoIndex = true)]
public string Content { get; set; }
[FtTagField("tags")]
public string[] Tags { get; set; }
[FtNumericField("views")]
public int Views { get; set; }
}
[Fact]
public void TagMapArray()
{
var repo = cli.FtDocumentRepository<TagMapArrayIndex>();
try
{
repo.DropIndex();
}
catch { }
repo.CreateIndex();
repo.Save(new TagMapArrayIndex { Id = 1, Title = "测试标题1 word", Category = "一级分类", Content = "测试内容1suffix", Tags = ["作者1", "作者2"], Views = 101 });
repo.Save(new TagMapArrayIndex { Id = 2, Title = "prefix测试标题2", Category = "二级分类", Content = "测试infix内容2", Tags = ["作者2", "作者3"], Views = 201 });
repo.Save(new TagMapArrayIndex { Id = 3, Title = "测试标题3 word", Category = "一级分类", Content = "测试word内容3", Tags = ["作者2", "作者5"], Views = 301 });
repo.Delete(1, 2, 3);
repo.Save(new[]{
new TagMapArrayIndex { Id = 1, Title = "测试标题1 word", Category = "一级分类", Content = "测试内容1suffix", Tags = ["作者1","作者2"], Views = 101 },
new TagMapArrayIndex { Id = 2, Title = "prefix测试标题2", Category = "二级分类", Content = "测试infix内容2", Tags = ["作者2","作者3"], Views = 201 },
new TagMapArrayIndex { Id = 3, Title = "测试标题3 word", Category = "一级分类", Content = "测试word内容3", Tags = ["作者2","作者5"], Views = 301 }
});
var list = repo.Search(a => a.Tags.Contains("作者1")).ToList();
list = repo.Search(a => a.Title.Contains("word")).ToList();
var list2 = repo.Search("@title:我是中国人").ToList();
list2 = repo.Search("@title:中国人").ToList();
list2 = repo.Search("@title:中国").ToList();
list2 = repo.Search("@title:国").ToList();
}
[FtDocument("index_post101", Prefix = "blog:post101:")]
class TagMapListIndex
{
[FtKey]
public int Id { get; set; }
[FtTextField("title1", Weight = 5.0)]
public string Title { get; set; }
[FtTextField("category1")]
public string Category { get; set; }
[FtTextField("content2", Weight = 1.0, NoIndex = true)]
public string Content { get; set; }
[FtTagField("tags11")]
public List<string> Tags { get; set; }
[FtNumericField("views")]
public int Views { get; set; }
}
[Fact]
public void TagMapList()
{
var repo = cli.FtDocumentRepository<TagMapListIndex>();
try
{
repo.DropIndex();
}
catch { }
repo.CreateIndex();
repo.Save(new TagMapListIndex { Id = 1, Title = "测试标题1 word", Category = "一级分类", Content = "测试内容1suffix", Tags = ["作者1", "作者2"], Views = 101 });
repo.Save(new TagMapListIndex { Id = 2, Title = "prefix测试标题2", Category = "二级分类", Content = "测试infix内容2", Tags = ["作者2", "作者3"], Views = 201 });
repo.Save(new TagMapListIndex { Id = 3, Title = "测试标题3 word", Category = "一级分类", Content = "测试word内容3", Tags = ["作者2", "作者5"], Views = 301 });
repo.Delete(1, 2, 3);
repo.Save(new[]{
new TagMapListIndex { Id = 1, Title = "测试标题1 word", Category = "一级分类", Content = "测试内容1suffix", Tags = ["作者1","作者2"], Views = 101 },
new TagMapListIndex { Id = 2, Title = "prefix测试标题2", Category = "二级分类", Content = "测试infix内容2", Tags = ["作者2","作者3"], Views = 201 },
new TagMapListIndex { Id = 3, Title = "测试标题3 word", Category = "一级分类", Content = "测试word内容3", Tags = ["作者2","作者5"], Views = 301 }
});
var list = repo.Search(a => a.Tags.Contains("作者1")).ToList();
list = repo.Search(a => a.Title.Contains("word")).ToList();
var list2 = repo.Search("@title:我是中国人").ToList();
list2 = repo.Search("@title:中国人").ToList();
list2 = repo.Search("@title:中国").ToList();
list2 = repo.Search("@title:国").ToList();
}
[Fact]
public void FtDocumentRepository()
{
var connStr = Connection.ToString();
var repo = cli.FtDocumentRepository<TestDoc>();
try
{
repo.DropIndex();
}
catch { }
repo.CreateIndex();
repo.Save(new TestDoc { Id = 1, Title = "测试标题1 word", Category = "一级分类", Content = "测试内容1suffix", Tags = "作者1,作者2", Views = 101 });
repo.Save(new TestDoc { Id = 2, Title = "prefix测试标题2", Category = "二级分类", Content = "测试infix内容2", Tags = "作者2,作者3", Views = 201 });
repo.Save(new TestDoc { Id = 3, Title = "测试标题3 word", Category = "一级分类", Content = "测试word内容3", Tags = "作者2,作者5", Views = 301 });
repo.Delete(1, 2, 3);
repo.Save(new[]{
new TestDoc { Id = 1, Title = "测试标题1 word", Category = "一级分类", Content = "测试内容1suffix", Tags = "作者1,作者2", Views = 101, Location = "104.800644 38.846127", Shape = "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))" },
new TestDoc { Id = 2, Title = "prefix测试标题2", Category = "二级分类", Content = "测试infix内容2", Tags = "作者2,作者3", Views = 201, Location = "-104.991531, 39.742043", Shape = "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))" },
new TestDoc { Id = 3, Title = "测试标题3 word", Category = "一级分类", Content = "测试word内容3", Tags = "作者2,作者5", Views = 301,Location = "-105.0618814,40.5150098", Shape = "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))" }
});
var list = repo.Search("*").InFields(a => new { a.Title }).ToList();
list = repo.Search("*").Return(a => new { a.Title, a.Tags }).ToList();
list = repo.Search("*").Return(a => new { tit1 = a.Title, tgs1 = a.Tags, a.Title, a.Tags }).ToList();
list = repo.Search(a => a.Title == "word" || a.Views > 100).Filter(a => a.Views, 1, 1000).ToList();
list = repo.Search(a => a.Title.Contains("word") || a.Views > 100).Filter(a => a.Views, 1, 1000).ToList();
list = repo.Search(a => a.Tags == "作者1").Filter(a => a.Views, 1, 1000).ToList();
list = repo.Search("word").ToList();
list = repo.Search("@title:word").ToList();
list = repo.Search("prefix*").ToList();
list = repo.Search("@title:prefix*").ToList();
list = repo.Search("*suffix").ToList();
list = repo.Search("*infix*").ToList();
list = repo.Search("%word%").ToList();
list = repo.Search("@views:[200 300]").ToList();
list = repo.Search("@views:[-inf 2000]").SortBy(a => a.Views).Limit(0, 5).ToList();
list = repo.Search("@views:[(200 (300]").ToList();
list = repo.Search("@views>=200").Dialect(4).ToList();
list = repo.Search("@views:[200 +inf]").ToList();
list = repo.Search("@views<=300").Dialect(4).ToList();
list = repo.Search("@views:[-inf 300]").ToList();
list = repo.Search("@views==200").Dialect(4).ToList();
list = repo.Search("@views:[200 200]").ToList();
list = repo.Search("@views!=200").Dialect(4).ToList();
list = repo.Search("-@views:[200 200]").ToList();
list = repo.Search("@views==200 | @views==300").Dialect(4).ToList();
list = repo.Search("*").Filter("views", 200, 300).Dialect(4).ToList();
list = repo.Search("word").ToList();
list = repo.Search("@title:word").ToList();
list = repo.Search("prefix*").ToList();
list = repo.Search("@title:prefix*").ToList();
list = repo.Search("*suffix").ToList();
list = repo.Search("*infix*").ToList();
list = repo.Search("%word%").ToList();
list = repo.Search("@views:[200 300]").ToList();
list = repo.Search("@views:[-inf 2000]").SortBy(a => a.Views).Limit(0, 5).ToList();
list = repo.Search("@views:[(200 (300]").ToList();
list = repo.Search("@views>=200").Dialect(4).ToList();
list = repo.Search("@views:[200 +inf]").ToList();
list = repo.Search("@views<=300").Dialect(4).ToList();
list = repo.Search("@views:[-inf 300]").ToList();
list = repo.Search("@views==200").Dialect(4).ToList();
list = repo.Search("@views:[200 200]").ToList();
list = repo.Search("@views!=200").Dialect(4).ToList();
list = repo.Search("-@views:[200 200]").ToList();
list = repo.Search("@views==200 | @views==300").Dialect(4).ToList();
list = repo.Search("*").Filter("views", 200, 300).Dialect(4).ToList();
list = repo.Search("@location:[-104.800644 38.846127 100 mi]").ToList();
list = repo.Search(a => a.Location.GeoRadius(-104.800644m, 38.846127m, 38.846127m, GeoUnit.mi)).ToList();
list = repo.Search("@shape:[WITHIN $qshape]").Params("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))").Dialect(3).ToList();
list = repo.Search(a => a.Shape.ShapeWithin("qshape")).Params("qshape", "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))").Dialect(3).ToList();
}
[Fact]
public void FtSearch()
{
var rt = cli.FtSearch("index_contacts", "(@email:*wjx\\.cn*) (@companyid==10096)")
.Limit(0, 10)
.Dialect(4)
.Execute();
var idxName = Guid.NewGuid().ToString();
cli.FtCreate(idxName)
.On(IndexDataType.Hash)
.Prefix("blog:post:")
.AddTextField("title", weight: 5.0)
.AddTextField("content")
.AddTagField("author")
.AddNumericField("created_date", sortable: true)
.AddNumericField("views")
.Execute();
cli.HSet("blog:post:1", "title", "测试标题1 word", "content", "测试内容1suffix", "author", "作者1,作者2", "created_date", "10000", "views", 10);
cli.HSet("blog:post:2", "title", "prefix测试标题2", "content", "测试infix内容2", "author", "作者2,作者3", "created_date", "10001", "views", 201);
cli.HSet("blog:post:3", "title", "测试标题3 word", "content", "测试word内容3", "author", "作者2,作者5", "created_date", "10002", "views", 301);
var list = cli.FtSearch(idxName, "word").Execute();
list = cli.FtSearch(idxName, "@title:word").Execute();
list = cli.FtSearch(idxName, "prefix*").Execute();
list = cli.FtSearch(idxName, "@title:prefix*").Execute();
list = cli.FtSearch(idxName, "*suffix").Execute();
list = cli.FtSearch(idxName, "*infix*").Execute();
list = cli.FtSearch(idxName, "%word%").Execute();
list = cli.FtSearch(idxName, "@views:[200 300]").Execute();
list = cli.FtSearch(idxName, "@views:[-inf 2000]").SortBy("views").Limit(0, 5).Execute();
list = cli.FtSearch(idxName, "@views:[(200 (300]").Execute();
list = cli.FtSearch(idxName, "@views>=200").Dialect(4).Execute();
list = cli.FtSearch(idxName, "@views:[200 +inf]").Execute();
list = cli.FtSearch(idxName, "@views<=300").Dialect(4).Execute();
list = cli.FtSearch(idxName, "@views:[-inf 300]").Execute();
list = cli.FtSearch(idxName, "@views==200").Dialect(4).Execute();
list = cli.FtSearch(idxName, "@views:[200 200]").Execute();
list = cli.FtSearch(idxName, "@views!=200").Dialect(4).Execute();
list = cli.FtSearch(idxName, "-@views:[200 200]").Execute();
list = cli.FtSearch(idxName, "@views==200 | @views==300").Dialect(4).Execute();
list = cli.FtSearch(idxName, "*").Filter("views", 200, 300).Dialect(4).Execute();
}
[Fact]
public void FtAggregate()
{
var idxName = Guid.NewGuid().ToString();
cli.FtCreate(idxName)
.On(IndexDataType.Hash)
.Prefix("blog:post:")
.AddTextField("title", weight: 5.0)
.AddTextField("content")
.AddTagField("author")
.AddNumericField("created_date", sortable: true)
.AddNumericField("views")
.Execute();
cli.HSet("blog:post:1", "title", "测试标题1 word", "content", "测试内容1suffix", "author", "作者1,作者2", "created_date", "10000", "views", 10);
cli.HSet("blog:post:2", "title", "prefix测试标题2", "content", "测试infix内容2", "author", "作者2,作者3", "created_date", "10001", "views", 201);
cli.HSet("blog:post:3", "title", "测试标题3 word", "content", "测试word内容3", "author", "作者2,作者5", "created_date", "10002", "views", 301);
var list = cli.FtAggregate(idxName, "word").Load("title", "author").Execute();
list = cli.FtAggregate(idxName, "@title:word").GroupBy("@title", "@views").Execute();
list = cli.FtAggregate(idxName, "*").GroupBy(["@title", "@views"], new AggregateReduce { Function = "SUM", Arguments = ["@views"], Alias = "sum1" }).Execute();
list = cli.FtAggregate(idxName, "*").Load("views").Apply("@views<200", "view_category").GroupBy(["@title"], new AggregateReduce { Function = "SUM", Arguments = ["@view_category"], Alias = "sum1" }).Execute();
}
[Fact]
public void FtCreate()
{
cli.FtCreate("idx1")
.On(IndexDataType.Hash)
.Prefix("blog:post:")
.AddTextField("title", weight: 5.0)
.AddTextField("content")
.AddTagField("author")
.AddNumericField("created_date", sortable: true)
.AddNumericField("views")
.Execute();
cli.FtCreate("idx2")
.On(IndexDataType.Hash)
.Prefix("book:details:")
.AddTextField("title")
.AddTagField("categories", separator: ";")
.Execute();
cli.FtCreate("idx3")
.On(IndexDataType.Hash)
.Prefix("blog:post:")
.AddTextField("sku", alias: "sku_text")
.AddTagField("sku", alias: "sku_tag", sortable: true)
.Execute();
cli.FtCreate("idx4")
.On(IndexDataType.Hash)
.Prefix("author:details:", "book:details:")
.AddTagField("author_id", sortable: true)
.AddTagField("author_ids")
.AddTextField("title")
.AddTextField("name")
.Execute();
cli.FtCreate("idx5")
.On(IndexDataType.Hash)
.Prefix("author:details")
.Filter("startswith(@name, 'G')")
.AddTextField("name")
.Execute();
cli.FtCreate("idx6")
.On(IndexDataType.Hash)
.Prefix("book:details")
.Filter("@subtitle != ''")
.AddTextField("title")
.Execute();
cli.FtCreate("idx7")
.On(IndexDataType.Json)
.Prefix("book:details")
.Filter("@subtitle != ''")
.AddTextField("$.title", alias: "title")
.AddTagField("$.categories", alias: "categories")
.Execute();
}
[Fact]
public void TestContactsUserIndex()
{
var repo = cli.FtDocumentRepository<ContactsUserIndex>();
//FT.SEARCH index_contacts "(@email:*wjx\\.cn*) (@companyid==10096)" dialect 4
var rt = repo.Search(@"(@email:*wjx\.cn*) (@companyid==10096)").Dialect(4).ToList();
var rt2 = repo.Search(a => a.UEmail.Contains("wjx.cn") && a.CompanyId == 10096).Dialect(4).ToList();
}
[FtDocument("index_contacts", Prefix = "contactsuser:")]
public class ContactsUserIndex
{
/// <summary>
/// 用户唯一编号
/// </summary>
[FtKey]
public long Id { get; set; }
/// <summary>
/// 用户编号
/// </summary>
[FtTextField("userid")]
public string UserId { get; set; }
/// <summary>
/// 用户姓名
/// </summary>
[FtTextField("name")]
public string Name { get; set; }
/// <summary>
/// 用户所属部门
/// </summary>
[FtTagField("department")]
public string Department { get; set; }
/// <summary>
/// 企业编号
/// </summary>
[FtNumericField("companyid")]
public int CompanyId { get; set; }
/// <summary>
/// 用户自定义标签
/// </summary>
[FtTagField("utags")]
public string UTags { get; set; }
/// <summary>
/// 添加时间
/// </summary>
[FtNumericField("addtime", Sortable = true)]
public long AddTime { get; set; }
/// <summary>
/// 更新时间
/// </summary>
[FtNumericField("updatetime")]
public long UpdateTime { get; set; }
/// <summary>
/// 手机号
/// </summary>
[FtTextField("umobile")]
public string UMobile { get; set; }
/// <summary>
/// 邮箱
/// </summary>
[FtTextField("uemail")]
public string UEmail { get; set; }
/// <summary>
/// 昵称
/// </summary>
[FtTextField("unickname")]
public string UNickname { get; set; }
/// <summary>
/// 生日
/// </summary>
[FtNumericField("ubirthday")]
public long UBirthday { get; set; }
[FtNumericField("lastmsgtime")]
public long LastMsgTime { get; set; }
[FtNumericField("lastjointime")]
public long LastJoinTime { get; set; }
/// <summary>
/// 用户信息标识位
/// </summary>
[FtNumericField("uinfomap")]
public long UInfoMap { get; set; }
}
}
}
|
2881099/FreeRedis | 4,663 | test/Unit/FreeRedis.Tests/RedisClientTests/AdapterTests/PipelineTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests.Other
{
public class PipelineTests : TestBase
{
[Fact]
public void StartPipe()
{
var key = Guid.NewGuid().ToString();
using (var pipe = cli.StartPipe())
{
pipe.IncrBy(key, 10);
pipe.Set("StartPipeTestSet_null", Null);
pipe.Get("StartPipeTestSet_null");
pipe.Set("StartPipeTestSet_string", String);
pipe.Get("StartPipeTestSet_string");
pipe.Set("StartPipeTestSet_bytes", Bytes);
pipe.Get<byte[]>("StartPipeTestSet_bytes");
pipe.Set("StartPipeTestSet_class", Class);
pipe.Get<TestClass>("StartPipeTestSet_class");
}
using (var pipe = cli.StartPipe())
{
pipe.IncrBy(key, 10);
pipe.Set("StartPipeTestSet_null", Null);
pipe.Get("StartPipeTestSet_null");
pipe.Set("StartPipeTestSet_string", String);
pipe.Get("StartPipeTestSet_string");
pipe.Set("StartPipeTestSet_bytes", Bytes);
pipe.Get<byte[]>("StartPipeTestSet_bytes");
pipe.Set("StartPipeTestSet_class", Class);
pipe.Get<TestClass>("StartPipeTestSet_class");
var ret = pipe.EndPipe();
Assert.Equal(10L, ret[0]);
Assert.Equal("", ret[2].ToString());
Assert.Equal(String, ret[4].ToString());
Assert.Equal(Bytes, ret[6]);
Assert.Equal(Class.ToString(), ret[8].ToString());
}
}
//[Fact]
//public void StartPipeAsync()
//{
// var key = Guid.NewGuid().ToString();
// using (var pipe = cli.StartPipe())
// {
// long t1 = 0;
// pipe.IncrByAsync(key, 10);
// pipe.SetAsync("StartPipeAsyncTestSet_null", Null);
// string t3 = "";
// pipe.GetAsync("StartPipeAsyncTestSet_null");
// pipe.SetAsync("StartPipeAsyncTestSet_string", String);
// string t4 = null;
// pipe.GetAsync("StartPipeAsyncTestSet_string");
// pipe.SetAsync("StartPipeAsyncTestSet_bytes", Bytes);
// byte[] t6 = null;
// pipe.GetAsync<byte[]>("StartPipeAsyncTestSet_bytes");
// pipe.SetAsync("StartPipeAsyncTestSet_class", Class);
// TestClass t8 = null;
// pipe.GetAsync<TestClass>("StartPipeAsyncTestSet_class");
// }
// using (var pipe = cli.StartPipe())
// {
// var tasks = new List<Task>();
// long t1 = 0;
// tasks.Add(pipe.IncrByAsync(key, 10).ContinueWith(t => t1 = t.Result));
// pipe.SetAsync("StartPipeAsyncTestSet_null", Null);
// string t3 = "";
// tasks.Add(pipe.GetAsync("StartPipeAsyncTestSet_null").ContinueWith(t => t3 = t.Result));
// pipe.SetAsync("StartPipeAsyncTestSet_string", String);
// string t4 = null;
// tasks.Add(pipe.GetAsync("StartPipeAsyncTestSet_string").ContinueWith(t => t4 = t.Result));
// pipe.SetAsync("StartPipeAsyncTestSet_bytes", Bytes);
// byte[] t6 = null;
// tasks.Add(pipe.GetAsync<byte[]>("StartPipeAsyncTestSet_bytes").ContinueWith(t => t6 = t.Result));
// pipe.SetAsync("StartPipeAsyncTestSet_class", Class);
// TestClass t8 = null;
// tasks.Add(pipe.GetAsync<TestClass>("StartPipeAsyncTestSet_class").ContinueWith(t => t8 = t.Result));
// var ret = pipe.EndPipe();
// Task.WaitAll(tasks.ToArray());
// Assert.Equal(10L, ret[0]);
// Assert.Equal("", ret[2].ToString());
// Assert.Equal(String, ret[4].ToString());
// Assert.Equal(Bytes, ret[6]);
// Assert.Equal(Class.ToString(), ret[8].ToString());
// Assert.Equal(10L, t1);
// Assert.Equal("", t3);
// Assert.Equal(String, t4);
// Assert.Equal(Bytes, t6);
// Assert.Equal(Class.ToString(), t8.ToString());
// }
//}
}
}
|
2881099/FreeRedis | 5,129 | test/Unit/FreeRedis.Tests/RedisClientTests/AdapterTests/TransactionTests.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace FreeRedis.Tests.RedisClientTests.Other
{
public class TransactionTests : TestBase
{
[Fact]
public void Multi()
{
using (var tran = cli.Multi())
{
tran.Discard();
}
var key = Guid.NewGuid().ToString();
using (var tran = cli.Multi())
{
tran.IncrBy(key, 10);
tran.Set("MultiTestSet_null", Null);
tran.Get("MultiTestSet_null");
tran.Set("MultiTestSet_string", String);
tran.Get("MultiTestSet_string");
tran.Set("MultiTestSet_bytes", Bytes);
tran.Get<byte[]>("MultiTestSet_bytes");
tran.Set("MultiTestSet_class", Class);
tran.Get<TestClass>("MultiTestSet_class");
tran.Discard();
}
using (var tran = cli.Multi())
{
tran.IncrBy(key, 10);
tran.Set("MultiTestSet_null", Null);
tran.Get("MultiTestSet_null");
tran.Set("MultiTestSet_string", String);
tran.Get("MultiTestSet_string");
tran.Set("MultiTestSet_bytes", Bytes);
tran.Get<byte[]>("MultiTestSet_bytes");
tran.Set("MultiTestSet_class", Class);
tran.Get<TestClass>("MultiTestSet_class");
var ret = tran.Exec();
Assert.Equal(10L, ret[0]);
Assert.Equal("", ret[2].ToString());
Assert.Equal(String, ret[4].ToString());
Assert.Equal(Bytes, ret[6]);
Assert.Equal(Class.ToString(), ret[8].ToString());
}
}
//[Fact]
//public void MultiAsync()
//{
// using (var tran = cli.Multi())
// {
// tran.Discard();
// }
// var key = Guid.NewGuid().ToString();
// using (var tran = cli.Multi())
// {
// long t1 = 0;
// tran.IncrByAsync(key, 10);
// tran.SetAsync("MultiAsyncTestSet_null", Null);
// string t3 = "";
// tran.GetAsync("MultiAsyncTestSet_null");
// tran.SetAsync("MultiAsyncTestSet_string", String);
// string t4 = null;
// tran.GetAsync("MultiAsyncTestSet_string");
// tran.SetAsync("MultiAsyncTestSet_bytes", Bytes);
// byte[] t6 = null;
// tran.GetAsync<byte[]>("TestSet_bytes");
// tran.SetAsync("MultiAsyncTestSet_class", Class);
// TestClass t8 = null;
// tran.GetAsync<TestClass>("MultiAsyncTestSet_class");
// tran.Discard();
// }
// using (var tran = cli.Multi())
// {
// var tasks = new List<Task>();
// long t1 = 0;
// tasks.Add(tran.IncrByAsync(key, 10).ContinueWith(t =>
// t1 = t.Result));
// tran.SetAsync("MultiAsyncTestSet_null", Null);
// string t3 = "";
// tasks.Add(tran.GetAsync("MultiAsyncTestSet_null").ContinueWith(t => t3 = t.Result));
// tran.SetAsync("MultiAsyncTestSet_string", String);
// string t4 = null;
// tasks.Add(tran.GetAsync("MultiAsyncTestSet_string").ContinueWith(t => t4 = t.Result));
// tran.SetAsync("MultiAsyncTestSet_bytes", Bytes);
// byte[] t6 = null;
// tasks.Add(tran.GetAsync<byte[]>("MultiAsyncTestSet_bytes").ContinueWith(t => t6 = t.Result));
// tran.SetAsync("MultiAsyncTestSet_class", Class);
// TestClass t8 = null;
// tasks.Add(tran.GetAsync<TestClass>("MultiAsyncTestSet_class").ContinueWith(t => t8 = t.Result));
// var ret = tran.Exec();
// Task.WaitAll(tasks.ToArray());
// Assert.Equal(10L, ret[0]);
// Assert.Equal("", ret[2].ToString());
// Assert.Equal(String, ret[4].ToString());
// Assert.Equal(Bytes, ret[6]);
// Assert.Equal(Class.ToString(), ret[8].ToString());
// Assert.Equal(10L, t1);
// Assert.Equal("", t3);
// Assert.Equal(String, t4);
// Assert.Equal(Bytes, t6);
// Assert.Equal(Class.ToString(), t8.ToString());
// }
//}
[Fact]
public void Discard()
{
}
[Fact]
public void Exec()
{
}
[Fact]
public void UnWatch()
{
}
[Fact]
public void Watch()
{
}
}
}
|
2881099/FreeRedis | 1,366 | examples/console_net8_norman/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
namespace console_net8_norman
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var r = new RedisClient(new ConnectionStringBuilder[] { "127.0.0.1:6379,database=1", "127.0.0.1:6379,database=2" }, default(Func<string,string>));
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
r.Notice += (s, e) => Console.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static void Main(string[] args)
{
//预热
cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, "我也不知道为什么刚刚好十五个字");
var val = cli.Get(tmp);
if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
}
stopwatch.Stop();
Console.WriteLine("FreeRedis:" + stopwatch.ElapsedMilliseconds);
}
static readonly string String = "我是中国人";
}
}
|
2881099/FreeRedis | 2,662 | examples/console_net8_cluster_client_side_caching/Program.cs | using FreeRedis;
using System.Diagnostics;
class Program
{
static RedisClient CreateRedisClient()
{
var cli = new RedisClient(new[] { (ConnectionStringBuilder)"192.168.164.10:6380,password=123456,min pool size=10" });
cli.UseClientSideCaching(new ClientSideCachingOptions
{
//本地缓存的容量
Capacity = 99999,
//过滤哪些键能被本地缓存
KeyFilter = key => true,
//检查长期未使用的缓存
CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(600)
});
return cli;
// redis6 cluster
// https://www.cnblogs.com/sharktech/p/14475748.html
// /redis6-cluster.sh
// ps -ef | grep redis
// redis-cli --cluster create 0.0.0.0:6379 0.0.0.0:6380 0.0.0.0:6381 0.0.0.0:6382 0.0.0.0:6383 0.0.0.0:6384 --cluster-replicas 1 -a 123456
}
static void Main(string[] args)
{
var testCount = 10;
Console.WriteLine($"测试 {testCount} 个 RedisClient Cluster 客户端缓存功能 client side cahcing");
Console.WriteLine($"正在创建 {testCount} 个 RedisCient 对象...\r\n");
var clis = new List<RedisClient>();
for(var a = 0; a < testCount; a++)
{
clis.Add(CreateRedisClient());
}
var key = Guid.NewGuid().ToString();
string value = null;
Console.WriteLine($"{clis.Count} 个 RedisClient 对象创建完成.\r\n");
Console.WriteLine($"【Esc】退出程序");
Console.WriteLine($"【Enter】对比 {clis.Count} 值同步");
Console.WriteLine($"【1】刷新新值\r\n");
Console.WriteLine($"本次测试 key: {key}\r\n\r\n");
while (true)
{
var readkey = Console.ReadKey().Key;
if (readkey == ConsoleKey.Escape) break;
if (readkey == ConsoleKey.Enter)
{
var sw = new Stopwatch();
sw.Reset();
sw.Start();
var equalsCounter = 0;
foreach (var cli in clis)
{
if (value == cli.Get(key)) equalsCounter++;
}
sw.Stop();
Console.WriteLine($"RedisClient[0..{clis.Count}] Get 新值比较,耗时 {sw.ElapsedMilliseconds}ms,相同 {equalsCounter},不相同 {(clis.Count - equalsCounter)}");
}
if (readkey == ConsoleKey.D1)
{
value = Guid.NewGuid().ToString();
clis[0].Set(key, value);
Console.WriteLine($"RedisClient[0] Set 新值已写入 {value}");
}
}
Console.WriteLine($"正在退出...");
foreach (var cli in clis) cli.Dispose();
Console.WriteLine($"退出成功.");
}
} |
2881099/FreeRedis | 1,601 | examples/console_net8_pooling/Program.cs | using FreeRedis;
using System;
using System.Threading;
namespace console_net8_pooling
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
//var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test
var r = new RedisClient("127.0.0.1:6379,database=10"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1");
//var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0
//r.Serialize = obj => JsonConvert.SerializeObject(obj);
//r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
//r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static void Main(string[] args)
{
//网络出错后,断熔,后台线程定时检查恢复
for (var k = 0; k < 1; k++)
{
new Thread(() =>
{
for (var a = 0; a < 10000; a++)
{
try
{
cli.Get(Guid.NewGuid().ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.CurrentThread.Join(100);
}
}).Start();
}
Console.ReadKey();
return;
}
}
}
|
2881099/FreeRedis | 10,307 | examples/console_net8/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace console_net8
{
class ResetCommandAop : IInterceptor
{
public void After(InterceptorAfterEventArgs args)
{
}
public void Before(InterceptorBeforeEventArgs args)
{
if (args.Command._command == "AUTH")
{
args.Command.Command("passwd");
}
}
}
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var r = new RedisClient("127.0.0.1:6379"); //redis 3.2 Single test
//r.Interceptors.Add(() => new ResetCommandAop());
//var r = new RedisClient("localhost:6379,database=9,password=123456"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1");
//var r = new RedisClient(new ConnectionStringBuilder[] { "192.168.164.10:6381,password=123456,subscribleReadBytes=true" }); //redis 7.0 cluster
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
r.Notice += (s, e) =>
{
Console.WriteLine(e.Log);
};
return r;
});
static RedisClient cli => _cliLazy.Value;
//static StackExchange.Redis.ConnectionMultiplexer seredis = StackExchange.Redis.ConnectionMultiplexer.Connect("127.0.0.1:6379");
//static StackExchange.Redis.IDatabase sedb = seredis.GetDatabase(1);
static void Main(string[] args)
{
var vs1 = cli.Get<string[]>("sdlfksdjf");
var vs2 = cli.Get<List<string>>("sdlfksdjf");
Console.WriteLine(typeof(GeoUnit).FromObject(null));
Console.WriteLine(typeof(GeoUnit).FromObject(""));
Console.WriteLine(typeof(GeoUnit).FromObject("ft"));
Console.WriteLine(Array.CreateInstance(typeof(GeoMember[]).GetElementType(), 0));
var redis = new RedisClient("127.0.0.1:6379,ssl=false");
foreach (var result1 in redis.SScan("tset1", "*", 100))
{
}
foreach (var result1 in redis.SScan<byte[]>("tset1", "*", 100))
{
}
foreach (var result1 in redis.HScan("thash", "*", 100))
{
}
foreach (var result1 in redis.HScan<byte[]>("thash", "*", 100))
{
}
redis.Get("xxx");
var result71 = cli.AclGetUser("sample");
void ondata(string channel, object data)
{
Console.WriteLine($"{channel} -> {data}");
}
using (cli.Subscribe("abc", ondata))
{
using (cli.Subscribe("abcc", ondata))
{
using (cli.PSubscribe("*", ondata))
{
Console.ReadKey();
}
Console.ReadKey();
}
Console.ReadKey();
}
Console.WriteLine("one more time");
//cli.SSubscribe("key1", (key, msg) =>
//{
// Console.WriteLine(key + ": " + msg);
//});
//cli.SSubscribe("key11", (key, msg) =>
//{
// Console.WriteLine(key + ": " + msg);
//});
//Console.ReadKey();
//cli.PubSubShardChannels("*");
//cli.SPublish("key11", "111");
//cli.SPublish("key1", "222");
var result7 = cli.AclGetUser("sample");
cli.Set("num", 10);
using (var tran = cli.Multi())
{
tran.Watch("num");
tran.IncrBy("num", 80);
tran.Exec();
}
var keys = cli.Scan(0, "*", 100, null);
Console.WriteLine(string.Join(",", keys.items));
foreach (var ks in cli.Scan("*", 3, null)) Console.WriteLine(string.Join(",", ks));
var hkeys = cli.HScan("key1", 0, "*", 100);
Console.WriteLine(string.Join(",", hkeys.items.Select(a => $"{a.Key}={a.Value}")));
foreach (var ks in cli.HScan("key1", "*", 3)) Console.WriteLine(string.Join(",", ks.Select(a => $"{a.Key}={a.Value}")));
var skeys = cli.SScan("skey1", 0, "*", 100);
Console.WriteLine(string.Join(",", skeys.items));
foreach (var ks in cli.SScan("skey1", "*", 3)) Console.WriteLine(string.Join(",", ks));
var zkeys = cli.ZScan("zkey1", 0, "*", 100);
Console.WriteLine(string.Join(",", zkeys.items.Select(a => $"{a.member}={a.score}")));
foreach (var ks in cli.ZScan("zkey1", "*", 3)) Console.WriteLine(string.Join(",", ks.Select(a => $"{a.member}={a.score}")));
cli.Ping();
var cmd = new CommandPacket("AUTH").Input("user1", "password1")
.Command("password");
for (var a = 0; a < 200; a++)
{
new Thread(() =>
{
while (true)
{
try
{
cli.Get("key" + a);
}
catch (Exception ex)
{
Trace.WriteLine($"线程{a}: [{DateTime.Now.ToString("HH:mm:ss")}] " + ex.ToString());
//Thread.CurrentThread.Join(30000);
}
Thread.CurrentThread.Join(100);
}
}).Start();
}
while(Console.ReadKey().Key != ConsoleKey.Escape)
{
}
cli.JsonSet("freedis.test",System.Text.Json.JsonSerializer.Serialize( new TestClass
{
Id = 1,
CreateTime = DateTime.Now,
Name = "张三",
TagId = new int[] { 1, 2, 3, 4 },
Deleted = true,
}));
var mem = cli.JsonStrAppend("freedis.test", "狂徒", "$.Name");
Console.WriteLine(JsonConvert.SerializeObject(mem));
var result =System.Text.Json.JsonSerializer.Deserialize<TestClass[]>( cli.JsonGet("freedis.test"));
Console.WriteLine(JsonConvert.SerializeObject(result));
//cli.SubscribeList("list01", msg =>
//{
// if (!string.IsNullOrEmpty(msg))
// Console.WriteLine("SubscribeList_list01: " + msg);
//});
//cli.SubscribeListBroadcast("list01", "client01", msg =>
//{
// if (!string.IsNullOrEmpty(msg))
// Console.WriteLine("SubscribeListBroadcast_client01_list01: " + msg);
//});
//cli.SubscribeListBroadcast("list01", "client01", msg =>
//{
// if (!string.IsNullOrEmpty(msg))
// Console.WriteLine("SubscribeListBroadcast_client01_list01: " + msg);
//});
//cli.SubscribeListBroadcast("list01", "client02", msg =>
//{
// if (!string.IsNullOrEmpty(msg))
// Console.WriteLine("SubscribeListBroadcast_client02_list01: " + msg);
//});
//Console.ReadKey();
//var info = cli.Info();
//var info1 = cli.Info("server");
//RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,database=2"));
//cli.Set("TestMGet_null1", String);
//RedisHelper.Set("TestMGet_null1", String);
//sedb.StringSet("TestMGet_string1", String);
//Stopwatch sw = new Stopwatch();
//sw.Start();
//cli.Set("TestMGet_string1", String);
//cli.Set("TestMGet_bytes1", Bytes);
//cli.Set("TestMGet_string2", String);
//cli.Set("TestMGet_bytes2", Bytes);
//cli.Set("TestMGet_string3", String);
//cli.Set("TestMGet_bytes3", Bytes);
//sw.Stop();
//Console.WriteLine("FreeRedis: " + sw.ElapsedMilliseconds + "ms");
//sw.Reset();
//sw.Start();
//cli.Set("TestMGet_string1", String);
//cli.Set("TestMGet_bytes1", Bytes);
//cli.Set("TestMGet_string2", String);
//cli.Set("TestMGet_bytes2", Bytes);
//cli.Set("TestMGet_string3", String);
//cli.Set("TestMGet_bytes3", Bytes);
//sw.Stop();
//Console.WriteLine("FreeRedis: " + sw.ElapsedMilliseconds + "ms");
//sw.Reset();
//sw.Start();
//RedisHelper.Set("TestMGet_string1", String);
//RedisHelper.Set("TestMGet_bytes1", Bytes);
//RedisHelper.Set("TestMGet_string2", String);
//RedisHelper.Set("TestMGet_bytes2", Bytes);
//RedisHelper.Set("TestMGet_string3", String);
//RedisHelper.Set("TestMGet_bytes3", Bytes);
//sw.Stop();
//Console.WriteLine("CSRedisCore: " + sw.ElapsedMilliseconds + "ms");
//sw.Reset();
//sw.Start();
//sedb.StringSet("TestMGet_string1", String);
//sedb.StringSet("TestMGet_bytes1", Bytes);
//sedb.StringSet("TestMGet_string2", String);
//sedb.StringSet("TestMGet_bytes2", Bytes);
//sedb.StringSet("TestMGet_string3", String);
//sedb.StringSet("TestMGet_bytes3", Bytes);
//sw.Stop();
//Console.WriteLine("StackExchange: " + sw.ElapsedMilliseconds + "ms");
}
static readonly string String = "我是中国人";
static readonly byte[] Bytes = Encoding.UTF8.GetBytes("这是一个byte字节");
}
public class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
public int[] TagId { get; set; }
public bool Deleted { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
|
2881099/FreeRedis | 2,128 | examples/console_net8_sentinel/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Threading;
namespace console_net8_sentinel
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var r = new RedisClient("mymaster,database=3", new[] { "127.0.0.1:26379", "127.0.0.1:26479", "127.0.0.1:26579" }, true);
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
r.Notice += (s, e) => Console.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static void Main(string[] args)
{
while (Console.ReadKey().Key == ConsoleKey.Enter)
{
try
{
cli.Get(Guid.NewGuid().ToString());
cli.Set(Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return;
for (var k = 0; k < 1; k++)
{
new Thread(() =>
{
for (var a = 0; a < 10000; a++)
{
try
{
cli.Get(Guid.NewGuid().ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Thread.CurrentThread.Join(100);
}
}).Start();
}
Console.ReadKey();
return;
}
}
public class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
public int[] TagId { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
|
2881099/FreeRedis | 2,890 | examples/console_net452_vs/console_net452_vs.csproj | <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{7AC68251-83D4-423F-849C-04BD89F4BDFB}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>console_net452_vs</RootNamespace>
<AssemblyName>console_net452_vs</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CSRedisCore">
<Version>3.8.800</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>13.0.1</Version>
</PackageReference>
<PackageReference Include="StackExchange.Redis">
<Version>1.2.6</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\FreeRedis\FreeRedis.csproj">
<Project>{b07c7025-4191-4243-a6ab-34b5be539450}</Project>
<Name>FreeRedis</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project> |
2881099/FreeRedis | 13,190 | examples/console_net452_vs/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace console_net452_vs
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
//var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test
var r = new RedisClient("127.0.0.1:6379,max pool size=500,retry=1"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1");
//var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
//r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static StackExchange.Redis.ConnectionMultiplexer seredis = StackExchange.Redis.ConnectionMultiplexer.Connect("127.0.0.1:6379");
static StackExchange.Redis.IDatabase sedb = seredis.GetDatabase(1);
static void Main(string[] args)
{
RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
cli.Set("TestMGet_null1", "");
RedisHelper.Set("TestMGet_null1", "");
sedb.StringSet("TestMGet_string1", String);
ThreadPool.SetMinThreads(10001, 10001);
Stopwatch sw = new Stopwatch();
var tasks = new List<Task>();
var results = new ConcurrentQueue<string>();
cli.FlushDb();
while (results.TryDequeue(out var del)) ;
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await cli.SetAsync(tmp, String);
var val = await cli.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
//FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
//FreeRedis.Internal.AsyncRedisSocket.sw.Start();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await cli.SetAsync(tmp, String);
var val = await cli.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
//var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
//sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
using (var pipe = cli.StartPipe())
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
pipe.Set(tmp, String);
var val = pipe.Get(tmp);
}
var vals = pipe.EndPipe();
for (var a = 1; a < 200000; a += 2)
{
var val = vals[a].ToString();
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}
sw.Stop();
Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
// cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
//sw.Stop();
//Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
//{
// using (var rds = cli.GetTestRedisSocket())
// {
// var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
// rds.Write(cmd);
// cmd.Read<string>();
// }
//}
//sw.Stop();
//Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
//if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
}
static readonly string String = "我是中国人";
}
}
|
2881099/FreeRedis | 1,110 | examples/OpenTelemetryTest/OpenTelemetryTest.csproj | <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.9.0" />
<PackageReference Include="OpenTelemetry" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\FreeRedis.OpenTelemetry\FreeRedis.OpenTelemetry.csproj" />
<ProjectReference Include="..\..\src\FreeRedis\FreeRedis.csproj" />
</ItemGroup>
</Project>
|
2881099/FreeRedis | 1,895 | examples/OpenTelemetryTest/Program.cs | using FreeRedis;
using FreeRedis.OpenTelemetry;
using Microsoft.Extensions.DependencyInjection.Extensions;
using OpenTelemetry.Exporter;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var services = builder.Services;
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//redis
var redisClient = new RedisClient(builder.Configuration.GetConnectionString("Redis"));
redisClient.Serialize = obj => System.Text.Json.JsonSerializer.Serialize(obj);
redisClient.Deserialize = (json, type) => System.Text.Json.JsonSerializer.Deserialize(json, type);
//redisClient.Notice += (s, e) =>
//{
// Console.WriteLine(e.Log);
//};
services.TryAddSingleton<IRedisClient>(redisClient);
//OpenTelemetry
var otel = services.AddOpenTelemetry();
otel.ConfigureResource(resource =>
{
resource.AddTelemetrySdk();
resource.AddEnvironmentVariableDetector();
resource.AddService("FreeRedisTest");
});
var otlpUrl = builder.Configuration["OpenTelemetry:OtlpHttpUrl"];
otel.WithTracing(tracing => tracing.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddFreeRedisInstrumentation(redisClient)
.SetSampler(new AlwaysOnSampler())
//.AddConsoleExporter()
.AddOtlpExporter(otlpOptions =>
{
otlpOptions.Endpoint = new Uri($"http://{otlpUrl}/v1/traces");
otlpOptions.Protocol = OtlpExportProtocol.HttpProtobuf;
otlpOptions.Headers = "Authorization=Basic YWRtaW46dGVzdEAxMjM=";
})
);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run(); |
2881099/FreeRedis | 4,678 | examples/console_net8_client_side_caching/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Globalization;
using System.Threading;
namespace console_net8_client_side_caching
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var r = new RedisClient("127.0.0.1:6379"); //redis 3.2 Single test
//var r = new RedisClient("192.168.164.10:6379"); //redis 3.2 Single test
//var r = new RedisClient("127.0.0.1:6379,database=1,min pool size=500,max pool size=500"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=10", "127.0.0.1:6380,database=10", "127.0.0.1:6381,database=10");
//var r = new RedisClient(new [] { (ConnectionStringBuilder)"192.168.164.10:6379,database=1", (ConnectionStringBuilder)"192.168.164.10:6379,database=2" }); //redis 6.0
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
r.Notice += (s, e) => Console.WriteLine(e.Log);
return r;
// redis6 cluster
// https://www.cnblogs.com/sharktech/p/14475748.html
// /redis6-cluster.sh
// ps -ef | grep redis
// redis-cli --cluster create 0.0.0.0:6379 0.0.0.0:6380 0.0.0.0:6381 0.0.0.0:6382 0.0.0.0:6383 0.0.0.0:6384 --cluster-replicas 1 -a 123456
});
static RedisClient cli => _cliLazy.Value;
static void Main(string[] args)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("nb");
var test = long.Parse("-1");
cli.Notice += (s, e) =>
{
if (e.NoticeType == NoticeType.Event && e.Log == "ClientSideCaching:InValidate")
{
var keys = e.Tag as string[];
}
};
cli.UseClientSideCaching(new ClientSideCachingOptions
{
//本地缓存的容量
Capacity = 3,
//过滤哪些键能被本地缓存
//KeyFilter = key => key.StartsWith("Interceptor"),
//检查长期未使用的缓存
CheckExpired = (key, dt) => DateTime.Now.Subtract(dt) > TimeSpan.FromSeconds(600)
});
while (Console.ReadKey().Key != ConsoleKey.Escape)
{
Console.WriteLine(cli.HGetAll("hash01"));
Console.WriteLine(cli.HGet("hash01", "f3"));
Console.WriteLine(cli.HMGet("hash01", "f3", "f2"));
}
cli.Set("Interceptor01", "123123"); //redis-server
var val1 = cli.Get("Interceptor01"); //redis-server
var val2 = cli.Get("Interceptor01"); //本地
var val3 = cli.Get("Interceptor01"); //断点等3秒,redis-server
cli.Set("Interceptor01", "234567"); //redis-server
var val4 = cli.Get("Interceptor01"); //redis-server
var val5 = cli.Get("Interceptor01"); //本地
var val6 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //redis-server
var val7 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地
var val8 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地
cli.MSet("Interceptor01", "Interceptor01Value", "Interceptor02", "Interceptor02Value", "Interceptor03", "Interceptor03Value"); //redis-server
var val9 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //redis-server
var val10 = cli.MGet("Interceptor01", "Interceptor02", "Interceptor03"); //本地
//以下 KeyFilter 返回 false,从而不使用本地缓存
cli.Set("123Interceptor01", "123123"); //redis-server
var val11 = cli.Get("123Interceptor01"); //redis-server
var val12 = cli.Get("123Interceptor01"); //redis-server
var val23 = cli.Get("123Interceptor01"); //redis-server
cli.Set("Interceptor011", Class); //redis-server
var val0111 = cli.Get<TestClass>("Interceptor011"); //redis-server
var val0112 = cli.Get<TestClass>("Interceptor011"); //本地
var val0113 = cli.Get<TestClass>("Interceptor011"); //断点等3秒,redis-server
Console.WriteLine("all test has done running");
Console.ReadKey();
cli.Dispose();
}
static readonly TestClass Class = new TestClass { Id = 1, Name = "Class名称", CreateTime = DateTime.Now, TagId = new[] { 1, 3, 3, 3, 3 } };
}
public class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
public int[] TagId { get; set; }
}
}
|
2881099/FreeRedis | 3,308 | examples/console_net8_cluster/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Diagnostics;
namespace console_net8_cluster
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
var r = new RedisClient(new ConnectionStringBuilder[] { "127.0.0.1:6379", "127.0.0.1:6380" });
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
//r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static CSRedis.CSRedisClient csredis = new CSRedis.CSRedisClient("127.0.0.1:6379");
static ConnectionMultiplexer seredis = ConnectionMultiplexer.Connect("127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381");
static IDatabase sedb => seredis.GetDatabase();
static void Main(string[] args)
{
var tblv1 = cli.BLPop("testblist01", 5);
var tblv2 = cli.BLPop("testblist02", 5);
var tblv3 = cli.BLPop("testblist03", 5);
cli.LPush("testblist01", "value1");
tblv1 = cli.BLPop("testblist01", 5);
cli.LPush("testblist02", "value2");
tblv2 = cli.BLPop("testblist02", 5);
cli.LPush("testblist03", "value3");
tblv3 = cli.BLPop("testblist03", 5);
//预热
cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
sedb.StringSet(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, "我也不知道为什么刚刚好十五个字");
var val = cli.Get(tmp);
if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
}
stopwatch.Stop();
Console.WriteLine("FreeRedis:"+stopwatch.ElapsedMilliseconds);
//stopwatch.Restart();
// csredis 会出现连接不能打开的情况
//for (int i = 0; i < 100; i++)
//{
// var tmp = Guid.NewGuid().ToString();
// csredis.Set(tmp, "我也不知道为什么刚刚好十五个字");
// _ = csredis.Get(tmp);
//}
//stopwatch.Stop();
//Console.WriteLine("csredis:" + stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
for (int i = 0; i < 10000; i++)
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, "我也不知道为什么刚刚好十五个字");
var val = sedb.StringGet(tmp);
if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
}
stopwatch.Stop();
Console.WriteLine("Seredis:" + stopwatch.ElapsedMilliseconds);
cli.Subscribe("abc", (chan, msg) =>
{
Console.WriteLine($"FreeRedis {chan} => {msg}");
});
seredis.GetSubscriber().Subscribe("abc", (chan, msg) =>
{
Console.WriteLine($"Seredis {chan} => {msg}");
});
Console.ReadKey();
return;
}
}
}
|
2881099/FreeRedis | 14,550 | examples/console_net8_vs/Program.cs | using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace console_net8_vs
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
//var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test
var r = new RedisClient("127.0.0.1:6379,min pool size=500,max pool size=500"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1");
//var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
//r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static StackExchange.Redis.ConnectionMultiplexer seredis = StackExchange.Redis.ConnectionMultiplexer.Connect("127.0.0.1:6379");
static StackExchange.Redis.IDatabase sedb = seredis.GetDatabase(1);
static void Main(string[] args)
{
sedb.StringSet("key1", (string)null);
var val111 = sedb.StringGet("key1");
RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
cli.Set("TestMGet_null1", "");
RedisHelper.Set("TestMGet_null1", "");
sedb.StringSet("TestMGet_string1", String);
ThreadPool.SetMinThreads(10001, 10001);
Stopwatch sw = new Stopwatch();
var tasks = new List<Task>();
var results = new ConcurrentQueue<string>();
cli.FlushDb();
results.Clear();
sw.Reset();
sw.Start();
for (var a = 0; a < 10000; a++)
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("StackExchange(0-10000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
//sw.Reset();
//sw.Start();
//tasks = new List<Task>();
//for (var a = 0; a < 100000; a++)
//{
// tasks.Add(Task.Run(() =>
// {
// var tmp = Guid.NewGuid().ToString();
// sedb.StringSet(tmp, String);
// var val = sedb.StringGet(tmp);
// if (val != String) throw new Exception("not equal");
// results.Enqueue(val);
// }));
//}
//Task.WaitAll(tasks.ToArray());
//sw.Stop();
//Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
//tasks.Clear();
//results.Clear();
//cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 10000; a++)
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("StackExchangeAsync(0-10000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 10000; a++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("FreeRedisSync(0-10000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("FreeRedisSync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 10000; a++)
{
var tmp = Guid.NewGuid().ToString();
await cli.SetAsync(tmp, String);
var val = await cli.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("FreeRedisAsync(0-10000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await cli.SetAsync(tmp, String);
var val = await cli.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
return;
//sw.Reset();
//sw.Start();
//Task.Run(async () =>
//{
// for (var a = 0; a < 100000; a++)
// {
// var tmp = Guid.NewGuid().ToString();
// await cli.SetAsync(tmp, String);
// var val = await cli.GetAsync(tmp);
// if (val != String) throw new Exception("not equal");
// results.Enqueue(val);
// }
//}).Wait();
//sw.Stop();
//Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
//tasks.Clear();
//results.Clear();
//cli.FlushDb();
//FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
//FreeRedis.Internal.AsyncRedisSocket.sw.Start();
//sw.Reset();
//sw.Start();
//tasks = new List<Task>();
//for (var a = 0; a < 100000; a++)
//{
// tasks.Add(Task.Run(async () =>
// {
// var tmp = Guid.NewGuid().ToString();
// await cli.SetAsync(tmp, String);
// var val = await cli.GetAsync(tmp);
// if (val != String) throw new Exception("not equal");
// results.Enqueue(val);
// }));
//}
//Task.WaitAll(tasks.ToArray());
//sw.Stop();
////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
//Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
//tasks.Clear();
//results.Clear();
//cli.FlushDb();
sw.Reset();
sw.Start();
using (var pipe = cli.StartPipe())
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
pipe.Set(tmp, String);
var val = pipe.Get(tmp);
}
var vals = pipe.EndPipe();
for (var a = 1; a < 200000; a += 2)
{
var val = vals[a].ToString();
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}
sw.Stop();
Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
results.Clear();
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
// cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
//sw.Stop();
//Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
results.Clear();
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
//{
// using (var rds = cli.GetTestRedisSocket())
// {
// var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
// rds.Write(cmd);
// cmd.Read<string>();
// }
//}
//sw.Stop();
//Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
//if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
results.Clear();
cli.FlushDb();
}
static readonly string String = "我是中国人";
}
}
|
2881099/FreeRedis | 2,599 | examples/console_net8_benchmark/Program.cs | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using FreeRedis;
using Newtonsoft.Json;
using System;
using System.Text;
namespace console_net8_benchmark
{
public class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
//var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test
var r = new RedisClient("127.0.0.1:6379,database=1,poolsize=100,min pool size=100"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1");
//var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0
r.Serialize = obj => JsonConvert.SerializeObject(obj);
r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
//r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static CSRedis.CSRedisClient csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,database=2,poolsize=100");
static StackExchange.Redis.ConnectionMultiplexer seredis = StackExchange.Redis.ConnectionMultiplexer.Connect("127.0.0.1:6379");
static StackExchange.Redis.IDatabase sedb = seredis.GetDatabase(1);
public static void Main(string[] args)
{
RedisHelper.Initialization(csredis);
cli.Set("TestMGet_string1", String);
RedisHelper.Set("TestMGet_string1", String);
sedb.StringSet("TestMGet_string1", String);
var summary = BenchmarkRunner.Run<SetVs>();
}
public class SetVs
{
[Benchmark]
public void FreeRedis()
{
//cli.Set("TestMGet_string1", String);
cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
}
[Benchmark]
public void CSRedisCore()
{
csredis.Set("TestMGet_string1", String);
}
[Benchmark]
public void StackExchange()
{
sedb.StringSet("TestMGet_string1", String);
}
}
static readonly string String = "我是中国人";
}
public class TestClass
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime CreateTime { get; set; }
public int[] TagId { get; set; }
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
}
|
2881099/FreeRedis | 2,231 | examples/console_net8_pubsub/Program.cs | using FreeRedis;
using System;
namespace console_net8
{
class Program
{
static Lazy<RedisClient> _cliLazy = new Lazy<RedisClient>(() =>
{
//var r = new RedisClient("127.0.0.1:6379", false); //redis 3.2 Single test
var r = new RedisClient("127.0.0.1:6379,database=10"); //redis 3.2
//var r = new RedisClient("127.0.0.1:6379,database=1", "127.0.0.1:6379,database=1");
//var r = new RedisClient("192.168.164.10:6379,database=1"); //redis 6.0
//r.Serialize = obj => JsonConvert.SerializeObject(obj);
//r.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
//r.Notice += (s, e) => Trace.WriteLine(e.Log);
return r;
});
static RedisClient cli => _cliLazy.Value;
static void Main(string[] args)
{
using (var local = cli.GetDatabase())
{
var r1 = local.Call(new CommandPacket("Subscribe").Input("abc"));
var r2 = local.Ping();
var r3 = local.Ping("testping123");
//var r4 = local.Call(new CommandPacket("punSubscribe").Input("*"));
}
using (cli.Subscribe("abc", ondata))
{
using (cli.Subscribe("abcc", ondata))
{
using (cli.PSubscribe("*", ondata))
{
Console.ReadKey();
}
Console.ReadKey();
}
Console.ReadKey();
}
Console.WriteLine("one more time");
Console.ReadKey();
using (cli.Subscribe("abc", ondata))
{
using (cli.Subscribe("abcc", ondata))
{
using (cli.PSubscribe("*", ondata))
{
Console.ReadKey();
}
Console.ReadKey();
}
Console.ReadKey();
}
void ondata(string channel, object data)
{
Console.WriteLine($"{channel} -> {data}");
}
//return;
}
}
}
|
2881099/FreeRedis | 949 | examples/console_net452_vs/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("console_net452_vs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("console_net452_vs")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7ac68251-83d4-423f-849c-04bd89f4bdfb")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
2881099/FreeRedis | 1,623 | examples/OpenTelemetryTest/Controllers/WeatherForecastController.cs | using FreeRedis;
using Microsoft.AspNetCore.Mvc;
namespace OpenTelemetryTest.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly IRedisClient _redisClient;
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IRedisClient redisClient)
{
_logger = logger;
_redisClient = redisClient;
}
[HttpGet(Name = "GetWeatherForecast")]
public async Task<IEnumerable<WeatherForecast>> Get()
{
var response = Enumerable.Range(1, 20).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
}).ToArray();
await _redisClient.SetAsync("test01", response, 60 * 5);
await _redisClient.GetAsync("test01");
var cache = response.GroupBy(x => x.Summary).ToDictionary(g => g.Key!, g => g.ToList());
await _redisClient.MSetAsync(cache);
var cache1 = await _redisClient.GetAsync<List<WeatherForecast>>(Summaries[Random.Shared.Next(Summaries.Length)]);
return response;
}
}
}
|
2881099/FreeRedis | 2,232 | src/FreeRedis.DistributedCache/FreeRedis.DistributedCache.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net80;net70;net60;net50;netcoreapp31</TargetFrameworks>
<AssemblyName>FreeRedis.DistributedCache</AssemblyName>
<PackageId>FreeRedis.DistributedCache</PackageId>
<RootNamespace>FreeRedis.DistributedCache</RootNamespace>
<Version>1.5.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageProjectUrl>https://github.com/2881099/FreeRedis</PackageProjectUrl>
<Description>分布式缓存 FreeRedis 实现 Microsoft.Extensions.Caching</Description>
<RepositoryUrl>https://github.com/2881099/FreeRedis</RepositoryUrl>
<PackageTags>caching freeredis redis c# 分布式缓存 集群 负载 cluster Microsoft.Extensions.Caching</PackageTags>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
<DelaySign>false</DelaySign>
<PackageReadmeFile>readme.md</PackageReadmeFile>
</PropertyGroup>
<ItemGroup>
<None Include="../../readme.md" Pack="true" PackagePath="\"/>
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>bin\Debug\netstandard2.0\Caching.CSRedis.xml</DocumentationFile>
<WarningLevel>3</WarningLevel>
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net80' or '$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="8.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net70'">
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="7.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net60'">
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net50'">
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netcoreapp31'">
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="3.1.10" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FreeRedis\FreeRedis.csproj" />
</ItemGroup>
</Project>
|
2881099/FreeRedis | 11,964 | src/FreeRedis.DistributedCache/FreeRedisCache.cs | using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;
namespace FreeRedis
{
public class DistributedCache : IDistributedCache
{
private RedisClient _redisClient;
public DistributedCache(RedisClient redisClient)
{
_redisClient = redisClient;
}
// KEYS[1] = = key
// ARGV[1] = absolute-expiration - ticks as long (-1 for none)
// ARGV[2] = sliding-expiration - ticks as long (-1 for none)
// ARGV[3] = relative-expiration (long, in seconds, -1 for none) - Min(absolute-expiration - Now, sliding-expiration)
// ARGV[4] = data - byte[]
// this order should not change LUA script depends on it
private const string SetScript = (@"
redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
if ARGV[3] ~= '-1' then
redis.call('EXPIRE', KEYS[1], ARGV[3])
end
return 1");
private const string AbsoluteExpirationKey = "absexp";
private const string SlidingExpirationKey = "sldexp";
private const string DataKey = "data";
private const long NotPresent = -1;
private static readonly string[] _hashMembersAbsoluteExpirationSlidingExpirationData = new string[] { AbsoluteExpirationKey, SlidingExpirationKey, DataKey };
private static readonly string[] _hashMembersAbsoluteExpirationSlidingExpiration = new string[] { AbsoluteExpirationKey, SlidingExpirationKey };
public byte[] Get(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return GetAndRefresh(key, getData: true);
}
public async Task<byte[]> GetAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
return await GetAndRefreshAsync(key, getData: true, token: token);
}
public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
var creationTime = DateTimeOffset.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
_redisClient.Eval(SetScript, new[] { key },
new object[]
{
absoluteExpiration?.Ticks ?? NotPresent,
options.SlidingExpiration?.Ticks ?? NotPresent,
GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
value
});
}
public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
token.ThrowIfCancellationRequested();
var creationTime = DateTimeOffset.UtcNow;
var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);
await _redisClient.EvalAsync(SetScript, new[] { key },
new object[]
{
absoluteExpiration?.Ticks ?? NotPresent,
options.SlidingExpiration?.Ticks ?? NotPresent,
GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
value
});
}
public void Refresh(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
GetAndRefresh(key, getData: false);
}
public async Task RefreshAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
await GetAndRefreshAsync(key, getData: false, token: token);
}
private static string[] GetHashFields(bool getData)
{
return getData
? _hashMembersAbsoluteExpirationSlidingExpirationData
: _hashMembersAbsoluteExpirationSlidingExpiration;
}
private byte[] GetAndRefresh(string key, bool getData)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
// This also resets the LRU status as desired.
// TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
var results = _redisClient.HMGet<byte[]>(key, GetHashFields(getData));
// TODO: Error handling
if (results.Length >= 2)
{
MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
Refresh(key, absExpr, sldExpr);
}
return results.Length >= 3 ? results[2] : null;
}
private async Task<byte[]> GetAndRefreshAsync(string key, bool getData, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
// This also resets the LRU status as desired.
// TODO: Can this be done in one operation on the server side? Probably, the trick would just be the DateTimeOffset math.
var results = await _redisClient.HMGetAsync<byte[]>(key, GetHashFields(getData));
// TODO: Error handling
if (results.Length >= 2)
{
MapMetadata(results, out DateTimeOffset? absExpr, out TimeSpan? sldExpr);
await RefreshAsync(key, absExpr, sldExpr, token);
}
return results.Length >= 3 ? results[2] : null;
}
public void Remove(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_redisClient.Del(key.Split('|'));
// TODO: Error handling
}
public async Task RemoveAsync(string key, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
await _redisClient.DelAsync(key.Split('|'));
// TODO: Error handling
}
private void MapMetadata(byte[][] results, out DateTimeOffset? absoluteExpiration, out TimeSpan? slidingExpiration)
{
absoluteExpiration = null;
slidingExpiration = null;
var absoluteExpirationStr = results[0] == null ? null : Encoding.UTF8.GetString(results[0]);
if (long.TryParse(absoluteExpirationStr, out var absoluteExpirationTicks) && absoluteExpirationTicks != NotPresent)
{
absoluteExpiration = new DateTimeOffset(absoluteExpirationTicks, TimeSpan.Zero);
}
var slidingExpirationStr = results[1] == null ? null : Encoding.UTF8.GetString(results[1]);
if (long.TryParse(slidingExpirationStr, out var slidingExpirationTicks) && slidingExpirationTicks != NotPresent)
{
slidingExpiration = new TimeSpan(slidingExpirationTicks);
}
}
private void Refresh(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
// Note Refresh has no effect if there is just an absolute expiration (or neither).
if (sldExpr.HasValue)
{
TimeSpan? expr;
if (absExpr.HasValue)
{
var relExpr = absExpr.Value - DateTimeOffset.Now;
expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
}
else
{
expr = sldExpr;
}
_redisClient.Expire(key, expr ?? TimeSpan.Zero);
// TODO: Error handling
}
}
private async Task RefreshAsync(string key, DateTimeOffset? absExpr, TimeSpan? sldExpr, CancellationToken token = default(CancellationToken))
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
token.ThrowIfCancellationRequested();
// Note Refresh has no effect if there is just an absolute expiration (or neither).
if (sldExpr.HasValue)
{
TimeSpan? expr;
if (absExpr.HasValue)
{
var relExpr = absExpr.Value - DateTimeOffset.Now;
expr = relExpr <= sldExpr.Value ? relExpr : sldExpr;
}
else
{
expr = sldExpr;
}
await _redisClient.ExpireAsync(key, (int)(expr ?? TimeSpan.Zero).TotalSeconds);
// TODO: Error handling
}
}
private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset? absoluteExpiration, DistributedCacheEntryOptions options)
{
if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue)
{
return (long)Math.Min(
(absoluteExpiration.Value - creationTime).TotalSeconds,
options.SlidingExpiration.Value.TotalSeconds);
}
else if (absoluteExpiration.HasValue)
{
return (long)(absoluteExpiration.Value - creationTime).TotalSeconds;
}
else if (options.SlidingExpiration.HasValue)
{
return (long)options.SlidingExpiration.Value.TotalSeconds;
}
return null;
}
private static DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset creationTime, DistributedCacheEntryOptions options)
{
if (options.AbsoluteExpiration.HasValue && options.AbsoluteExpiration <= creationTime)
{
#pragma warning disable CA2208
throw new ArgumentOutOfRangeException(
nameof(DistributedCacheEntryOptions.AbsoluteExpiration),
options.AbsoluteExpiration.Value,
"The absolute expiration value must be in the future.");
#pragma warning restore CA2208
}
var absoluteExpiration = options.AbsoluteExpiration;
if (options.AbsoluteExpirationRelativeToNow.HasValue)
{
absoluteExpiration = creationTime + options.AbsoluteExpirationRelativeToNow;
}
return absoluteExpiration;
}
}
} |
2881099/FreeRedis | 3,075 | src/FreeRedis.OpenTelemetry/DiagnosticSourceSubscriber.cs | using System;
using System.Collections.Generic;
using System.Threading;
namespace FreeRedis.OpenTelemetry
{
public class DiagnosticSourceSubscriber : IDisposable, IObserver<System.Diagnostics.DiagnosticListener>
{
private readonly Func<System.Diagnostics.DiagnosticListener, bool> _diagnosticSourceFilter;
private readonly Func<string, DiagnosticListener> _handlerFactory;
private readonly Func<string, object?, object?, bool>? _isEnabledFilter;
private readonly List<IDisposable> _listenerSubscriptions;
private IDisposable? _allSourcesSubscription;
private long _disposed;
public DiagnosticSourceSubscriber(
DiagnosticListener handler,
Func<string, object?, object?, bool>? isEnabledFilter)
: this(_ => handler,
value => FreeRedisDiagnosticListenerNames.DiagnosticListenerName == value.Name,
isEnabledFilter)
{
}
public DiagnosticSourceSubscriber(
Func<string, DiagnosticListener> handlerFactory,
Func<System.Diagnostics.DiagnosticListener, bool> diagnosticSourceFilter,
Func<string, object?, object?, bool>? isEnabledFilter)
{
_listenerSubscriptions = new List<IDisposable>();
_handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory));
_diagnosticSourceFilter = diagnosticSourceFilter;
_isEnabledFilter = isEnabledFilter;
}
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void OnNext(System.Diagnostics.DiagnosticListener value)
{
if (Interlocked.Read(ref _disposed) == 0 && _diagnosticSourceFilter(value))
{
var handler = _handlerFactory(value.Name);
var subscription = _isEnabledFilter == null
? value.Subscribe(handler)
: value.Subscribe(handler, _isEnabledFilter);
lock (_listenerSubscriptions)
{
_listenerSubscriptions.Add(subscription);
}
}
}
public void OnCompleted()
{
}
public void OnError(Exception error)
{
}
public void Subscribe()
{
_allSourcesSubscription ??= System.Diagnostics.DiagnosticListener.AllListeners.Subscribe(this);
}
protected virtual void Dispose(bool disposing)
{
if (Interlocked.CompareExchange(ref _disposed, 1, 0) == 1) return;
lock (_listenerSubscriptions)
{
foreach (var listenerSubscription in _listenerSubscriptions)
{
listenerSubscription?.Dispose();
}
_listenerSubscriptions.Clear();
}
_allSourcesSubscription?.Dispose();
_allSourcesSubscription = null;
}
}
} |
2881099/FreeRedis | 1,317 | src/FreeRedis.OpenTelemetry/FreeRedis.OpenTelemetry.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net80</TargetFrameworks>
<AssemblyName>FreeRedis.OpenTelemetry</AssemblyName>
<PackageId>FreeRedis.OpenTelemetry</PackageId>
<RootNamespace>FreeRedis.OpenTelemetry</RootNamespace>
<Version>1.5.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageProjectUrl>https://github.com/2881099/FreeRedis</PackageProjectUrl>
<RepositoryUrl>https://github.com/2881099/FreeRedis</RepositoryUrl>
<PackageTags>FreeRedis redis-trib cluster rediscluster sentinel OpenTelemetry</PackageTags>
<RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Title>$(AssemblyName)</Title>
<IsPackable>true</IsPackable>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<WarningLevel>3</WarningLevel>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
<DelaySign>false</DelaySign>
<PackageReadmeFile>readme.md</PackageReadmeFile>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="OpenTelemetry" Version="1.9.0" />
</ItemGroup>
<ItemGroup>
<None Include="../../readme.md" Pack="true" PackagePath="\"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FreeRedis\FreeRedis.csproj" />
</ItemGroup>
</Project> |
2881099/FreeRedis | 3,903 | src/FreeRedis.OpenTelemetry/DiagnosticListener.cs | using OpenTelemetry.Trace;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace FreeRedis.OpenTelemetry
{
public class DiagnosticListener : IObserver<KeyValuePair<string, object?>>
{
public const string SourceName = "FreeRedis.OpenTelemetry";
private static readonly ActivitySource ActivitySource = new(SourceName, "1.0.0");
/// <summary>Notifies the observer that the provider has finished sending push-based notifications.</summary>
public void OnCompleted()
{
}
/// <summary>Notifies the observer that the provider has experienced an error condition.</summary>
/// <param name="error">An object that provides additional information about the error.</param>
public void OnError(Exception error)
{
}
/// <summary>Provides the observer with new data.</summary>
/// <param name="evt">The current notification information.</param>
public void OnNext(KeyValuePair<string, object?> evt)
{
//https://opentelemetry.io/docs/specs/semconv/database/redis/
switch (evt.Key)
{
case FreeRedisDiagnosticListenerNames.NoticeCallBefore:
{
var eventData = (InterceptorBeforeEventArgs)evt.Value!;
var activity = ActivitySource.StartActivity("redis command execute: " + eventData.Command);
if (activity != null)
{
activity.SetTag("db.system", "redis");
activity.SetTag("db.operation.name", eventData.Command._command);
activity.SetTag("db.query.text", eventData.Command);
//Activity.Current?.SetTag("network.peer.address", ip);
//Activity.Current?.SetTag("network.peer.port", port);
activity.AddEvent(new ActivityEvent("redis command execute start",
DateTimeOffset.FromUnixTimeMilliseconds(eventData.OperationTimestamp!.Value)));
}
}
break;
case FreeRedisDiagnosticListenerNames.NoticeCallAfter:
{
var eventData = (InterceptorAfterEventArgs)evt.Value!;
var writeTarget = eventData.Command.WriteTarget;
if (!string.IsNullOrEmpty(writeTarget))
{
var parts = writeTarget.Split(new[] { ':', '/' }, StringSplitOptions.RemoveEmptyEntries);
var ip = parts[0];
var port = int.Parse(parts[1]);
var dbIndex = int.Parse(parts[2]);
Activity.Current?.SetTag("server.address", ip);
Activity.Current?.SetTag("server.port", port);
Activity.Current?.SetTag("db.namespace", dbIndex);
}
var tags = new ActivityTagsCollection { new("free_redis.duration", eventData.ElapsedMilliseconds) };
if (eventData.Exception != null)
{
Activity.Current?.SetStatus(Status.Error.WithDescription(eventData.Exception.Message));
tags.Add(new("error.type", eventData.Exception.Message));
}
Activity.Current?.AddEvent(new ActivityEvent("redis command executed",
DateTimeOffset.FromUnixTimeMilliseconds(eventData.OperationTimestamp!.Value), tags)
);
Activity.Current?.Stop();
}
break;
}
}
}
} |
2881099/FreeRedis | 161,878 | src/FreeRedis/FreeRedis.xml | <?xml version="1.0"?>
<doc>
<assembly>
<name>FreeRedis</name>
</assembly>
<members>
<member name="P:FreeRedis.ClientSideCachingOptions.KeyFilter">
<summary>
true: cache
</summary>
</member>
<member name="P:FreeRedis.ClientSideCachingOptions.CheckExpired">
<summary>
true: expired
</summary>
</member>
<member name="F:FreeRedis.ClientSideCachingExtensions.ClientSideCachingContext._dict">
<summary>
key -> Type(string|byte[]|class) -> value
</summary>
</member>
<member name="M:FreeRedis.CommandPacket.FlagReadbytes(System.Boolean)">
<summary>
read byte[]
</summary>
<param name="isReadbytes"></param>
<returns></returns>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.write">
<summary>
command may result in modifications
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.readonly">
<summary>
command will never modify keys
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.denyoom">
<summary>
reject command if currently out of memory
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.admin">
<summary>
server admin command
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.pubsub">
<summary>
pubsub-related command
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.noscript">
<summary>
deny this command from scripts
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.random">
<summary>
command has random results, dangerous for scripts
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.sort_for_script">
<summary>
if called from script, sort output
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.loading">
<summary>
allow command while database is loading
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.stale">
<summary>
allow command while replica has stale data
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.skip_monitor">
<summary>
do not show this command in MONITOR
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.asking">
<summary>
cluster related - accept even if importing
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.fast">
<summary>
command operates in constant or log(N) time. Used for latency monitoring.
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.movablekeys">
<summary>
keys have no pre-determined position. You must discover keys yourself.
</summary>
</member>
<member name="F:FreeRedis.CommandSets.ServerFlag.skip_slowlog">
<summary>
do not show this command in SLOWLOG
</summary>
</member>
<member name="T:FreeRedis.Internal.IdleBus">
<summary>
空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
</summary>
</member>
<member name="M:FreeRedis.Internal.IdleBus.#ctor">
<summary>
按空闲时间1分钟,创建空闲容器
</summary>
</member>
<member name="M:FreeRedis.Internal.IdleBus.#ctor(System.TimeSpan)">
<summary>
指定空闲时间、创建空闲容器
</summary>
<param name="idle">空闲时间</param>
</member>
<member name="T:FreeRedis.Internal.IdleBus`1">
<summary>
空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
</summary>
</member>
<member name="M:FreeRedis.Internal.IdleBus`1.#ctor">
<summary>
按空闲时间1分钟,创建空闲容器
</summary>
</member>
<member name="M:FreeRedis.Internal.IdleBus`1.#ctor(System.TimeSpan)">
<summary>
指定空闲时间、创建空闲容器
</summary>
<param name="idle">空闲时间</param>
</member>
<member name="T:FreeRedis.Internal.IdleBus`2">
<summary>
空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
</summary>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.#ctor">
<summary>
按空闲时间1分钟,创建空闲容器
</summary>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.#ctor(System.TimeSpan)">
<summary>
指定空闲时间、创建空闲容器
</summary>
<param name="idle">空闲时间</param>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.Get(`0)">
<summary>
根据 key 获得或创建【实例】(线程安全)<para></para>
key 未注册时,抛出异常
</summary>
<param name="key"></param>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.GetAll">
<summary>
获得或创建所有【实例】(线程安全)
</summary>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.GetKeys(System.Func{`1,System.Boolean})">
<summary>
获得所有已注册的 key(线程安全)
</summary>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.Exists(`0)">
<summary>
判断 key 是否注册
</summary>
<param name="key"></param>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.IdleBus`2.Register(`0,System.Func{`1})">
<summary>
注册【实例】
</summary>
<param name="key"></param>
<param name="create">实例创建方法</param>
<returns></returns>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.UsageQuantity">
<summary>
已创建【实例】数量
</summary>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.Quantity">
<summary>
注册数量
</summary>
</member>
<member name="E:FreeRedis.Internal.IdleBus`2.Notice">
<summary>
通知事件
</summary>
</member>
<member name="F:FreeRedis.Internal.IdleBus`2.NoticeType.Register">
<summary>
执行 Register 方法的时候
</summary>
</member>
<member name="F:FreeRedis.Internal.IdleBus`2.NoticeType.Remove">
<summary>
执行 Remove 方法的时候,注意:实际会延时释放【实例】
</summary>
</member>
<member name="F:FreeRedis.Internal.IdleBus`2.NoticeType.AutoCreate">
<summary>
自动创建【实例】的时候
</summary>
</member>
<member name="F:FreeRedis.Internal.IdleBus`2.NoticeType.AutoRelease">
<summary>
自动释放不活跃【实例】的时候
</summary>
</member>
<member name="F:FreeRedis.Internal.IdleBus`2.NoticeType.Get">
<summary>
获取【实例】的时候
</summary>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.TimeoutScanOptions.Interval">
<summary>
扫描线程间隔(默认值:2秒)
</summary>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.TimeoutScanOptions.QuitWaitSeconds">
<summary>
扫描线程空闲多少秒退出(默认值:10秒)
</summary>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.TimeoutScanOptions.BatchQuantity">
<summary>
扫描的每批数量(默认值:512)<para></para>
可防止注册数量太多时导致 CPU 占用过高
</summary>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.TimeoutScanOptions.BatchQuantityWait">
<summary>
达到扫描的每批数量时,线程等待(默认值:1秒)
</summary>
</member>
<member name="P:FreeRedis.Internal.IdleBus`2.ScanOptions">
<summary>
扫描过期对象的设置<para></para>
机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。<para></para>
连续多少秒都没存活的对象时,才退出扫描。
</summary>
</member>
<member name="P:FreeRedis.Internal.IRedisSocket.ClientId">
<summary>
Redis-server ClientID
</summary>
</member>
<member name="P:FreeRedis.Internal.IRedisSocket.ClientId2">
<summary>
FreeRedis 本地专用 ID
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IObjectPool`1.IsAvailable">
<summary>
是否可用
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IObjectPool`1.UnavailableException">
<summary>
不可用错误
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IObjectPool`1.UnavailableTime">
<summary>
不可用时间
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IObjectPool`1.SetUnavailable(System.Exception,System.DateTime)">
<summary>
将对象池设置为不可用,后续 Get/GetAsync 均会报错,同时启动后台定时检查服务恢复可用
</summary>
<param name="exception"></param>
<param name="lastGetTime"></param>
<returns>由【可用】变成【不可用】时返回true,否则返回false</returns>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IObjectPool`1.Statistics">
<summary>
统计对象池中的对象
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IObjectPool`1.StatisticsFullily">
<summary>
统计对象池中的对象(完整)
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IObjectPool`1.Get(System.Nullable{System.TimeSpan})">
<summary>
获取资源
</summary>
<param name="timeout">超时</param>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IObjectPool`1.GetAsync">
<summary>
获取资源
</summary>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IObjectPool`1.Return(FreeRedis.Internal.ObjectPool.Object{`0},System.Boolean)">
<summary>
使用完毕后,归还资源
</summary>
<param name="obj">对象</param>
<param name="isReset">是否重新创建</param>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.Name">
<summary>
名称
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.PoolSize">
<summary>
池容量
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.SyncGetTimeout">
<summary>
默认获取超时设置
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.IdleTimeout">
<summary>
空闲时间,获取时若超出,则重新创建
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.AsyncGetCapacity">
<summary>
异步获取排队队列大小,小于等于0不生效
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.IsThrowGetTimeoutException">
<summary>
获取超时后,是否抛出异常
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.IsAutoDisposeWithSystem">
<summary>
监听 AppDomain.CurrentDomain.ProcessExit/Console.CancelKeyPress 事件自动释放
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.AvailableCheckInterval">
<summary>
后台定时检查可用性间隔
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.ToleranceWindow">
<summary>
故障切换的容忍窗口期。
当设置为大于 TimeSpan.Zero 的值时,首次失败会进入观察期,而不是立即熔断。
在观察期内持续失败,才会最终熔断。设置为 Zero 表示关闭此功能。
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.IPolicy`1.ToleranceCheckInterval">
<summary>
在容忍窗口期(观察期)内,进行健康检查的间隔。
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnCreate">
<summary>
对象池的对象被创建时
</summary>
<returns>返回被创建的对象</returns>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnDestroy(`0)">
<summary>
销毁对象
</summary>
<param name="obj">资源对象</param>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnGetTimeout">
<summary>
从对象池获取对象超时的时候触发,通过该方法统计
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnGet(FreeRedis.Internal.ObjectPool.Object{`0})">
<summary>
从对象池获取对象成功的时候触发,通过该方法统计或初始化对象
</summary>
<param name="obj">资源对象</param>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnGetAsync(FreeRedis.Internal.ObjectPool.Object{`0})">
<summary>
从对象池获取对象成功的时候触发,通过该方法统计或初始化对象
</summary>
<param name="obj">资源对象</param>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnReturn(FreeRedis.Internal.ObjectPool.Object{`0})">
<summary>
归还对象给对象池的时候触发
</summary>
<param name="obj">资源对象</param>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnCheckAvailable(FreeRedis.Internal.ObjectPool.Object{`0})">
<summary>
检查可用性
</summary>
<param name="obj">资源对象</param>
<returns></returns>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnAvailable">
<summary>
事件:可用时触发
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.IPolicy`1.OnUnavailable">
<summary>
事件:不可用时触发
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.Pool">
<summary>
所属对象池
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.Id">
<summary>
在对象池中的唯一标识
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.Value">
<summary>
资源对象
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.GetTimes">
<summary>
被获取的总次数
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.LastGetTime">
最后获取时的时间
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.LastReturnTime">
<summary>
最后归还时的时间
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.CreateTime">
<summary>
创建时间
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.LastGetThreadId">
<summary>
最后获取时的线程id
</summary>
</member>
<member name="P:FreeRedis.Internal.ObjectPool.Object`1.LastReturnThreadId">
<summary>
最后归还时的线程id
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.Object`1.ResetValue">
<summary>
重置 Value 值
</summary>
</member>
<member name="T:FreeRedis.Internal.ObjectPool.ObjectPool`1">
<summary>
对象池管理类
</summary>
<typeparam name="T">对象类型</typeparam>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.SetUnavailable(System.Exception,System.DateTime)">
<summary>
报告一次失败。这是新的故障处理入口。
它会根据策略决定是进入“观察期”还是直接“熔断”。
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.UnifiedCheckerLoop">
<summary>
一个统一的、能处理两种状态(Observing 和 Unavailable)的检查循环。
这个线程一旦启动,就会一直运行,直到状态恢复为 Healthy 或池被 Dispose。
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.TransitionToUnavailable(System.Exception,System.DateTime,System.Boolean)">
<summary>
将连接池状态切换为“不可用”
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.CheckUntilAvailable(System.TimeSpan)">
<summary>
后台定时检查可用性(原 CheckAvailable 方法)
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.TryHealthCheck">
<summary>
尝试进行一次健康检查的通用逻辑
</summary>
<returns>检查是否成功</returns>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.RestoreToAvailable">
<summary>
将连接池恢复到可用状态
</summary>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.#ctor(System.Int32,System.Func{`0},System.Action{FreeRedis.Internal.ObjectPool.Object{`0}})">
<summary>
创建对象池
</summary>
<param name="poolsize">池大小</param>
<param name="createObject">池内对象的创建委托</param>
<param name="onGetObject">获取池内对象成功后,进行使用前操作</param>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.#ctor(FreeRedis.Internal.ObjectPool.IPolicy{`0})">
<summary>
创建对象池
</summary>
<param name="policy">策略</param>
</member>
<member name="M:FreeRedis.Internal.ObjectPool.ObjectPool`1.GetFree(System.Boolean)">
<summary>
获取可用资源,或创建资源
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.BlobString">
<summary>
$11\r\nhelloworld\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.SimpleString">
<summary>
+hello world\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.VerbatimString">
<summary>
=15\r\ntxt:Some string\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.SimpleError">
<summary>
-ERR this is the error description\r\n<para></para>
The first word in the error is in upper case and describes the error code.
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.BlobError">
<summary>
!21\r\nSYNTAX invalid syntax\r\n<para></para>
The first word in the error is in upper case and describes the error code.
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Number">
<summary>
:1234\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.BigNumber">
<summary>
(3492890328409238509324850943850943825024385\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Null">
<summary>
_\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Double">
<summary>
,1.23\r\n<para></para>
,inf\r\n<para></para>
,-inf\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Boolean">
<summary>
#t\r\n<para></para>
#f\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Array">
<summary>
*3\r\n:1\r\n:2\r\n:3\r\n<para></para>
[1, 2, 3]
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Set">
<summary>
~5\r\n+orange\r\n+apple\r\n#t\r\n:100\r\n:999\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Push">
<summary>
>4\r\n+pubsub\r\n+message\r\n+somechannel\r\n+this is the message\r\n
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Map">
<summary>
%2\r\n+first\r\n:1\r\n+second\r\n:2\r\n<para></para>
{ "first": 1, "second": 2 }
</summary>
</member>
<member name="F:FreeRedis.RedisMessageType.Attribute">
<summary>
|2\r\n+first\r\n:1\r\n+second\r\n:2\r\n<para></para>
{ "first": 1, "second": 2 }
</summary>
</member>
<member name="M:FreeRedis.RedisClient.#ctor(FreeRedis.ConnectionStringBuilder,FreeRedis.ConnectionStringBuilder[])">
<summary>
Pooling RedisClient
</summary>
</member>
<member name="M:FreeRedis.RedisClient.#ctor(FreeRedis.ConnectionStringBuilder[],System.Collections.Generic.Dictionary{System.String,System.String})">
<summary>
Cluster RedisClient
</summary>
</member>
<member name="M:FreeRedis.RedisClient.#ctor(FreeRedis.ConnectionStringBuilder[],System.Func{System.String,System.String})">
<summary>
Norman RedisClient
</summary>
</member>
<member name="M:FreeRedis.RedisClient.#ctor(FreeRedis.ConnectionStringBuilder,System.String[],System.Boolean)">
<summary>
Sentinel RedisClient
</summary>
</member>
<member name="M:FreeRedis.RedisClient.#ctor(FreeRedis.RedisClient,System.String,System.Boolean,System.Net.Security.RemoteCertificateValidationCallback,System.Net.Security.LocalCertificateSelectionCallback,System.TimeSpan,System.TimeSpan,System.TimeSpan,System.Action{FreeRedis.RedisClient},System.Action{FreeRedis.RedisClient})">
<summary>
Single inside RedisClient
</summary>
</member>
<member name="M:FreeRedis.RedisClient.DelAsync(System.String[])">
<summary>
DEL command (An Asynchronous Version) <br /><br />
<br />
Removes the specified keys. A key is ignored if it does not exist.<br /><br />
<br />
移除指定的键。如果键不存在,则忽略之。<br /><br />
<br />
Document link: https://redis.io/commands/del <br />
Available since 2.6.0.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys that were removed.</returns>
</member>
<member name="M:FreeRedis.RedisClient.DumpAsync(System.String)">
<summary>
DUMP command (An Asynchronous Version) <br /><br />
<br />
Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command.<br /><br />
<br />
以 Redis 特有格式序列化指定的键值,并返回给用户。可结合 RESTORE 命令将序列化的结果重新写回 Redis。<br /><br />
<br />
Document link: https://redis.io/commands/dump <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<returns>The serialized value.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ExistsAsync(System.String)">
<summary>
EXISTS command (An Asynchronous Version) <br /><br />
<br />
Returns if key exists.<br /><br />
<br />
返回键是否存在。<br /><br />
<br />
Document link: https://redis.io/commands/exists <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>Specifically: True if the key exists. False if the key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ExistsAsync(System.String[])">
<summary>
EXISTS command (An Asynchronous Version) <br /><br />
<br />
Returns if key exists.<br /><br />
<br />
返回键是否存在。<br /><br />
<br />
Document link: https://redis.io/commands/exists <br />
Available since 3.0.3.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys existing among the ones specified as arguments. Keys mentioned multiple times and existing are counted multiple times.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ExpireAsync(System.String,System.Int32)">
<summary>
EXPIRE command (An Asynchronous Version) <br /><br />
<br />
Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
<br />
设置键的超时时间。到期后,键将被自动删除。<br /><br />
<br />
Document link: https://redis.io/commands/expire <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="seconds">Expires time (seconds)</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ExpireAsync(System.String,System.TimeSpan)">
<summary>
EXPIRE command (An Asynchronous Version) <br /><br />
<br />
Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
<br />
设置键的超时时间。到期后,键将被自动删除。<br /><br />
<br />
Document link: https://redis.io/commands/expire <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="expire">Expires TimeSpan</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ExpireAtAsync(System.String,System.DateTime)">
<summary>
EXPIREAT command (An Asynchronous Version) <br /><br />
<br />
EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970). A timestamp in the past will delete the key immediately.<br /><br />
<br />
EXPIREAT 具有与 EXPIRE 相同的作用和语义,但是它没有指定表示 TTL(生存时间)的秒数,而是使用了绝对的 Unix 时间戳(自1970年1月1日以来的秒数)。时间戳一旦过期就会被删除。<br /><br />
<br />
Document link: https://redis.io/commands/expireat <br />
Available since 1.2.0.
</summary>
<param name="key">Key</param>
<param name="timestamp">UNIX Timestamp</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.KeysAsync(System.String)">
<summary>
KEYS command (An Asynchronous Version) <br /><br />
<br />
Returns all keys matching pattern.<br /><br />
<br />
返回所有与模式匹配的键。<br /><br />
<br />
Document link: https://redis.io/commands/keys <br />
Available since 1.0.0.
</summary>
<param name="pattern">Pattern</param>
<returns>List of keys matching pattern.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MigrateAsync(System.String,System.Int32,System.String,System.Int32,System.Int64,System.Boolean,System.Boolean,System.String,System.String,System.String,System.String[])">
<summary>
MIGRATE command (An Asynchronous Version) <br /><br />
<br />
Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance and is guaranteed to exist in the target instance.<br /><br />
<br />
原子地将键从 Redis 源实例转移到目标实例。转移成功后,Key 将从源实例中删除,并确保保存在目标实例之中。<br /><br />
<br />
Document link: https://redis.io/commands/migrate <br />
Available since 2.6.0.
</summary>
<param name="host">Destination Instance's Host</param>
<param name="port">Destination Instance's Port</param>
<param name="key">Key</param>
<param name="destinationDb">Destination Instance's Database</param>
<param name="timeoutMilliseconds">Timeout milliseconds</param>
<param name="copy">Do not remove the key from the local instance. Available since 3.0.0. </param>
<param name="replace">Replace existing key on the remote instance. Available since 3.0.0. </param>
<param name="authPassword">Authenticate with the given password to the remote instance. Available since 4.0.7. </param>
<param name="auth2Username">Authenticate with the given username (Redis 6 or greater ACL auth style).</param>
<param name="auth2Password">Authenticate with the given password (Redis 6 or greater ACL auth style).</param>
<param name="keys">If the key argument is an empty string, the command will instead migrate all the keys that follow the KEYS option (see the above section for more info). Available since 3.0.6. </param>
</member>
<member name="M:FreeRedis.RedisClient.MoveAsync(System.String,System.Int32)">
<summary>
MOVE command (An Asynchronous Version) <br /><br />
<br />
Move key from the currently selected database (see SELECT) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use MOVE as a locking primitive because of this. <br /><br />
<br />
将指定的 Key 从当前数据库移动到目标数据库。<br />
如果目标数据库中已存在该键,或源数据库中不存在该键,则什么都不做。<br /><br />
<br />
Document link: https://redis.io/commands/move <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="db">Database</param>
<returns>Specifically: True if key was moved. False if key was not moved.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectRefCountAsync(System.String)">
<summary>
OBJECT REFCOUNT command (An Asynchronous Version) <br /><br />
<br />
Returns the number of references of the value associated with the specified key. This command is mainly useful for debugging.<br /><br />
<br />
返回与指定键关联的值的引用数。<br /><br />
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the number of references of the value associated with the specified key.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectIdleTimeAsync(System.String)">
<summary>
OBJECT IDLETIME command (An Asynchronous Version) <br /><br />
<br />
returns the number of seconds since the object stored at the specified key is idle (not requested by read or write operations). While the value is returned in seconds the actual resolution of this timer is 10 seconds, but may vary in future implementations. This subcommand is available when maxmemory-policy is set to an LRU policy or noeviction and maxmemory is set. <br /><br />
<br />
返回指定键值的空闲时间,单位为秒。<br /><br />
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the number of seconds since the object stored at the specified key is idle</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectEncodingAsync(System.String)">
<summary>
OBJECT ENCODING command (An Asynchronous Version) <br /><br />
<br />
Returns the kind of internal representation used in order to store the value associated with a key.<br /><br />
<br />
返回用于存储与键关联的值的内部表示形式的类型。
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the kind of internal representation used in order to store the value associated with a key.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectFreqAsync(System.String)">
<summary>
OBJECT FREQ command (An Asynchronous Version) <br /><br />
<br />
Returns the logarithmic access frequency counter of the object stored at the specified key. This subcommand is available when maxmemory-policy is set to an LFU policy.<br /><br />
<br />
返回存储在指定键处的对象的对数访问频率计数器。<br /><br />
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the logarithmic access frequency counter of the object stored at the specified key.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PersistAsync(System.String)">
<summary>
PERSIST command (An Asynchronous Version) <br /><br />
<br />
Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated).<br /><br />
<br />
将指定键的超时设置移除,将键从可变键转换为持久键。<br /><br />
<br />
Document link: https://redis.io/commands/persist <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<returns>Specifically: True if the timeout was removed. False if key does not exist or does not have an associated timeout.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PExpireAsync(System.String,System.Int32)">
<summary>
PEXPIRE command (An Asynchronous Version) <br /><br />
<br />
This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds.<br /><br />
<br />
此命令与 EXPIRE 相同,区别仅仅在于时间单位是毫秒,不是秒。<br /><br />
<br />
Document link: https://redis.io/commands/expire <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="milliseconds">Expires time (milliseconds)</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PExpireAtAsync(System.String,System.DateTime)">
<summary>
PEXPIREAT command (An Asynchronous Version) <br /><br />
<br />
PEXPIREAT has the same effect and semantic as EXPIREAT, but the Unix time at which the key will expire is specified in milliseconds instead of seconds.<br /><br />
<br />
PEXPIREAT 具有与 EXPIREAT 相同的作用和语义,但 Key 的时间戳使用的是毫秒,而不是秒。<br /><br />
<br />
Document link: https://redis.io/commands/pexpireat <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="timestamp">UNIX Timestamp</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.PTtlAsync(System.String)">
<summary>
PTTL command (An Asynchronous Version) <br /><br />
<br />
Like TTL this command returns the remaining time to live of a key that has an expire set, with the sole difference that TTL returns the amount of remaining time in seconds while PTTL returns it in milliseconds.<br />
In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
Starting with Redis 2.8 the return value in case of error changed: <br />
- The command returns -2 if the key does not exist.<br />
- The command returns -1 if the key exists but has no associated expire.<br /><br />
<br />
与 TTL 命令一样,返回键的剩余生存时间,唯一的区别是 TTL 以秒为单位返回剩余时间,而 PTTL 以毫秒为单位返回。<br />
在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
- 如果 Key 不存在,则返回 -2 <br />
- 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
<br />
Document link: https://redis.io/commands/pttl <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<returns>TTL in milliseconds, or a negative value in order to signal an error (see the description above).</returns>
</member>
<member name="M:FreeRedis.RedisClient.RandomKeyAsync">
<summary>
RANDOMKEY command (An Asynchronous Version) <br /><br />
<br />
Return a random key from the currently selected database. <br /><br />
<br />
从当前选择的数据库返回一个随机密钥。<br /><br />
<br />
Document link: https://redis.io/commands/randomkey <br />
Available since 1.0.0.
</summary>
<returns>The random key, or nil when the database is empty.</returns>
</member>
<member name="M:FreeRedis.RedisClient.RenameAsync(System.String,System.String)">
<summary>
RENAME command (An Asynchronous Version) <br /><br />
<br />
Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
- Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
<br />
将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
- 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/rename <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="newkey">New key</param>
</member>
<member name="M:FreeRedis.RedisClient.RenameNxAsync(System.String,System.String)">
<summary>
RENAMENX command (An Asynchronous Version) <br /><br />
<br />
Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
- Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
<br />
将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
- 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/renamenx <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="newkey">New key</param>
<returns>specifically: True if key was renamed to newkey. False if newkey already exists.</returns>
</member>
<member name="M:FreeRedis.RedisClient.RestoreAsync(System.String,System.Byte[])">
<summary>
RESTORE command (An Asynchronous Version) <br /><br />
<br />
Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
<br />
将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
<br />
Document link: https://redis.io/commands/restore <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="serializedValue">Serialized value</param>
</member>
<member name="M:FreeRedis.RedisClient.RestoreAsync(System.String,System.Int32,System.Byte[],System.Boolean,System.Boolean,System.Nullable{System.Int32},System.Nullable{System.Decimal})">
<summary>
RESTORE command (An Asynchronous Version) <br /><br />
<br />
Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
<br />
将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
<br />
Document link: https://redis.io/commands/restore <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="ttl">If ttl is 0 the key is created without any expire, otherwise the specified expire time (in milliseconds) is set.</param>
<param name="serializedValue">Serialized value</param>
<param name="replace">REPLACE modifier: If the Key already exists, replace it. Available since 3.0.0.</param>
<param name="absTtl">Absolute Unix timestamp (in milliseconds) in which the key will expire. Available since 5.0.0.</param>
<param name="idleTimeSeconds">IDLETIME modifier. Available since 5.0.0.</param>
<param name="frequency">FREQ modifier. Available since 5.0.0.</param>
</member>
<member name="M:FreeRedis.RedisClient.ScanAsync(System.Int64,System.String,System.Int64,System.String)">
<summary>
SCAN command (An Asynchronous Version) <br /><br />
<br />
The SCAN command and the closely related commands SSCAN, HSCAN and ZSCAN are used in order to incrementally iterate over a collection of elements.<br /><br />
<br />
使用 SCAN 命令及其关联的 SSCAN、HSCAN、ZSCAN 等命令来迭代返回元素集合。<br /><br />
<br />
Document link: https://redis.io/commands/scan <br />
Available since 2.8.0.
</summary>
<param name="cursor">Cursor</param>
<param name="pattern">MATCH option</param>
<param name="count">COUNT option: while SCAN does not provide guarantees about the number of elements returned at every iteration, it is possible to empirically adjust the behavior of SCAN using the COUNT option, default is 10</param>
<param name="type">TYPE option: the type argument is the same string name that the TYPE command returns. Available since 6.0</param>
<returns>Return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements.</returns>
</member>
<member name="M:FreeRedis.RedisClient.SortAsync(System.String,System.String,System.Int64,System.Int64,System.String[],System.Nullable{FreeRedis.Collation},System.Boolean)">
<summary>
SORT command (An Asynchronous Version) <br /><br />
<br />
Returns or stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
<br />
返回含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
<br />
Document link: https://redis.io/commands/sort <br />
Available since 1.0.0.
</summary>
<param name="key">Keys</param>
<param name="byPattern">BY modifier</param>
<param name="offset">The number of elements to skip.</param>
<param name="count">Specifying the number of elements to return from starting at offset.</param>
<param name="getPatterns">GET modifier</param>
<param name="collation">ASC | DESC modifier</param>
<param name="alpha">ALPHA modifier, sort by lexicographically.</param>
<returns>A list of sorted elements</returns>
</member>
<member name="M:FreeRedis.RedisClient.SortStoreAsync(System.String,System.String,System.String,System.Int64,System.Int64,System.String[],System.Nullable{FreeRedis.Collation},System.Boolean)">
<summary>
SORT command (An Asynchronous Version) <br /><br />
<br />
Stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
<br />
存储包含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
<br />
Document link: https://redis.io/commands/sort <br />
Available since 1.0.0.
</summary>
<param name="storeDestination">Storing the result of a SORT operation to the destination key.</param>
<param name="key">Keys</param>
<param name="byPattern">BY modifier</param>
<param name="offset">The number of elements to skip.</param>
<param name="count">Specifying the number of elements to return from starting at offset.</param>
<param name="getPatterns">GET modifier</param>
<param name="collation">ASC | DESC modifier</param>
<param name="alpha">ALPHA modifier, sort by lexicographically.</param>
<returns>The number of sorted elements in the destination list.</returns>
</member>
<member name="M:FreeRedis.RedisClient.TouchAsync(System.String[])">
<summary>
TOUCH command (An Asynchronous Version) <br /><br />
<br />
Alters the last access time of a key(s). A key is ignored if it does not exist.<br /><br />
<br />
更改 Key(s) 最后访问时间。如果键不存在,则忽略之。<br /><br />
<br />
Document link: https://redis.io/commands/touch <br />
Available since 3.2.1.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys that were touched.</returns>
</member>
<member name="M:FreeRedis.RedisClient.TtlAsync(System.String)">
<summary>
TTL command (An Asynchronous Version) <br /><br />
<br />
Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.<br />
In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
Starting with Redis 2.8 the return value in case of error changed: <br />
- The command returns -2 if the key does not exist.<br />
- The command returns -1 if the key exists but has no associated expire.<br /><br />
<br />
返回键的剩余生存时间。这种自省能力允许 Redis 客户端检查指定键还能再数据集中生存多少秒。<br />
在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
- 如果 Key 不存在,则返回 -2 <br />
- 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
<br />
Document link: https://redis.io/commands/ttl <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>TTL in seconds, or a negative value in order to signal an error (see the description above).</returns>
</member>
<member name="M:FreeRedis.RedisClient.TypeAsync(System.String)">
<summary>
TYPE command (An Asynchronous Version) <br /><br />
<br />
Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset, hash and stream.<br /><br />
<br />
获取键对应值的类型的字符串表达形式。可以返回的类型是:string,list,set,zset,hash 以及 stream。<br /><br />
<br />
Document link: https://redis.io/commands/type <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>The type of key, or none when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.UnLinkAsync(System.String[])">
<summary>
UNLINK command (An Asynchronous Version) <br /><br />
<br />
This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. <br /><br />
<br />
本命令与 DEL 相似,能删除指定的键值;如果键不存在,则忽略。与 DEL 不同的是,本命令将在另一个线程中执行实际的内存回收,因此是非阻塞的。<br /><br />
<br />
Document link: https://redis.io/commands/unlink <br />
Available since 4.0.0.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys that were unlinked.</returns>
</member>
<member name="M:FreeRedis.RedisClient.WaitAsync(System.Int64,System.Int64)">
<summary>
WAIT command (An Asynchronous Version) <br /><br />
<br />
This command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of replicas. If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of replicas were not yet reached. <br /><br />
<br />
本命令将阻塞当前客户端,直到所有写命令成功发送、且大于等于指定数量的副本进行了确认。<br />
如果超时(单位为毫秒),即便没能获得指定数量副本的确认,命令也会返回。<br /><br />
<br />
Document link: https://redis.io/commands/wait <br />
Available since 3.0.0.
</summary>
<param name="numreplicas">The number of replicas</param>
<param name="timeoutMilliseconds">Timeout milliseconds</param>
<returns>The command returns the number of replicas reached by all the writes performed in the context of the current connection.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Del(System.String[])">
<summary>
DEL command (A Synchronized Version) <br /><br />
<br />
Removes the specified keys. A key is ignored if it does not exist.<br /><br />
<br />
移除指定的键。如果键不存在,则忽略之。<br /><br />
<br />
Document link: https://redis.io/commands/del <br />
Available since 2.6.0.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys that were removed.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Dump(System.String)">
<summary>
DUMP command (A Synchronized Version) <br /><br />
<br />
Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command.<br /><br />
<br />
以 Redis 特有格式序列化指定的键值,并返回给用户。可结合 RESTORE 命令将序列化的结果重新写回 Redis。<br /><br />
<br />
Document link: https://redis.io/commands/dump <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<returns>The serialized value.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Exists(System.String)">
<summary>
EXISTS command (A Synchronized Version) <br /><br />
<br />
Returns if key exists.<br /><br />
<br />
返回键是否存在。<br /><br />
<br />
Document link: https://redis.io/commands/exists <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>Specifically: True if the key exists. False if the key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Exists(System.String[])">
<summary>
EXISTS command (A Synchronized Version) <br /><br />
<br />
Returns if key exists.<br /><br />
<br />
返回键是否存在。<br /><br />
<br />
Document link: https://redis.io/commands/exists <br />
Available since 3.0.3.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys existing among the ones specified as arguments. Keys mentioned multiple times and existing are counted multiple times.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Expire(System.String,System.Int32)">
<summary>
EXPIRE command (A Synchronized Version) <br /><br />
<br />
Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
<br />
设置键的超时时间。到期后,键将被自动删除。<br /><br />
<br />
Document link: https://redis.io/commands/expire <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="seconds">Expires time (seconds)</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Expire(System.String,System.TimeSpan)">
<summary>
EXPIRE command (A Synchronized Version) <br /><br />
<br />
Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
<br />
设置键的超时时间。到期后,键将被自动删除。<br /><br />
<br />
Document link: https://redis.io/commands/expire <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="expire">Expires TimeSpan</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ExpireAt(System.String,System.DateTime)">
<summary>
EXPIREAT command (A Synchronized Version) <br /><br />
<br />
EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970). A timestamp in the past will delete the key immediately.<br /><br />
<br />
EXPIREAT 具有与 EXPIRE 相同的作用和语义,但是它没有指定表示 TTL(生存时间)的秒数,而是使用了绝对的 Unix 时间戳(自1970年1月1日以来的秒数)。时间戳一旦过期就会被删除。<br /><br />
<br />
Document link: https://redis.io/commands/expireat <br />
Available since 1.2.0.
</summary>
<param name="key">Key</param>
<param name="timestamp">UNIX Timestamp</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Keys(System.String)">
<summary>
KEYS command (A Synchronized Version) <br /><br />
<br />
Returns all keys matching pattern.<br /><br />
<br />
返回所有与模式匹配的键。<br /><br />
<br />
Document link: https://redis.io/commands/keys <br />
Available since 1.0.0.
</summary>
<param name="pattern">Pattern</param>
<returns>List of keys matching pattern.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Migrate(System.String,System.Int32,System.String,System.Int32,System.Int64,System.Boolean,System.Boolean,System.String,System.String,System.String,System.String[])">
<summary>
MIGRATE command (A Synchronized Version) <br /><br />
<br />
Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance and is guaranteed to exist in the target instance.<br /><br />
<br />
原子地将键从 Redis 源实例转移到目标实例。转移成功后,Key 将从源实例中删除,并确保保存在目标实例之中。<br /><br />
<br />
Document link: https://redis.io/commands/migrate <br />
Available since 2.6.0.
</summary>
<param name="host">Destination Instance's Host</param>
<param name="port">Destination Instance's Port</param>
<param name="key">Key</param>
<param name="destinationDb">Destination Instance's Database</param>
<param name="timeoutMilliseconds">Timeout milliseconds</param>
<param name="copy">Do not remove the key from the local instance. Available since 3.0.0. </param>
<param name="replace">Replace existing key on the remote instance. Available since 3.0.0. </param>
<param name="authPassword">Authenticate with the given password to the remote instance. Available since 4.0.7. </param>
<param name="auth2Username">Authenticate with the given username (Redis 6 or greater ACL auth style).</param>
<param name="auth2Password">Authenticate with the given password (Redis 6 or greater ACL auth style).</param>
<param name="keys">If the key argument is an empty string, the command will instead migrate all the keys that follow the KEYS option (see the above section for more info). Available since 3.0.6. </param>
</member>
<member name="M:FreeRedis.RedisClient.Move(System.String,System.Int32)">
<summary>
MOVE command (A Synchronized Version) <br /><br />
<br />
Move key from the currently selected database (see SELECT) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use MOVE as a locking primitive because of this. <br /><br />
<br />
将指定的 Key 从当前数据库移动到目标数据库。<br />
如果目标数据库中已存在该键,或源数据库中不存在该键,则什么都不做。<br /><br />
<br />
Document link: https://redis.io/commands/move <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="db">Database</param>
<returns>Specifically: True if key was moved. False if key was not moved.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectRefCount(System.String)">
<summary>
OBJECT REFCOUNT command (A Synchronized Version) <br /><br />
<br />
Returns the number of references of the value associated with the specified key. This command is mainly useful for debugging.<br /><br />
<br />
返回与指定键关联的值的引用数。<br /><br />
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the number of references of the value associated with the specified key.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectIdleTime(System.String)">
<summary>
OBJECT IDLETIME command (A Synchronized Version) <br /><br />
<br />
returns the number of seconds since the object stored at the specified key is idle (not requested by read or write operations). While the value is returned in seconds the actual resolution of this timer is 10 seconds, but may vary in future implementations. This subcommand is available when maxmemory-policy is set to an LRU policy or noeviction and maxmemory is set. <br /><br />
<br />
返回指定键值的空闲时间,单位为秒。<br /><br />
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the number of seconds since the object stored at the specified key is idle</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectEncoding(System.String)">
<summary>
OBJECT ENCODING command (A Synchronized Version) <br /><br />
<br />
Returns the kind of internal representation used in order to store the value associated with a key.<br /><br />
<br />
返回用于存储与键关联的值的内部表示形式的类型。
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the kind of internal representation used in order to store the value associated with a key.</returns>
</member>
<member name="M:FreeRedis.RedisClient.ObjectFreq(System.String)">
<summary>
OBJECT FREQ command (A Synchronized Version) <br /><br />
<br />
Returns the logarithmic access frequency counter of the object stored at the specified key. This subcommand is available when maxmemory-policy is set to an LFU policy.<br /><br />
<br />
返回存储在指定键处的对象的对数访问频率计数器。<br /><br />
<br />
Document link: https://redis.io/commands/object <br />
Available since 2.2.3.
</summary>
<param name="key">Key</param>
<returns>Returns the logarithmic access frequency counter of the object stored at the specified key.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Persist(System.String)">
<summary>
PERSIST command (A Synchronized Version) <br /><br />
<br />
Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated).<br /><br />
<br />
将指定键的超时设置移除,将键从可变键转换为持久键。<br /><br />
<br />
Document link: https://redis.io/commands/persist <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<returns>Specifically: True if the timeout was removed. False if key does not exist or does not have an associated timeout.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PExpire(System.String,System.Int32)">
<summary>
PEXPIRE command (A Synchronized Version) <br /><br />
<br />
This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds.<br /><br />
<br />
此命令与 EXPIRE 相同,区别仅仅在于时间单位是毫秒,不是秒。<br /><br />
<br />
Document link: https://redis.io/commands/expire <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="milliseconds">Expires time (milliseconds)</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PExpireAt(System.String,System.DateTime)">
<summary>
PEXPIREAT command (A Synchronized Version) <br /><br />
<br />
PEXPIREAT has the same effect and semantic as EXPIREAT, but the Unix time at which the key will expire is specified in milliseconds instead of seconds.<br /><br />
<br />
PEXPIREAT 具有与 EXPIREAT 相同的作用和语义,但 Key 的时间戳使用的是毫秒,而不是秒。<br /><br />
<br />
Document link: https://redis.io/commands/pexpireat <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="timestamp">UNIX Timestamp</param>
<returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.PTtl(System.String)">
<summary>
PTTL command (A Synchronized Version) <br /><br />
<br />
Like TTL this command returns the remaining time to live of a key that has an expire set, with the sole difference that TTL returns the amount of remaining time in seconds while PTTL returns it in milliseconds.<br />
In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
Starting with Redis 2.8 the return value in case of error changed: <br />
- The command returns -2 if the key does not exist.<br />
- The command returns -1 if the key exists but has no associated expire.<br /><br />
<br />
与 TTL 命令一样,返回键的剩余生存时间,唯一的区别是 TTL 以秒为单位返回剩余时间,而 PTTL 以毫秒为单位返回。<br />
在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
- 如果 Key 不存在,则返回 -2 <br />
- 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
<br />
Document link: https://redis.io/commands/pttl <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<returns>TTL in milliseconds, or a negative value in order to signal an error (see the description above).</returns>
</member>
<member name="M:FreeRedis.RedisClient.RandomKey">
<summary>
RANDOMKEY command (A Synchronized Version) <br /><br />
<br />
Return a random key from the currently selected database. <br /><br />
<br />
从当前选择的数据库返回一个随机密钥。<br /><br />
<br />
Document link: https://redis.io/commands/randomkey <br />
Available since 1.0.0.
</summary>
<returns>The random key, or nil when the database is empty.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Rename(System.String,System.String)">
<summary>
RENAME command (A Synchronized Version) <br /><br />
<br />
Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
- Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
<br />
将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
- 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/rename <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="newkey">New key</param>
</member>
<member name="M:FreeRedis.RedisClient.RenameNx(System.String,System.String)">
<summary>
RENAMENX command (A Synchronized Version) <br /><br />
<br />
Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
- Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
<br />
将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
- 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/renamenx <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="newkey">New key</param>
<returns>specifically: True if key was renamed to newkey. False if newkey already exists.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Restore(System.String,System.Byte[])">
<summary>
RESTORE command (A Synchronized Version) <br /><br />
<br />
Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
<br />
将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
<br />
Document link: https://redis.io/commands/restore <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="serializedValue">Serialized value</param>
</member>
<member name="M:FreeRedis.RedisClient.Restore(System.String,System.Int32,System.Byte[],System.Boolean,System.Boolean,System.Nullable{System.Int32},System.Nullable{System.Decimal})">
<summary>
RESTORE command (A Synchronized Version) <br /><br />
<br />
Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
<br />
将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
<br />
Document link: https://redis.io/commands/restore <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="ttl">If ttl is 0 the key is created without any expire, otherwise the specified expire time (in milliseconds) is set.</param>
<param name="serializedValue">Serialized value</param>
<param name="replace">REPLACE modifier: If the Key already exists, replace it. Available since 3.0.0.</param>
<param name="absTtl">Absolute Unix timestamp (in milliseconds) in which the key will expire. Available since 5.0.0.</param>
<param name="idleTimeSeconds">IDLETIME modifier. Available since 5.0.0.</param>
<param name="frequency">FREQ modifier. Available since 5.0.0.</param>
</member>
<member name="M:FreeRedis.RedisClient.Scan(System.Int64,System.String,System.Int64,System.String)">
<summary>
SCAN command (A Synchronized Version) <br /><br />
<br />
The SCAN command and the closely related commands SSCAN, HSCAN and ZSCAN are used in order to incrementally iterate over a collection of elements.<br /><br />
<br />
使用 SCAN 命令及其关联的 SSCAN、HSCAN、ZSCAN 等命令来迭代返回元素集合。<br /><br />
<br />
Document link: https://redis.io/commands/scan <br />
Available since 2.8.0.
</summary>
<param name="cursor">Cursor</param>
<param name="pattern">MATCH option</param>
<param name="count">COUNT option: while SCAN does not provide guarantees about the number of elements returned at every iteration, it is possible to empirically adjust the behavior of SCAN using the COUNT option, default is 10</param>
<param name="type">TYPE option: the type argument is the same string name that the TYPE command returns. Available since 6.0</param>
<returns>Return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Sort(System.String,System.String,System.Int64,System.Int64,System.String[],System.Nullable{FreeRedis.Collation},System.Boolean)">
<summary>
SORT command (A Synchronized Version) <br /><br />
<br />
Returns or stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
<br />
返回含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
<br />
Document link: https://redis.io/commands/sort <br />
Available since 1.0.0.
</summary>
<param name="key">Keys</param>
<param name="byPattern">BY modifier</param>
<param name="offset">The number of elements to skip.</param>
<param name="count">Specifying the number of elements to return from starting at offset.</param>
<param name="getPatterns">GET modifier</param>
<param name="collation">ASC | DESC modifier</param>
<param name="alpha">ALPHA modifier, sort by lexicographically.</param>
<returns>A list of sorted elements</returns>
</member>
<member name="M:FreeRedis.RedisClient.SortStore(System.String,System.String,System.String,System.Int64,System.Int64,System.String[],System.Nullable{FreeRedis.Collation},System.Boolean)">
<summary>
SORT command (A Synchronized Version) <br /><br />
<br />
Stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
<br />
存储包含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
<br />
Document link: https://redis.io/commands/sort <br />
Available since 1.0.0.
</summary>
<param name="storeDestination">Storing the result of a SORT operation to the destination key.</param>
<param name="key">Keys</param>
<param name="byPattern">BY modifier</param>
<param name="offset">The number of elements to skip.</param>
<param name="count">Specifying the number of elements to return from starting at offset.</param>
<param name="getPatterns">GET modifier</param>
<param name="collation">ASC | DESC modifier</param>
<param name="alpha">ALPHA modifier, sort by lexicographically.</param>
<returns>The number of sorted elements in the destination list.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Touch(System.String[])">
<summary>
TOUCH command (A Synchronized Version) <br /><br />
<br />
Alters the last access time of a key(s). A key is ignored if it does not exist.<br /><br />
<br />
更改 Key(s) 最后访问时间。如果键不存在,则忽略之。<br /><br />
<br />
Document link: https://redis.io/commands/touch <br />
Available since 3.2.1.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys that were touched.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Ttl(System.String)">
<summary>
TTL command (A Synchronized Version) <br /><br />
<br />
Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.<br />
In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
Starting with Redis 2.8 the return value in case of error changed: <br />
- The command returns -2 if the key does not exist.<br />
- The command returns -1 if the key exists but has no associated expire.<br /><br />
<br />
返回键的剩余生存时间。这种自省能力允许 Redis 客户端检查指定键还能再数据集中生存多少秒。<br />
在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
- 如果 Key 不存在,则返回 -2 <br />
- 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
<br />
Document link: https://redis.io/commands/ttl <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>TTL in seconds, or a negative value in order to signal an error (see the description above).</returns>
</member>
<member name="M:FreeRedis.RedisClient.Type(System.String)">
<summary>
TYPE command (A Synchronized Version) <br /><br />
<br />
Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset, hash and stream.<br /><br />
<br />
获取键对应值的类型的字符串表达形式。可以返回的类型是:string,list,set,zset,hash 以及 stream。<br /><br />
<br />
Document link: https://redis.io/commands/type <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>The type of key, or none when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.UnLink(System.String[])">
<summary>
UNLINK command (A Synchronized Version) <br /><br />
<br />
This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. <br /><br />
<br />
本命令与 DEL 相似,能删除指定的键值;如果键不存在,则忽略。与 DEL 不同的是,本命令将在另一个线程中执行实际的内存回收,因此是非阻塞的。<br /><br />
<br />
Document link: https://redis.io/commands/unlink <br />
Available since 4.0.0.
</summary>
<param name="keys">Keys</param>
<returns>The number of keys that were unlinked.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Wait(System.Int64,System.Int64)">
<summary>
WAIT command (A Synchronized Version) <br /><br />
<br />
This command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of replicas. If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of replicas were not yet reached. <br /><br />
<br />
本命令将阻塞当前客户端,直到所有写命令成功发送、且大于等于指定数量的副本进行了确认。<br />
如果超时(单位为毫秒),即便没能获得指定数量副本的确认,命令也会返回。<br /><br />
<br />
Document link: https://redis.io/commands/wait <br />
Available since 3.0.0.
</summary>
<param name="numreplicas">The number of replicas</param>
<param name="timeoutMilliseconds">Timeout milliseconds</param>
<returns>The command returns the number of replicas reached by all the writes performed in the context of the current connection.</returns>
</member>
<member name="M:FreeRedis.RedisClient.DelayQueue(System.String)">
<summary>
延时队列
</summary>
<param name="queueKey">延时队列Key</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.Lock(System.String,System.Int32,System.Boolean)">
<summary>
开启分布式锁,若超时返回null
</summary>
<param name="name">锁名称</param>
<param name="timeoutSeconds">超时(秒)</param>
<param name="autoDelay">自动延长锁超时时间,看门狗线程的超时时间为timeoutSeconds/2 , 在看门狗线程超时时间时自动延长锁的时间为timeoutSeconds。除非程序意外退出,否则永不超时。</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.Lock(System.String,System.Int32,System.Int32,System.Int32,System.Boolean,System.Threading.CancellationToken)">
<summary>
开启分布式锁,若超时返回null
</summary>
<param name="name">锁名称</param>
<param name="timeoutSeconds">独占锁过期时间</param>
<param name="refrshTimeoutSeconds">每隔多久自动延长一次锁,时间要比 timeoutSeconds 小,否则没有意义</param>
<param name="waitTimeoutSeconds">等待锁释放超时时间,如果这个时间内获取不到锁,则 LockController 为 null</param>
<param name="autoDelay">自动延长锁超时时间,看门狗线程的超时时间为timeoutSeconds/2 , 在看门狗线程超时时间时自动延长锁的时间为timeoutSeconds。除非程序意外退出,否则永不超时。</param>
<param name="token">CancellationToken 自动取消锁</param>
<returns></returns>
</member>
<member name="P:FreeRedis.RedisClient.LockController.HandleLostToken">
<summary>
当刷新锁时间的看门狗线程失去与Redis连接时,导致无法刷新延长锁时间时,触发此HandelLostToken Cancel
</summary>
</member>
<member name="M:FreeRedis.RedisClient.LockController.Delay(System.Int32)">
<summary>
延长锁时间,锁在占用期内操作时返回true,若因锁超时被其他使用者占用则返回false
</summary>
<param name="milliseconds">延长的毫秒数</param>
<returns>成功/失败</returns>
</member>
<member name="M:FreeRedis.RedisClient.LockController.Refresh(System.Int32)">
<summary>
刷新锁时间,把key的ttl重新设置为milliseconds,锁在占用期内操作时返回true,若因锁超时被其他使用者占用则返回false
</summary>
<param name="milliseconds">刷新的毫秒数</param>
<returns>成功/失败</returns>
</member>
<member name="M:FreeRedis.RedisClient.LockController.Unlock">
<summary>
释放分布式锁
</summary>
<returns>成功/失败</returns>
</member>
<member name="M:FreeRedis.RedisClient.SubscribeList(System.String,System.Action{System.String})">
<summary>
使用lpush + blpop订阅端(多端争抢模式),只有一端收到消息
</summary>
<param name="listKey">list key(不含prefix前辍)</param>
<param name="onMessage">接收消息委托</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.SubscribeList(System.String[],System.Action{System.String,System.String})">
<summary>
使用lpush + blpop订阅端(多端争抢模式),只有一端收到消息
</summary>
<param name="listKeys">支持多个 key(不含prefix前辍)</param>
<param name="onMessage">接收消息委托,参数1:key;参数2:消息体</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.SubscribeListBroadcast(System.String,System.String,System.Action{System.String})">
<summary>
使用lpush + blpop订阅端(多端非争抢模式),都可以收到消息
</summary>
<param name="listKey">list key(不含prefix前辍)</param>
<param name="clientId">订阅端标识,若重复则争抢,若唯一必然收到消息</param>
<param name="onMessage">接收消息委托</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.ZRandMember(System.String,System.Int32,System.Boolean)">
<summary>
随机返回N个元素
<para>Redis 6.2.0+以上才支持该命令</para>
</summary>
<param name="key">Key</param>
<param name="count">返回的个数</param>
<param name="repetition">是否允许有重复元素返回</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.ZRandMemberWithScores(System.String,System.Int32,System.Boolean)">
<summary>
随机返回N个元素, 包含分数
<para>Redis 6.2.0+以上才支持该命令</para>
</summary>
<param name="key">Key</param>
<param name="count">返回的个数</param>
<param name="repetition">是否允许有重复元素返回</param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.ZScan(System.String,System.Int64,System.String,System.Int64)">
<summary>
ZSCAN key cursor [MATCH pattern] [COUNT count]
</summary>
<param name="key"></param>
<param name="cursor"></param>
<param name="pattern"></param>
<param name="count"></param>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.AppendAsync``1(System.String,``0)">
<summary>
APPEND command (An Asynchronous Version)<br /><br />
<br />
If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. <br /><br />
<br />
若键值已存在且为字符串,则此命令将值附加在字符串的末尾;<br />
若键值不存在,则会先创建一个空字符串,并附加值(在此情况下,APPEND 类似 SET 命令)。<br /><br />
<br />
Document link: https://redis.io/commands/append <br />
Available since 2.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
<returns>The length of the string after the append operation.</returns>
</member>
<member name="M:FreeRedis.RedisClient.BitCountAsync(System.String,System.Int64,System.Int64)">
<summary>
BITCOUNT command (An Asynchronous Version)<br /><br />
<br />
Count the number of set bits (population counting) in a string.<br /><br />
<br />
统计字符串中的位数。<br /><br />
<br />
Document link: https://redis.io/commands/bitcount <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
<param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
<returns>The number of set bits in the string. Non-existent keys are treated as empty strings and will return zero.</returns>
</member>
<member name="M:FreeRedis.RedisClient.BitOpAsync(FreeRedis.BitOpOperation,System.String,System.String[])">
<summary>
BITOP command (An Asynchronous Version) <br /><br />
<br />
Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.<br /><br />
<br />
在(包括字符串值)的多键之间按位运算,并将结果保存在目标键中。<br />
目前支持 AND、OR、XOR 与 NOT 四种运算方式。<br /><br />
<br />
Document link: https://redis.io/commands/bitop <br />
Available since 2.6.0.
</summary>
<param name="operation">Bit operation type: AND, OR, XOR or NOT</param>
<param name="destkey">Destination Key</param>
<param name="keys">Multiple keys (containing string values)</param>
<returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns>
</member>
<member name="M:FreeRedis.RedisClient.BitPosAsync(System.String,System.Boolean,System.Nullable{System.Int64},System.Nullable{System.Int64})">
<summary>
BITPOS command (An Asynchronous Version) <br /><br />
<br />
Return the position of the first bit set to 1 or 0 in a string.<br />
The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position 8, and so forth.<br /><br />
<br />
返回字符串中第一个 1 或 0 的位置。<br />
注意,本命令将字符串视作位数组,自左向右计算,第一个字节在位置 0,第二个字节在位置 8,以此类推。<br /><br />
<br />
Document link: https://redis.io/commands/bitpos <br />
Available since 2.8.7.
</summary>
<param name="key">Key</param>
<param name="bit">Bit value, 1 is true, 0 is false.</param>
<param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
<param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
<returns>Returns the position of the first bit set to 1 or 0 according to the request.</returns>
</member>
<member name="M:FreeRedis.RedisClient.DecrAsync(System.String)">
<summary>
DECR command (An Asynchronous Version) <br /><br />
<br />
Decrements the number stored at key by one. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值减去 1。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/decr <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>the value of key after the decrement.</returns>
</member>
<member name="M:FreeRedis.RedisClient.DecrByAsync(System.String,System.Int64)">
<summary>
DECRBY command (An Asynchronous Version) <br /><br />
<br />
Decrements the number stored at key by decrement. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值减去给定的值。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/decrby <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="decrement">The given value to be decreased.</param>
<returns>the value of key after the decrement.</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetAsync(System.String)">
<summary>
GET command (An Asynchronous Version) <br /><br />
<br />
Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
<br />
获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
<br />
Document link: https://redis.io/commands/get <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>The value of key, or nil when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetAsync``1(System.String)">
<summary>
GET command (An Asynchronous Version) <br /><br />
<br />
Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
<br />
获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
<br />
Document link: https://redis.io/commands/get <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<typeparam name="T"></typeparam>
<returns>The value of key, or nil when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetAsync(System.String,System.IO.Stream,System.Int32)">
<summary>
GET command (A Synchronized Version) <br /><br />
<br />
Get the value of key and write to the stream.. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
<br />
获得给定键的值并写入流中。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
<br />
Document link: https://redis.io/commands/get <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="destination">Destination stream</param>
<param name="bufferSize">Size</param>
</member>
<member name="M:FreeRedis.RedisClient.GetBitAsync(System.String,System.Int64)">
<summary>
GETBIT command (An Asynchronous Version) <br /><br />
<br />
Returns the bit value at offset in the string value stored at key.<br /><br />
<br />
返回键所对应字符串值中偏移量的位值。<br /><br />
<br />
Document link: https://redis.io/commands/getbit <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<param name="offset">Offset</param>
<returns>The bit value stored at offset.</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetRangeAsync(System.String,System.Int64,System.Int64)">
<summary>
GETRANGE command (An Asynchronous Version) <br /><br />
<br />
Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
<br />
返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
<br />
Document link: https://redis.io/commands/getrange <br />
Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
</summary>
<param name="key">Key</param>
<param name="start">Start</param>
<param name="end">End</param>
<returns>The substring of the string value</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetRangeAsync``1(System.String,System.Int64,System.Int64)">
<summary>
GETRANGE command (An Asynchronous Version) <br /><br />
<br />
Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
<br />
返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
<br />
Document link: https://redis.io/commands/getrange <br />
Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
</summary>
<param name="key">Key</param>
<param name="start">Start</param>
<param name="end">End</param>
<typeparam name="T"></typeparam>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.GetSetAsync``1(System.String,``0)">
<summary>
GETSET command (An Asynchronous Version) <br /><br />
<br />
Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value.<br /><br />
<br />
以原子的方式将新值取代给定键的旧值,并返回旧值。如果该键存在但不包含字符串值时,返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/getset <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="value">New value</param>
<typeparam name="T"></typeparam>
<returns>The old value stored at key, or nil when key did not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.IncrAsync(System.String)">
<summary>
INCR command (An Asynchronous Version) <br /><br />
<br />
Increments the number stored at key by one. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值加上 1。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/incr <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>The value of key after the increment</returns>
</member>
<member name="M:FreeRedis.RedisClient.IncrByAsync(System.String,System.Int64)">
<summary>
INCRBY command (An Asynchronous Version) <br /><br />
<br />
Decrements the number stored at key by increment. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值加上给定的值。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/incrby <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="increment">The given value to be increased.</param>
<returns>The value of key after the increment</returns>
</member>
<member name="M:FreeRedis.RedisClient.IncrByFloatAsync(System.String,System.Decimal)">
<summary>
INCRBYFLOAT command (An Asynchronous Version) <br /><br />
<br />
Increment the string representing a floating point number stored at key by the specified increment. <br />
By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:<br />
- The key contains a value of the wrong type (not a string).<br />
- The current key content or the specified increment are not parsable as a double precision floating point number.<br />
If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.<br /><br />
<br />
对该键的值加上给定的值,可以通过给定负值来减小对应键的值。<br />
如果键值不存在,则在操作前先设置为 0。如果发生以下情况,则返回错误:<br />
- 键所对应的值是错误的类型(不是字符串);<br />
- 该键的内容不能被解析为双精度浮点数。<br />
如果命令执行成功,则将新值替换旧值,并返回给调用方。<br /><br />
<br />
Document link: https://redis.io/commands/incrby <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="increment">The given value to be increased.</param>
<returns>The value of key after the increment.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MGetAsync(System.String[])">
<summary>
MGET command (An Asynchronous Version) <br /><br />
<br />
Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
<br />
返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
<br />
Document link: https://redis.io/commands/mget <br />
Available since 1.0.0.
</summary>
<param name="keys">Key list</param>
<returns>A list of values at the specified keys.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MGetAsync``1(System.String[])">
<summary>
MGET command (An Asynchronous Version) <br /><br />
<br />
Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
<br />
返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
<br />
Document link: https://redis.io/commands/mget <br />
Available since 1.0.0.
</summary>
<param name="keys">Key list</param>
<typeparam name="T"></typeparam>
<returns>A list of values at the specified keys.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MSetAsync(System.String,System.Object,System.Object[])">
<summary>
MSET command (An Asynchronous Version) <br /><br />
<br />
Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
<br />
将给定键的值设置为对应的新值。 <br /><br />
<br />
Document link: https://redis.io/commands/mset <br />
Available since 1.0.1.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keyValues">Other key-value sets</param>
</member>
<member name="M:FreeRedis.RedisClient.MSetAsync``1(System.Collections.Generic.Dictionary{System.String,``0})">
<summary>
MSET command (An Asynchronous Version) <br /><br />
<br />
Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
<br />
将给定键的值设置为对应的新值。 <br /><br />
<br />
Document link: https://redis.io/commands/mset <br />
Available since 1.0.1.
</summary>
<param name="keyValues">Key-value sets</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.MSetNxAsync(System.String,System.Object,System.Object[])">
<summary>
MSETNX command (An Asynchronous Version) <br /><br />
<br />
Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
<br />
将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
<br />
Document link: https://redis.io/commands/msetnx <br />
Available since 1.0.1.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keyValues">Other key-value sets</param>
<returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
</member>
<member name="M:FreeRedis.RedisClient.MSetNxAsync``1(System.Collections.Generic.Dictionary{System.String,``0})">
<summary>
MSETNX command (An Asynchronous Version) <br /><br />
<br />
Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
<br />
将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
<br />
Document link: https://redis.io/commands/msetnx <br />
Available since 1.0.1.
</summary>
<param name="keyValues">Key-value sets</param>
<typeparam name="T"></typeparam>
<returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
</member>
<member name="M:FreeRedis.RedisClient.MSetAsync``1(System.Boolean,System.String,System.Object,System.Object[])">
<summary>
MSET key value [key value ...] command (An Asynchronous Version) <br /><br />
<br />
Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.<br /><br />
<br />
将给定键的值设置为对应的新值。如果不想覆盖现有的值,可以使用 MSETNX 指令。<br /><br />
<br />
Document link: https://redis.io/commands/mset <br />
Available since 1.0.1.
</summary>
<param name="nx">Mark whether it is NX mode. If it is, use the MSETNX command; otherwise, use the MSET command.</param>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keyValues">Other key-value sets</param>
<typeparam name="T"></typeparam>
<returns>Always OK since MSET can't fail.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PSetExAsync``1(System.String,System.Int64,``0)">
<summary>
PSETEX command (An Asynchronous Version) <br /><br />
<br />
PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.<br /><br />
<br />
PSETEX 的工作方式与 SETEX 完全相同,唯一的区别是到期时间的单位是毫秒(ms),而不是秒(s)。<br /><br />
<br />
Document link: https://redis.io/commands/psetex <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="milliseconds">Timeout milliseconds value</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetAsync``1(System.String,``0,System.Int32)">
<summary>
SET key value EX seconds (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value.<br /><br />
<br />
设置键和值。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeoutSeconds">Timeout seconds</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetAsync``1(System.String,``0,System.Boolean)">
<summary>
SET key value KEEPTTL command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. Retain the time to live associated with the key. <br /><br />
<br />
设置键和值。<br /><br />
Document link: https://redis.io/commands/set <br />
Available since 6.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keepTtl">Retain the time to live associated with the key</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetNxAsync``1(System.String,``0,System.Int32)">
<summary>
SET key value EX seconds NX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
<br />
设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeoutSeconds">Timeout seconds</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetNxAsync``1(System.String,``0,System.TimeSpan)">
<summary>
SET key value EX seconds NX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
<br />
设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetXxAsync``1(System.String,``0,System.Int32)">
<summary>
SET key value EX seconds XX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it already exist.<br /><br />
<br />
设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeoutSeconds">Timeout seconds</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetXxAsync``1(System.String,``0,System.TimeSpan)">
<summary>
SET key value EX seconds XX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it already exist.<br /><br />
<br />
设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetXxAsync``1(System.String,``0,System.Boolean)">
<summary>
SET key value KEEPTTL XX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it already exist.<br /><br />
<br />
设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 6.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keepTtl">Retain the time to live associated with the key</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetAsync``1(System.String,``0,System.TimeSpan,System.Boolean,System.Boolean,System.Boolean,System.Boolean)">
<summary>
SET command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <br /><br />
<br />
设置键和值。如果该键已存在,则覆盖之。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout value</param>
<param name="keepTtl">Retain the time to live associated with the key</param>
<param name="nx">Only set the key if it does not already exist.</param>
<param name="xx">Only set the key if it already exist.</param>
<param name="get"></param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetAsync``1(System.String,``0,System.TimeSpan)">
<summary>
SET key value EX seconds (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value.<br /><br />
<br />
设置键和值。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetBitAsync(System.String,System.Int64,System.Boolean)">
<summary>
SETBIT command (An Asynchronous Version) <br /><br />
<br />
Sets or clears the bit at offset in the string value stored at key.<br /><br />
<br />
设置或清除键值字符串指定偏移量的位(bit)。<br /><br />
<br />
Document link: https://redis.io/commands/setbit <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<param name="offset">Offset value</param>
<param name="value">New value</param>
<returns>The original bit value stored at offset.</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetExAsync``1(System.String,System.Int32,``0)">
<summary>
SETEX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold the string value and set key to timeout after a given number of seconds.<br /><br />
<br />
设置键值在给定的秒数后超时。<br /><br />
<br />
Document link: https://redis.io/commands/setex <br />
Available since 2.0.0.
</summary>
<param name="key">Key</param>
<param name="seconds">Seconds</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetNxAsync``1(System.String,``0)">
<summary>
SETNX command (An Asynchronous Version) <br /><br />
<br />
Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. <br />
SETNX is short for "SET if Not eXists".<br /><br />
<br />
如果键值不存在,则设置该键值,在此情况下与 SET 指令相似。当键值已经存在时,不执行任何操作。<br /><br />
<br />
Document link: https://redis.io/commands/setnx <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
<returns>Set result, specifically: 1 is if the key was set; 0 is if the key was not set.</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetRangeAsync``1(System.String,System.Int64,``0)">
<summary>
SETRANGE command (An Asynchronous Version) <br /><br />
<br />
Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.<br /><br />
<br />
从给定的偏移量开始覆盖键所对应的字符串值。如果偏移量大于值的长度,则为该字符串填充零字节(zero-bytes)以满足偏移量的要求。若键值不存在则视作空字符串值。故本指令将确保有足够长度的字符串以适应偏移量的要求。<br /><br />
<br />
Document link: https://redis.io/commands/setrange <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<param name="offset">Offset value</param>
<param name="value">The value to be filled.</param>
<typeparam name="T"></typeparam>
<returns>The length of the string after it was modified by the command.</returns>
</member>
<member name="M:FreeRedis.RedisClient.StrLenAsync(System.String)">
<summary>
STRLRN command (An Asynchronous Version) <br /><br />
<br />
Returns the length of the string value stored at key. An error is returned when key holds a non-string value.<br /><br />
<br />
返回键对应值字符串的长度。当该键对应的值不是字符串,则返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/strlen <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<returns>The length of the string at key, or 0 when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Append``1(System.String,``0)">
<summary>
APPEND command (A Synchronized Version)<br /><br />
<br />
If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. <br /><br />
<br />
若键值已存在且为字符串,则此命令将值附加在字符串的末尾;<br />
若键值不存在,则会先创建一个空字符串,并附加值(在此情况下,APPEND 类似 SET 命令)。<br /><br />
<br />
Document link: https://redis.io/commands/append <br />
Available since 2.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
<returns>The length of the string after the append operation.</returns>
</member>
<member name="M:FreeRedis.RedisClient.BitCount(System.String,System.Int64,System.Int64)">
<summary>
BITCOUNT command (A Synchronized Version)<br /><br />
<br />
Count the number of set bits (population counting) in a string.<br /><br />
<br />
统计字符串中的位数。<br /><br />
<br />
Document link: https://redis.io/commands/bitcount <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
<param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
<returns>The number of set bits in the string. Non-existent keys are treated as empty strings and will return zero.</returns>
</member>
<member name="M:FreeRedis.RedisClient.BitOp(FreeRedis.BitOpOperation,System.String,System.String[])">
<summary>
BITOP command (A Synchronized Version) <br /><br />
<br />
Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.<br /><br />
<br />
在(包括字符串值)的多键之间按位运算,并将结果保存在目标键中。<br />
目前支持 AND、OR、XOR 与 NOT 四种运算方式。<br /><br />
<br />
Document link: https://redis.io/commands/bitop <br />
Available since 2.6.0.
</summary>
<param name="operation">Bit operation type: AND, OR, XOR or NOT</param>
<param name="destkey">Destination Key</param>
<param name="keys">Multiple keys (containing string values)</param>
<returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns>
</member>
<member name="M:FreeRedis.RedisClient.BitPos(System.String,System.Boolean,System.Nullable{System.Int64},System.Nullable{System.Int64})">
<summary>
BITPOS command (A Synchronized Version) <br /><br />
<br />
Return the position of the first bit set to 1 or 0 in a string.<br />
The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position 8, and so forth.<br /><br />
<br />
返回字符串中第一个 1 或 0 的位置。<br />
注意,本命令将字符串视作位数组,自左向右计算,第一个字节在位置 0,第二个字节在位置 8,以此类推。<br /><br />
<br />
Document link: https://redis.io/commands/bitpos <br />
Available since 2.8.7.
</summary>
<param name="key">Key</param>
<param name="bit">Bit value, 1 is true, 0 is false.</param>
<param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
<param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
<returns>Returns the position of the first bit set to 1 or 0 according to the request.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Decr(System.String)">
<summary>
DECR command (A Synchronized Version) <br /><br />
<br />
Decrements the number stored at key by one. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值减去 1。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/decr <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>the value of key after the decrement.</returns>
</member>
<member name="M:FreeRedis.RedisClient.DecrBy(System.String,System.Int64)">
<summary>
DECRBY command (A Synchronized Version) <br /><br />
<br />
Decrements the number stored at key by decrement. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值减去给定的值。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/decrby <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="decrement">The given value to be decreased.</param>
<returns>the value of key after the decrement.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Get(System.String)">
<summary>
GET command (A Synchronized Version) <br /><br />
<br />
Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
<br />
获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
<br />
Document link: https://redis.io/commands/get <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>The value of key, or nil when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Get``1(System.String)">
<summary>
GET command (A Synchronized Version) <br /><br />
<br />
Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
<br />
获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
<br />
Document link: https://redis.io/commands/get <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<typeparam name="T"></typeparam>
<returns>The value of key, or nil when key does not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Get(System.String,System.IO.Stream,System.Int32)">
<summary>
GET command (A Synchronized Version) <br /><br />
<br />
Get the value of key and write to the stream.. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
<br />
获得给定键的值并写入流中。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
<br />
Document link: https://redis.io/commands/get <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="destination">Destination stream</param>
<param name="bufferSize">Size</param>
</member>
<member name="M:FreeRedis.RedisClient.GetBit(System.String,System.Int64)">
<summary>
GETBIT command (A Synchronized Version) <br /><br />
<br />
Returns the bit value at offset in the string value stored at key.<br /><br />
<br />
返回键所对应字符串值中偏移量的位值。<br /><br />
<br />
Document link: https://redis.io/commands/getbit <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<param name="offset">Offset</param>
<returns>The bit value stored at offset.</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetRange(System.String,System.Int64,System.Int64)">
<summary>
GETRANGE command (A Synchronized Version) <br /><br />
<br />
Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
<br />
返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
<br />
Document link: https://redis.io/commands/getrange <br />
Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
</summary>
<param name="key">Key</param>
<param name="start">Start</param>
<param name="end">End</param>
<returns>The substring of the string value</returns>
</member>
<member name="M:FreeRedis.RedisClient.GetRange``1(System.String,System.Int64,System.Int64)">
<summary>
GETRANGE command (A Synchronized Version) <br /><br />
<br />
Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
<br />
返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
<br />
Document link: https://redis.io/commands/getrange <br />
Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
</summary>
<param name="key">Key</param>
<param name="start">Start</param>
<param name="end">End</param>
<typeparam name="T"></typeparam>
<returns></returns>
</member>
<member name="M:FreeRedis.RedisClient.GetSet``1(System.String,``0)">
<summary>
GETSET command (A Synchronized Version) <br /><br />
<br />
Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value.<br /><br />
<br />
以原子的方式将新值取代给定键的旧值,并返回旧值。如果该键存在但不包含字符串值时,返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/getset <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="value">New value</param>
<typeparam name="T"></typeparam>
<returns>The old value stored at key, or nil when key did not exist.</returns>
</member>
<member name="M:FreeRedis.RedisClient.Incr(System.String)">
<summary>
INCR command (A Synchronized Version) <br /><br />
<br />
Increments the number stored at key by one. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值加上 1。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/incr <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<returns>The value of key after the increment</returns>
</member>
<member name="M:FreeRedis.RedisClient.IncrBy(System.String,System.Int64)">
<summary>
INCRBY command (A Synchronized Version) <br /><br />
<br />
Decrements the number stored at key by increment. <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
This operation is limited to 64 bit signed integers.<br /><br />
<br />
对该键的值加上给定的值。<br />
如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
<br />
Document link: https://redis.io/commands/incrby <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="increment">The given value to be increased.</param>
<returns>The value of key after the increment</returns>
</member>
<member name="M:FreeRedis.RedisClient.IncrByFloat(System.String,System.Decimal)">
<summary>
INCRBYFLOAT command (A Synchronized Version) <br /><br />
<br />
Increment the string representing a floating point number stored at key by the specified increment. <br />
By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). <br />
If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:<br />
- The key contains a value of the wrong type (not a string).<br />
- The current key content or the specified increment are not parsable as a double precision floating point number.<br />
If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.<br /><br />
<br />
对该键的值加上给定的值,可以通过给定负值来减小对应键的值。<br />
如果键值不存在,则在操作前先设置为 0。如果发生以下情况,则返回错误:<br />
- 键所对应的值是错误的类型(不是字符串);<br />
- 该键的内容不能被解析为双精度浮点数。<br />
如果命令执行成功,则将新值替换旧值,并返回给调用方。<br /><br />
<br />
Document link: https://redis.io/commands/incrby <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="increment">The given value to be increased.</param>
<returns>The value of key after the increment.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MGet(System.String[])">
<summary>
MGET command (A Synchronized Version) <br /><br />
<br />
Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
<br />
返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
<br />
Document link: https://redis.io/commands/mget <br />
Available since 1.0.0.
</summary>
<param name="keys">Key list</param>
<returns>A list of values at the specified keys.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MGet``1(System.String[])">
<summary>
MGET command (A Synchronized Version) <br /><br />
<br />
Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
<br />
返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
<br />
Document link: https://redis.io/commands/mget <br />
Available since 1.0.0.
</summary>
<param name="keys">Key list</param>
<typeparam name="T"></typeparam>
<returns>A list of values at the specified keys.</returns>
</member>
<member name="M:FreeRedis.RedisClient.MSet(System.String,System.Object,System.Object[])">
<summary>
MSET command (A Synchronized Version) <br /><br />
<br />
Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
<br />
将给定键的值设置为对应的新值。 <br /><br />
<br />
Document link: https://redis.io/commands/mset <br />
Available since 1.0.1.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keyValues">Other key-value sets</param>
</member>
<member name="M:FreeRedis.RedisClient.MSet``1(System.Collections.Generic.Dictionary{System.String,``0})">
<summary>
MSET command (A Synchronized Version) <br /><br />
<br />
Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
<br />
将给定键的值设置为对应的新值。 <br /><br />
<br />
Document link: https://redis.io/commands/mset <br />
Available since 1.0.1.
</summary>
<param name="keyValues">Key-value sets</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.MSetNx(System.String,System.Object,System.Object[])">
<summary>
MSETNX command (A Synchronized Version) <br /><br />
<br />
Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
<br />
将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
<br />
Document link: https://redis.io/commands/msetnx <br />
Available since 1.0.1.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keyValues">Other key-value sets</param>
<returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
</member>
<member name="M:FreeRedis.RedisClient.MSetNx``1(System.Collections.Generic.Dictionary{System.String,``0})">
<summary>
MSETNX command (A Synchronized Version) <br /><br />
<br />
Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
<br />
将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
<br />
Document link: https://redis.io/commands/msetnx <br />
Available since 1.0.1.
</summary>
<param name="keyValues">Key-value sets</param>
<typeparam name="T"></typeparam>
<returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
</member>
<member name="M:FreeRedis.RedisClient.MSet``1(System.Boolean,System.String,System.Object,System.Object[])">
<summary>
MSET key value [key value ...] command (A Synchronized Version) <br /><br />
<br />
Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.<br /><br />
<br />
将给定键的值设置为对应的新值。如果不想覆盖现有的值,可以使用 MSETNX 指令。<br /><br />
<br />
Document link: https://redis.io/commands/mset <br />
Available since 1.0.1.
</summary>
<param name="nx">Mark whether it is NX mode. If it is, use the MSETNX command; otherwise, use the MSET command.</param>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keyValues">Other key-value sets</param>
<typeparam name="T"></typeparam>
<returns>Always OK since MSET can't fail.</returns>
</member>
<member name="M:FreeRedis.RedisClient.PSetEx``1(System.String,System.Int64,``0)">
<summary>
PSETEX command (A Synchronized Version) <br /><br />
<br />
PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.<br /><br />
<br />
PSETEX 的工作方式与 SETEX 完全相同,唯一的区别是到期时间的单位是毫秒(ms),而不是秒(s)。<br /><br />
<br />
Document link: https://redis.io/commands/psetex <br />
Available since 2.6.0.
</summary>
<param name="key">Key</param>
<param name="milliseconds">Timeout milliseconds value</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.Set``1(System.String,``0,System.Int32)">
<summary>
SET key value EX seconds (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value.<br /><br />
<br />
设置键和值。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeoutSeconds">Timeout seconds</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.Set``1(System.String,``0,System.TimeSpan)">
<summary>
SET key value EX seconds (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value.<br /><br />
<br />
设置键和值。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.Set``1(System.String,``0,System.Boolean)">
<summary>
SET key value KEEPTTL command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. Retain the time to live associated with the key. <br /><br />
<br />
设置键和值。<br /><br />
Document link: https://redis.io/commands/set <br />
Available since 6.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keepTtl">Retain the time to live associated with the key</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetNx``1(System.String,``0,System.Int32)">
<summary>
SET key value EX seconds NX command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
<br />
设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeoutSeconds">Timeout seconds</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetNx``1(System.String,``0,System.TimeSpan)">
<summary>
SET key value EX seconds NX command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
<br />
设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetXx``1(System.String,``0,System.Int32)">
<summary>
SET key value EX seconds XX command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it already exist.<br /><br />
<br />
设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeoutSeconds">Timeout seconds</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetXx``1(System.String,``0,System.TimeSpan)">
<summary>
SET key value EX seconds XX command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it already exist.<br /><br />
<br />
设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 2.6.12.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetXx``1(System.String,``0,System.Boolean)">
<summary>
SET key value KEEPTTL XX command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. Only set the key if it already exist.<br /><br />
<br />
设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 6.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="keepTtl">Retain the time to live associated with the key</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.Set``1(System.String,``0,System.TimeSpan,System.Boolean,System.Boolean,System.Boolean,System.Boolean)">
<summary>
SET command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <br /><br />
<br />
设置键和值。如果该键已存在,则覆盖之。<br /><br />
<br />
Document link: https://redis.io/commands/set <br />
Available since 6.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<param name="timeout">Timeout value</param>
<param name="keepTtl">Retain the time to live associated with the key</param>
<param name="nx">Only set the key if it does not already exist.</param>
<param name="xx">Only set the key if it already exist.</param>
<param name="get">Return the old value stored at key, or nil when key did not exist.</param>
<typeparam name="T"></typeparam>
<returns>
Simple string reply: OK if SET was executed correctly.<br />
Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetBit(System.String,System.Int64,System.Boolean)">
<summary>
SETBIT command (A Synchronized Version) <br /><br />
<br />
Sets or clears the bit at offset in the string value stored at key.<br /><br />
<br />
设置或清除键值字符串指定偏移量的位(bit)。<br /><br />
<br />
Document link: https://redis.io/commands/setbit <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<param name="offset">Offset value</param>
<param name="value">New value</param>
<returns>The original bit value stored at offset.</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetEx``1(System.String,System.Int32,``0)">
<summary>
SETEX command (A Synchronized Version) <br /><br />
<br />
Set key to hold the string value and set key to timeout after a given number of seconds.<br /><br />
<br />
设置键值在给定的秒数后超时。<br /><br />
<br />
Document link: https://redis.io/commands/setex <br />
Available since 2.0.0.
</summary>
<param name="key">Key</param>
<param name="seconds">Seconds</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
</member>
<member name="M:FreeRedis.RedisClient.SetNx``1(System.String,``0)">
<summary>
SETNX command (A Synchronized Version) <br /><br />
<br />
Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. <br />
SETNX is short for "SET if Not eXists".<br /><br />
<br />
如果键值不存在,则设置该键值,在此情况下与 SET 指令相似。当键值已经存在时,不执行任何操作。<br /><br />
<br />
Document link: https://redis.io/commands/setnx <br />
Available since 1.0.0.
</summary>
<param name="key">Key</param>
<param name="value">Value</param>
<typeparam name="T"></typeparam>
<returns>Set result, specifically: 1 is if the key was set; 0 is if the key was not set.</returns>
</member>
<member name="M:FreeRedis.RedisClient.SetRange``1(System.String,System.Int64,``0)">
<summary>
SETRANGE command (A Synchronized Version) <br /><br />
<br />
Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.<br /><br />
<br />
从给定的偏移量开始覆盖键所对应的字符串值。如果偏移量大于值的长度,则为该字符串填充零字节(zero-bytes)以满足偏移量的要求。若键值不存在则视作空字符串值。故本指令将确保有足够长度的字符串以适应偏移量的要求。<br /><br />
<br />
Document link: https://redis.io/commands/setrange <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<param name="offset">Offset value</param>
<param name="value">The value to be filled.</param>
<typeparam name="T"></typeparam>
<returns>The length of the string after it was modified by the command.</returns>
</member>
<member name="M:FreeRedis.RedisClient.StrLen(System.String)">
<summary>
STRLRN command (A Synchronized Version) <br /><br />
<br />
Returns the length of the string value stored at key. An error is returned when key holds a non-string value.<br /><br />
<br />
返回键对应值字符串的长度。当该键对应的值不是字符串,则返回错误。<br /><br />
<br />
Document link: https://redis.io/commands/strlen <br />
Available since 2.2.0.
</summary>
<param name="key">Key</param>
<returns>The length of the string at key, or 0 when key does not exist.</returns>
</member>
<member name="T:FreeRedis.ZAddThan">
<summary>
redis version >=6.2: Added the GT and LT options.
</summary>
</member>
<member name="T:FreeRedis.DelayQueue">
<summary>
延时队列
</summary>
</member>
<member name="M:FreeRedis.DelayQueue.Enqueue(System.String,System.TimeSpan)">
<summary>
写入延时队列
</summary>
<param name="value">队列值:值不可重复</param>
<param name="delay">延迟执行时间</param>
<returns></returns>
</member>
<member name="M:FreeRedis.DelayQueue.Enqueue(System.String,System.DateTime)">
<summary>
写入延时队列
</summary>
<param name="value">队列值:值不可重复</param>
<param name="delay">延迟执行时间</param>
<returns></returns>
</member>
<member name="M:FreeRedis.DelayQueue.Dequeue(System.Action{System.String},System.Int32,System.Nullable{System.Threading.CancellationToken})">
<summary>
消费延时队列,多个消费端不会重复
</summary>
<param name="action">消费委托</param>
<param name="choke">轮询队列时长,默认400毫秒,值越小越准确</param>
</member>
<member name="M:FreeRedis.DelayQueue.DequeueAsync(System.Func{System.String,System.Threading.Tasks.Task},System.Int32,System.Nullable{System.Threading.CancellationToken})">
<summary>
消费延时队列,多个消费端不会重复
</summary>
<param name="action">消费委托</param>
<param name="choke">轮询队列时长,默认400毫秒,值越小越准确</param>
<param name="token"></param>
</member>
</members>
</doc>
|
2881099/FreeRedis | 54,843 | src/FreeRedis/CommandSets.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
namespace FreeRedis
{
public class CommandSets
{
public ServerFlag Flag { get; }
public ServerTag Tag { get; }
public LocalStatus Status { get; private set; }
public CommandSets(ServerFlag flag, ServerTag tag, LocalStatus status)
{
this.Flag = flag;
this.Tag = tag;
this.Status = status;
}
public static List<string> _allCommands { get; }
static Dictionary<string, CommandSets> _dicOptions { get; }
public static CommandSets Get(string command)
{
if (string.IsNullOrWhiteSpace(command)) return null;
return _dicOptions.TryGetValue(command?.ToUpper().Trim(), out var options) ? options : null;
}
public static void Register(string command, CommandSets options)
{
command = command?.ToUpper().Trim();
if (string.IsNullOrWhiteSpace(command)) throw new ArgumentException(nameof(command));
if (options == null) throw new ArgumentNullException(nameof(options));
if (_dicOptions.ContainsKey(command) == false) throw new Exception($"The command \"{command}\" is already registered");
_dicOptions.Add(command, options);
}
[Flags]
public enum LocalStatus : long
{
none = 1,
check_single = 1 << 1,
}
static CommandSets()
{
#region _allCommands
_allCommands = new List<string>
{
//"BF.RESERVE",
//"BF.ADD",
//"BF.MADD",
//"BF.INSERT",
//"BF.EXISTS",
//"BF.MEXISTS",
//"BF.SCANDUMP",
//"BF.LOADCHUNK",
//"BF.INFO",
//"CMS.INITBYDIM",
//"CMS.INITBYPROB",
//"CMS.INCRBY",
//"CMS.INCRBY",
//"CMS.QUERY",
//"CMS.MERGE",
//"CMS.INFO",
//"CF.RESERVE",
//"CF.ADD",
//"CF.ADDNX",
//"CF.INSERT",
//"CF.INSERTNX",
//"CF.EXISTS",
//"CF.DEL",
//"CF.COUNT",
//"CF.SCANDUMP",
//"CF.LOADCHUNK",
//"CF.INFO",
//"TOPK.RESERVE",
//"TOPK.ADD",
//"TOPK.INCRBY",
//"TOPK.QUERY",
//"TOPK.COUNT",
//"TOPK.LIST",
//"TOPK.INFO",
//"CLUSTER ADDSLOTS",
//"CLUSTER BUMPEPOCH",
//"CLUSTER COUNT-FAILURE-REPORTS",
//"CLUSTER COUNTKEYSINSLOT",
//"CLUSTER DELSLOTS",
//"CLUSTER FAILOVER",
//"CLUSTER FLUSHSLOTS",
//"CLUSTER FORGET",
//"CLUSTER GETKEYSINSLOT",
//"CLUSTER INFO",
//"CLUSTER KEYSLOT",
//"CLUSTER MEET",
//"CLUSTER MYID",
//"CLUSTER NODES",
//"CLUSTER REPLICAS",
//"CLUSTER REPLICATE",
//"CLUSTER RESET",
//"CLUSTER SAVECONFIG",
//"CLUSTER SET-CONFIG-EPOCH",
//"CLUSTER SLAVES",
//"CLUSTER SLOTS",
//"READONLY",
//"READWRITE",
//"AUTH",
//"CLIENT CACHING",
//"CLIENT GETNAME",
//"CLIENT GETREDIR",
//"CLIENT ID",
//"CLIENT KILL",
//"CLIENT LIST",
//"CLIENT PAUSE",
//"CLIENT REPLY",
//"CLIENT SETNAME",
//"CLIENT TRACKING",
//"CLIENT UNBLOCK",
//"ECHO",
//"HELLO ",
//"PING ",
//"QUIT",
//"SELECT",
//"GEOADD",
//"GEODIST",
//"GEOHASH",
//"GEOPOS",
//"GEORADIUS",
//"GEORADIUSBYMEMBER",
//"HDEL",
//"HEXISTS",
//"HGET",
//"HGETALL",
//"HINCRBY",
//"HINCRBYFLOAT",
//"HKEYS",
//"HLEN",
//"HMGET",
//"HMSET",
//"HSCAN",
//"HSET",
//"HSETNX",
//"HSTRLEN",
//"HVALS",
//"PFADD",
//"PFCOUNT",
//"PFMERGE",
//"DEL",
//"DUMP",
//"EXISTS",
//"EXPIRE",
//"EXPIREAT",
//"KEYS",
//"MIGRATE",
//"MOVE",
//"OBJECT REFCOUNT",
//"OBJECT IDLETIME",
//"OBJECT ENCODING",
//"OBJECT FREQ",
//"OBJECT HELP",
//"PERSIST",
//"PEXPIRE",
//"PEXPIREAT",
//"PTTL",
//"RANDOMKEY",
//"RENAME",
//"RENAMENX",
//"RESTORE",
//"SCAN",
//"SORT",
//"TOUCH",
//"TTL",
//"TYPE",
//"UNLINK",
//"WAIT",
//"BLPOP",
//"BRPOP",
//"BRPOPLPUSH",
//"LINDEX",
//"LINSERT",
//"LLEN",
//"LPOP",
//"LPOS",
//"LPUSH",
//"LPUSHX",
//"LRANGE",
//"LREM",
//"LSET",
//"LTRIM",
//"RPOP",
//"RPOPLPUSH",
//"RPUSH",
//"RPUSHX",
//"EVAL",
//"EVALSHA",
//"SCRIPT DEBUG",
//"SCRIPT EXISTS",
//"SCRIPT FLUSH",
//"SCRIPT KILL",
//"SCRIPT LOAD",
//"ACL CAT",
//"ACL DELUSER",
//"ACL GENPASS",
//"ACL GETUSER",
//"ACL HELP",
//"ACL LIST",
//"ACL LOAD",
//"ACL LOG",
//"ACL SAVE",
//"ACL SETUSER",
//"ACL USERS",
//"ACL WHOAMI",
//"BGREWRITEAOF",
//"BGSAVE",
//"COMMAND",
//"COMMAND COUNT",
//"COMMAND GETKEYS",
//"COMMAND INFO",
//"CONFIG GET",
//"CONFIG RESETSTAT",
//"CONFIG REWRITE",
//"CONFIG SET",
//"DBSIZE",
//"DEBUG OBJECT",
//"DEBUG SEGFAULT",
//"FLUSHALL",
//"FLUSHDB",
//"INFO",
//"LASTSAVE",
//"LATENCY DOCTOR",
//"LATENCY GRAPH",
//"LATENCY HELP",
//"LATENCY HISTORY",
//"LATENCY LATEST",
//"LATENCY RESET",
//"LOLWUT",
//"MEMORY DOCTOR",
//"MEMORY HELP",
//"MEMORY MALLOC-STATS",
//"MEMORY PURGE",
//"MEMORY STATS",
//"MEMORY USAGE",
//"MODULE LIST",
//"MODULE LOAD",
//"MODULE UNLOAD",
//"MONITOR",
//"REPLICAOF",
//"ROLE",
//"SAVE",
//"SHUTDOWN",
//"SLOWLOG",
//"SWAPDB",
//"SYNC",
//"TIME",
//"SADD",
//"SCARD",
//"SDIFF",
//"SDIFFSTORE",
//"SINTER",
//"SINTERSTORE",
//"SISMEMBER",
//"SMEMBERS",
//"SMISMEMBER",
//"SMOVE",
//"SPOP",
//"SRANDMEMBER",
//"SREM",
//"SSCAN",
//"SUNION",
//"SUNIONSTORE",
//"BZPOPMAX",
//"BZPOPMIN",
//"ZADD",
//"ZCARD",
//"ZCOUNT",
//"ZINCRBY",
//"ZINTERSTORE",
//"ZLEXCOUNT",
//"ZPOPMAX",
//"ZPOPMIN",
//"ZRANGE",
//"ZRANGEBYLEX",
//"ZRANGEBYSCORE",
//"ZRANK",
//"ZREM",
//"ZREMRANGEBYLEX",
//"ZREMRANGEBYRANK",
//"ZREMRANGEBYSCORE",
//"ZREVRANGE",
//"ZREVRANGEBYLEX",
//"ZREVRANGEBYSCORE",
//"ZREVRANK",
//"ZSCAN",
//"ZSCORE",
//"XACK",
//"XADD",
//"XCLAIM",
//"XDEL",
//"XGROUP CREATE",
//"XGROUP SETID",
//"XGROUP DESTROY",
//"XGROUP DELCONSUMER",
//"XINFO STREAM",
//"XINFO GROUPS",
//"XINFO CONSUMERS",
//"XLEN",
//"XPENDING",
//"XRANGE",
//"XREVRANGE",
//"XREAD",
//"XREADGROUP",
//"XTRIM",
//"APPEND",
//"BITCOUNT",
//"BITFIELD",
//"BITOP",
//"BITPOS",
//"DECR",
//"DECRBY",
//"GET",
//"GETBIT",
//"GETRANGE",
//"GETSET",
//"INCR",
//"INCRBY",
//"INCRBYFLOAT",
//"MGET",
//"MSET",
//"MSETNX",
//"PSETEX",
//"SET",
//"SETBIT",
//"SETEX",
//"SETNX",
//"SETRANGE",
//"STRALGO",
//"STRLEN",
//"DISCARD",
//"EXEC",
//"MULTI",
//"UNWATCH",
//"WATCH",
};
#endregion
_dicOptions = new Dictionary<string, CommandSets>
{
#region 此部分是生成的代码
["BF.RESERVE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.ADD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.MADD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.INSERT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.EXISTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.MEXISTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.SCANDUMP"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.LOADCHUNK"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BF.INFO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.INITBYDIM"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.INITBYPROB"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.INCRBY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.INCRBY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.QUERY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.MERGE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CMS.INFO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.RESERVE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.ADD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.ADDNX"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.INSERT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.INSERTNX"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.EXISTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.DEL"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.COUNT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.SCANDUMP"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.LOADCHUNK"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CF.INFO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.RESERVE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.ADD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.INCRBY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.QUERY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.COUNT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.LIST"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["TOPK.INFO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER ADDSLOTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER BUMPEPOCH"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER COUNT-FAILURE-REPORTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER COUNTKEYSINSLOT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER DELSLOTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER FAILOVER"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER FLUSHSLOTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER FORGET"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER GETKEYSINSLOT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER INFO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER KEYSLOT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER MEET"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER MYID"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER NODES"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER REPLICAS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER REPLICATE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER RESET"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER SAVECONFIG"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER SET-CONFIG-EPOCH"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER SLAVES"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLUSTER SLOTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["READONLY"] = new CommandSets(ServerFlag.fast, ServerTag.keyspace | ServerTag.fast, LocalStatus.none),
["READWRITE"] = new CommandSets(ServerFlag.fast, ServerTag.keyspace | ServerTag.fast, LocalStatus.none),
["AUTH"] = new CommandSets(ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale | ServerFlag.skip_monitor | ServerFlag.skip_slowlog | ServerFlag.fast | ServerFlag.no_auth, ServerTag.fast | ServerTag.connection, LocalStatus.none),
["CLIENT CACHING"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT GETNAME"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT GETREDIR"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT ID"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT KILL"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT LIST"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT PAUSE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT REPLY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT SETNAME"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT TRACKING"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CLIENT UNBLOCK"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ECHO"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.fast | ServerTag.connection, LocalStatus.none),
["HELLO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["PING"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["QUIT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["SELECT"] = new CommandSets(ServerFlag.loading | ServerFlag.stale | ServerFlag.fast, ServerTag.keyspace | ServerTag.fast, LocalStatus.none),
["GEOADD"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.geo | ServerTag.slow, LocalStatus.none),
["GEODIST"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.geo | ServerTag.slow, LocalStatus.none),
["GEOHASH"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.geo | ServerTag.slow, LocalStatus.none),
["GEOPOS"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.geo | ServerTag.slow, LocalStatus.none),
["GEORADIUS"] = new CommandSets(ServerFlag.write | ServerFlag.movablekeys, ServerTag.write | ServerTag.geo | ServerTag.slow, LocalStatus.none),
["GEORADIUSBYMEMBER"] = new CommandSets(ServerFlag.write | ServerFlag.movablekeys, ServerTag.write | ServerTag.geo | ServerTag.slow, LocalStatus.none),
["HDEL"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HEXISTS"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HGET"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HGETALL"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.read | ServerTag.hash | ServerTag.slow, LocalStatus.none),
["HINCRBY"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HINCRBYFLOAT"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HKEYS"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.read | ServerTag.hash | ServerTag.slow, LocalStatus.none),
["HLEN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HMGET"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HMSET"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HSCAN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.read | ServerTag.hash | ServerTag.slow, LocalStatus.none),
["HSET"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HSETNX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HSTRLEN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.hash | ServerTag.fast, LocalStatus.none),
["HVALS"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.read | ServerTag.hash | ServerTag.slow, LocalStatus.none),
["PFADD"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.hyperloglog | ServerTag.fast, LocalStatus.none),
["PFCOUNT"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.hyperloglog | ServerTag.slow, LocalStatus.none),
["PFMERGE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.hyperloglog | ServerTag.slow, LocalStatus.none),
["DEL"] = new CommandSets(ServerFlag.write, ServerTag.keyspace | ServerTag.write | ServerTag.slow, LocalStatus.none),
["DUMP"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.keyspace | ServerTag.read | ServerTag.slow, LocalStatus.none),
["EXISTS"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.keyspace | ServerTag.read | ServerTag.fast, LocalStatus.none),
["EXPIRE"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["EXPIREAT"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["KEYS"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.keyspace | ServerTag.read | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["MIGRATE"] = new CommandSets(ServerFlag.write | ServerFlag.random | ServerFlag.movablekeys, ServerTag.keyspace | ServerTag.write | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["MOVE"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["OBJECT REFCOUNT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["OBJECT IDLETIME"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["OBJECT ENCODING"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["OBJECT FREQ"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["OBJECT HELP"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["PERSIST"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["PEXPIRE"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["PEXPIREAT"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["PTTL"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random | ServerFlag.fast, ServerTag.keyspace | ServerTag.read | ServerTag.fast, LocalStatus.none),
["RANDOMKEY"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.keyspace | ServerTag.read | ServerTag.slow, LocalStatus.none),
["RENAME"] = new CommandSets(ServerFlag.write, ServerTag.keyspace | ServerTag.write | ServerTag.slow, LocalStatus.none),
["RENAMENX"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["RESTORE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.keyspace | ServerTag.write | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["SCAN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.keyspace | ServerTag.read | ServerTag.slow, LocalStatus.none),
["SORT"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.movablekeys, ServerTag.write | ServerTag.set | ServerTag.sortedset | ServerTag.list | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["TOUCH"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.keyspace | ServerTag.read | ServerTag.fast, LocalStatus.none),
["TTL"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random | ServerFlag.fast, ServerTag.keyspace | ServerTag.read | ServerTag.fast, LocalStatus.none),
["TYPE"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.keyspace | ServerTag.read | ServerTag.fast, LocalStatus.none),
["UNLINK"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast, LocalStatus.none),
["WAIT"] = new CommandSets(ServerFlag.noscript, ServerTag.keyspace | ServerTag.slow, LocalStatus.none),
["BLPOP"] = new CommandSets(ServerFlag.write | ServerFlag.noscript, ServerTag.write | ServerTag.list | ServerTag.slow | ServerTag.blocking, LocalStatus.none),
["BRPOP"] = new CommandSets(ServerFlag.write | ServerFlag.noscript, ServerTag.write | ServerTag.list | ServerTag.slow | ServerTag.blocking, LocalStatus.none),
["BRPOPLPUSH"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.noscript, ServerTag.write | ServerTag.list | ServerTag.slow | ServerTag.blocking, LocalStatus.none),
["LINDEX"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.list | ServerTag.slow, LocalStatus.none),
["LINSERT"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.list | ServerTag.slow, LocalStatus.none),
["LLEN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.list | ServerTag.fast, LocalStatus.none),
["LPOP"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.list | ServerTag.fast, LocalStatus.none),
["LPOS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LPUSH"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.list | ServerTag.fast, LocalStatus.none),
["LPUSHX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.list | ServerTag.fast, LocalStatus.none),
["LRANGE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.list | ServerTag.slow, LocalStatus.none),
["LREM"] = new CommandSets(ServerFlag.write, ServerTag.write | ServerTag.list | ServerTag.slow, LocalStatus.none),
["LSET"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.list | ServerTag.slow, LocalStatus.none),
["LTRIM"] = new CommandSets(ServerFlag.write, ServerTag.write | ServerTag.list | ServerTag.slow, LocalStatus.none),
["RPOP"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.list | ServerTag.fast, LocalStatus.none),
["RPOPLPUSH"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.list | ServerTag.slow, LocalStatus.none),
["RPUSH"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.list | ServerTag.fast, LocalStatus.none),
["RPUSHX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.list | ServerTag.fast, LocalStatus.none),
["EVAL"] = new CommandSets(ServerFlag.noscript | ServerFlag.movablekeys, ServerTag.slow | ServerTag.scripting, LocalStatus.none),
["EVALSHA"] = new CommandSets(ServerFlag.noscript | ServerFlag.movablekeys, ServerTag.slow | ServerTag.scripting, LocalStatus.none),
["SCRIPT DEBUG"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["SCRIPT EXISTS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["SCRIPT FLUSH"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["SCRIPT KILL"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["SCRIPT LOAD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL CAT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL DELUSER"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL GENPASS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL GETUSER"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL HELP"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL LIST"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL LOAD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL LOG"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL SAVE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL SETUSER"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL USERS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["ACL WHOAMI"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["BGREWRITEAOF"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["BGSAVE"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["COMMAND"] = new CommandSets(ServerFlag.random | ServerFlag.loading | ServerFlag.stale, ServerTag.slow | ServerTag.connection, LocalStatus.none),
["COMMAND COUNT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["COMMAND GETKEYS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["COMMAND INFO"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CONFIG GET"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CONFIG RESETSTAT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CONFIG REWRITE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["CONFIG SET"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["DBSIZE"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.keyspace | ServerTag.read | ServerTag.fast, LocalStatus.none),
["DEBUG OBJECT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["DEBUG SEGFAULT"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["FLUSHALL"] = new CommandSets(ServerFlag.write, ServerTag.keyspace | ServerTag.write | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["FLUSHDB"] = new CommandSets(ServerFlag.write, ServerTag.keyspace | ServerTag.write | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["INFO"] = new CommandSets(ServerFlag.random | ServerFlag.loading | ServerFlag.stale, ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["LASTSAVE"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random | ServerFlag.loading | ServerFlag.stale | ServerFlag.fast, ServerTag.read | ServerTag.admin | ServerTag.fast | ServerTag.dangerous, LocalStatus.none),
["LATENCY DOCTOR"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LATENCY GRAPH"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LATENCY HELP"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LATENCY HISTORY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LATENCY LATEST"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LATENCY RESET"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["LOLWUT"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.fast, LocalStatus.none),
["MEMORY DOCTOR"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MEMORY HELP"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MEMORY MALLOC-STATS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MEMORY PURGE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MEMORY STATS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MEMORY USAGE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MODULE LIST"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MODULE LOAD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MODULE UNLOAD"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["MONITOR"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["REPLICAOF"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript | ServerFlag.stale, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["ROLE"] = new CommandSets(ServerFlag.@readonly | ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale | ServerFlag.fast, ServerTag.read | ServerTag.fast | ServerTag.dangerous, LocalStatus.none),
["SAVE"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["SHUTDOWN"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["SLOWLOG"] = new CommandSets(ServerFlag.admin | ServerFlag.random | ServerFlag.loading | ServerFlag.stale, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["SWAPDB"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.keyspace | ServerTag.write | ServerTag.fast | ServerTag.dangerous, LocalStatus.none),
["SYNC"] = new CommandSets(ServerFlag.admin | ServerFlag.noscript, ServerTag.admin | ServerTag.slow | ServerTag.dangerous, LocalStatus.none),
["TIME"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random | ServerFlag.loading | ServerFlag.stale | ServerFlag.fast, ServerTag.read | ServerTag.fast, LocalStatus.none),
["SADD"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.set | ServerTag.fast, LocalStatus.none),
["SCARD"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.set | ServerTag.fast, LocalStatus.none),
["SDIFF"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.read | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SDIFFSTORE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SINTER"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.read | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SINTERSTORE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SISMEMBER"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.set | ServerTag.fast, LocalStatus.none),
["SMEMBERS"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.read | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SMISMEMBER"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["SMOVE"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.set | ServerTag.fast, LocalStatus.none),
["SPOP"] = new CommandSets(ServerFlag.write | ServerFlag.random | ServerFlag.fast, ServerTag.write | ServerTag.set | ServerTag.fast, LocalStatus.none),
["SRANDMEMBER"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.read | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SREM"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.set | ServerTag.fast, LocalStatus.none),
["SSCAN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.read | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SUNION"] = new CommandSets(ServerFlag.@readonly | ServerFlag.sort_for_script, ServerTag.read | ServerTag.set | ServerTag.slow, LocalStatus.none),
["SUNIONSTORE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.set | ServerTag.slow, LocalStatus.none),
["BZPOPMAX"] = new CommandSets(ServerFlag.write | ServerFlag.noscript | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast | ServerTag.blocking, LocalStatus.none),
["BZPOPMIN"] = new CommandSets(ServerFlag.write | ServerFlag.noscript | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast | ServerTag.blocking, LocalStatus.none),
["ZADD"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZCARD"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZCOUNT"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZINCRBY"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZINTERSTORE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.movablekeys, ServerTag.write | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZLEXCOUNT"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZPOPMAX"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZPOPMIN"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZRANGE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZRANGEBYLEX"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZRANGEBYSCORE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZRANK"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZREM"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZREMRANGEBYLEX"] = new CommandSets(ServerFlag.write, ServerTag.write | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZREMRANGEBYRANK"] = new CommandSets(ServerFlag.write, ServerTag.write | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZREMRANGEBYSCORE"] = new CommandSets(ServerFlag.write, ServerTag.write | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZREVRANGE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZREVRANGEBYLEX"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZREVRANGEBYSCORE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZREVRANK"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["ZSCAN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.read | ServerTag.sortedset | ServerTag.slow, LocalStatus.none),
["ZSCORE"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.sortedset | ServerTag.fast, LocalStatus.none),
["XACK"] = new CommandSets(ServerFlag.write | ServerFlag.random | ServerFlag.fast, ServerTag.write | ServerTag.stream | ServerTag.fast, LocalStatus.none),
["XADD"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.random | ServerFlag.fast, ServerTag.write | ServerTag.stream | ServerTag.fast, LocalStatus.none),
["XCLAIM"] = new CommandSets(ServerFlag.write | ServerFlag.random | ServerFlag.fast, ServerTag.write | ServerTag.stream | ServerTag.fast, LocalStatus.none),
["XDEL"] = new CommandSets(ServerFlag.write | ServerFlag.fast, ServerTag.write | ServerTag.stream | ServerTag.fast, LocalStatus.none),
["XGROUP CREATE"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XGROUP SETID"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XGROUP DESTROY"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XGROUP DELCONSUMER"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XINFO STREAM"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XINFO GROUPS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XINFO CONSUMERS"] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none),
["XLEN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.stream | ServerTag.fast, LocalStatus.none),
["XPENDING"] = new CommandSets(ServerFlag.@readonly | ServerFlag.random, ServerTag.read | ServerTag.stream | ServerTag.slow, LocalStatus.none),
["XRANGE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.stream | ServerTag.slow, LocalStatus.none),
["XREVRANGE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.stream | ServerTag.slow, LocalStatus.none),
["XREAD"] = new CommandSets(ServerFlag.@readonly | ServerFlag.movablekeys, ServerTag.read | ServerTag.stream | ServerTag.slow | ServerTag.blocking, LocalStatus.none),
["XREADGROUP"] = new CommandSets(ServerFlag.write | ServerFlag.movablekeys, ServerTag.write | ServerTag.stream | ServerTag.slow | ServerTag.blocking, LocalStatus.none),
["XTRIM"] = new CommandSets(ServerFlag.write | ServerFlag.random, ServerTag.write | ServerTag.stream | ServerTag.slow, LocalStatus.none),
["APPEND"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["BITCOUNT"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.bitmap | ServerTag.slow, LocalStatus.none),
["BITFIELD"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.bitmap | ServerTag.slow, LocalStatus.none),
["BITOP"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.bitmap | ServerTag.slow, LocalStatus.none),
["BITPOS"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.bitmap | ServerTag.slow, LocalStatus.none),
["DECR"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["DECRBY"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["GET"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["GETBIT"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.bitmap | ServerTag.fast, LocalStatus.none),
["GETRANGE"] = new CommandSets(ServerFlag.@readonly, ServerTag.read | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["GETSET"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["INCR"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["INCRBY"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["INCRBYFLOAT"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["MGET"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["MSET"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["MSETNX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["PSETEX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["SET"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["SETBIT"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.bitmap | ServerTag.slow, LocalStatus.none),
["SETEX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["SETNX"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom | ServerFlag.fast, ServerTag.write | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["SETRANGE"] = new CommandSets(ServerFlag.write | ServerFlag.denyoom, ServerTag.write | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["STRALGO"] = new CommandSets(ServerFlag.@readonly | ServerFlag.movablekeys, ServerTag.read | ServerTag.@string | ServerTag.slow, LocalStatus.none),
["STRLEN"] = new CommandSets(ServerFlag.@readonly | ServerFlag.fast, ServerTag.read | ServerTag.@string | ServerTag.fast, LocalStatus.none),
["DISCARD"] = new CommandSets(ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale | ServerFlag.fast, ServerTag.fast | ServerTag.transaction, LocalStatus.none),
["EXEC"] = new CommandSets(ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale | ServerFlag.skip_monitor | ServerFlag.skip_slowlog, ServerTag.slow | ServerTag.transaction, LocalStatus.none),
["MULTI"] = new CommandSets(ServerFlag.noscript | ServerFlag.loading | ServerFlag.stale | ServerFlag.fast, ServerTag.fast | ServerTag.transaction, LocalStatus.none),
["UNWATCH"] = new CommandSets(ServerFlag.noscript | ServerFlag.fast, ServerTag.fast | ServerTag.transaction, LocalStatus.none),
["WATCH"] = new CommandSets(ServerFlag.noscript | ServerFlag.fast, ServerTag.fast | ServerTag.transaction, LocalStatus.none),
#endregion
};
Get("AUTH").Status = LocalStatus.check_single;
Get("CLIENT CACHING").Status = LocalStatus.check_single;
Get("CLIENT GETNAME").Status = LocalStatus.check_single;
Get("CLIENT GETREDIR").Status = LocalStatus.check_single;
Get("CLIENT ID").Status = LocalStatus.check_single;
Get("CLIENT REPLY").Status = LocalStatus.check_single;
Get("CLIENT SETNAME").Status = LocalStatus.check_single;
Get("CLIENT TRACKING").Status = LocalStatus.check_single;
Get("HELLO").Status = LocalStatus.check_single;
Get("QUIT").Status = LocalStatus.check_single;
Get("SELECT").Status = LocalStatus.check_single;
//Get("SCRIPT KILL").Status = LocalStatus.check_single;
}
[Flags]
public enum ServerFlag : long
{
none = 1,
/// <summary>
/// command may result in modifications
/// </summary>
write = 1 << 1,
/// <summary>
/// command will never modify keys
/// </summary>
@readonly = 1 << 2,
/// <summary>
/// reject command if currently out of memory
/// </summary>
denyoom = 1 << 3,
/// <summary>
/// server admin command
/// </summary>
admin = 1 << 4,
/// <summary>
/// pubsub-related command
/// </summary>
pubsub = 1 << 5,
/// <summary>
/// deny this command from scripts
/// </summary>
noscript = 1 << 6,
/// <summary>
/// command has random results, dangerous for scripts
/// </summary>
random = 1 << 7,
/// <summary>
/// if called from script, sort output
/// </summary>
sort_for_script = 1 << 8,
/// <summary>
/// allow command while database is loading
/// </summary>
loading = 1 << 9,
/// <summary>
/// allow command while replica has stale data
/// </summary>
stale = 1 << 10,
/// <summary>
/// do not show this command in MONITOR
/// </summary>
skip_monitor = 1 << 11,
/// <summary>
/// cluster related - accept even if importing
/// </summary>
asking = 1 << 12,
/// <summary>
/// command operates in constant or log(N) time. Used for latency monitoring.
/// </summary>
fast = 1 << 13,
/// <summary>
/// keys have no pre-determined position. You must discover keys yourself.
/// </summary>
movablekeys = 1 << 14,
no_auth = 1 << 15,
/// <summary>
/// do not show this command in SLOWLOG
/// </summary>
skip_slowlog = 1 << 16,
}
[Flags]
public enum ServerTag : long
{
none = 1,
admin = 1 << 1,
bitmap = 1 << 2,
blocking = 1 << 3,
connection = 1 << 4,
dangerous = 1 << 5,
fast = 1 << 6,
geo = 1 << 7,
hash = 1 << 8,
hyperloglog = 1 << 9,
keyspace = 1 << 10,
list = 1 << 11,
pubsub = 1 << 12,
read = 1 << 13,
scripting = 1 << 14,
set = 1 << 15,
slow = 1 << 16,
sortedset = 1 << 17,
stream = 1 << 18,
@string = 1 << 19,
transaction = 1 << 20,
write = 1 << 21,
}
}
}
|
2881099/FreeRedis | 12,074 | src/FreeRedis/CommandPacket.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace FreeRedis
{
public class CommandPacket
{
public string _command { get; private set; }
public string _subcommand { get; private set; }
public List<object> _input { get; } = new List<object>();
public List<int> _keyIndexes { get; } = new List<int>();
public string _prefix { get; internal set; }
internal bool? _IsIgnoreAop;
public bool IsIgnoreAop
{
get => _IsIgnoreAop ?? false;
set => _IsIgnoreAop = value;
}
public string GetKey(int index, bool withoutPrefix = false)
{
if (withoutPrefix && !string.IsNullOrWhiteSpace(_prefix))
return _input[_keyIndexes[index]].ToInvariantCultureToString().Substring(_prefix.Length);
return _input[_keyIndexes[index]].ToInvariantCultureToString();
}
public static implicit operator List<object>(CommandPacket cb) => cb._input;
public static implicit operator CommandPacket(string cmd) => new CommandPacket(cmd);
public override string ToString()
{
var sb = new StringBuilder();
for (var b = 0; b < _input.Count; b++)
{
if (b > 0) sb.Append(" ");
var tmpstr = _input[b].ToInvariantCultureToString().Replace("\r\n", "\\r\\n");
if (_command == "EVAL" && b > 0) tmpstr = $"\"{tmpstr}\"";
else if (tmpstr.Length > 96) tmpstr = $"{tmpstr.Substring(0, 96).Trim()}..";
sb.Append(tmpstr);
}
return sb.ToString();
}
internal Queue<Action<RedisResult>> _ondata;
public CommandPacket OnData(Action<RedisResult> ondata)
{
if (_ondata == null) _ondata = new Queue<Action<RedisResult>>();
_ondata.Enqueue(ondata);
return this;
}
internal void OnDataTrigger(RedisResult rt)
{
if (_ondata == null) return;
while (_ondata.Any())
_ondata.Dequeue()(rt);
}
public CommandPacket Prefix(string prefix)
{
if (string.IsNullOrWhiteSpace(prefix)) return this;
if (prefix == _prefix) return this;
if (!string.IsNullOrWhiteSpace(_prefix))
{
foreach (var idx in _keyIndexes)
{
var key = _input[idx].ToInvariantCultureToString();
if (key?.StartsWith(_prefix) == true)
_input[idx] = key.Substring(_prefix.Length);
}
}
_prefix = prefix;
foreach (var idx in _keyIndexes)
_input[idx] = $"{prefix}{_input[idx]}";
return this;
}
internal int _protocolErrorTryCount;
internal bool _clusterMovedAsking;
internal int _clusterMovedTryCount;
public string WriteTarget { get; internal set; }
public Guid ClientId2 { get; internal set; }
public bool _flagReadbytes;
/// <summary>
/// read byte[]
/// </summary>
/// <param name="isReadbytes"></param>
/// <returns></returns>
public CommandPacket FlagReadbytes(bool isReadbytes)
{
_flagReadbytes = isReadbytes;
return this;
}
public CommandPacket(string cmd, string subcmd = null) => this.Command(cmd, subcmd);
public CommandPacket Command(string cmd, string subcmd = null)
{
if (!string.IsNullOrWhiteSpace(_command) && _command.Equals(_input.FirstOrDefault())) _input.RemoveAt(0);
if (!string.IsNullOrWhiteSpace(_subcommand) && _subcommand.Equals(_input.FirstOrDefault())) _input.RemoveAt(0);
_command = cmd;
_subcommand = subcmd;
if (!string.IsNullOrWhiteSpace(_command))
{
if (!string.IsNullOrWhiteSpace(_subcommand)) _input.Insert(0, _subcommand);
_input.Insert(0, _command);
}
return this;
}
public CommandPacket InputKey(string key)
{
_keyIndexes.Add(_input.Count);
_input.Add(key);
return this;
}
public CommandPacket InputKey(string[] keys)
{
if (keys == null) return this;
foreach (var key in keys)
{
_keyIndexes.Add(_input.Count);
_input.Add(key);
}
return this;
}
public CommandPacket InputKeyIf(bool condition, params string[] keys)
{
if (condition == false) return this;
return InputKey(keys);
}
public CommandPacket InputRaw(object arg)
{
_input.Add(arg);
return this;
}
public CommandPacket Input(string[] args)
{
foreach (var arg in args) _input.Add(arg);
return this;
}
public CommandPacket Input(int[] args)
{
foreach (var arg in args) _input.Add(arg);
return this;
}
public CommandPacket Input(long[] args)
{
foreach (var arg in args) _input.Add(arg);
return this;
}
public CommandPacket Input(params object[] args) => this.InputIf(true, args);
public CommandPacket InputIf(bool condition, params object[] args)
{
if (condition && args != null)
{
foreach (var item in args)
{
if (item is object[] objs) _input.AddRange(objs);
else if (item is string[] strs) _input.AddRange(strs.Select(a => (object)a));
else if (item is int[] ints) _input.AddRange(ints.Select(a => (object)a));
else if (item is long[] longs) _input.AddRange(longs.Select(a => (object)a));
else if (item is KeyValuePair<string, long>[] kvps1) _input.AddRange(kvps1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is KeyValuePair<string, string>[] kvps2) _input.AddRange(kvps2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is Dictionary<string, long> dict1) _input.AddRange(dict1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else if (item is Dictionary<string, string> dict2) _input.AddRange(dict2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
else _input.Add(item);
}
}
return this;
}
public CommandPacket InputKv(object[] keyValues, bool iskey, Func<object, object> serialize)
{
if (keyValues == null || keyValues.Length == 0) return this;
if (keyValues.Length % 2 != 0) throw new ArgumentException($"Array {nameof(keyValues)} length is not even");
for (var a = 0;a < keyValues.Length; a += 2)
{
if (iskey) InputKey(keyValues[a].ToInvariantCultureToString());
else InputRaw(keyValues[a]);
InputRaw((serialize?.Invoke(keyValues[a + 1]) ?? keyValues[a + 1]));
}
return this;
}
public CommandPacket InputKv<T>(Dictionary<string, T> keyValues, bool iskey, Func<object, object> serialize)
{
foreach (var kv in keyValues)
{
if (iskey) InputKey(kv.Key);
else InputRaw(kv.Key);
InputRaw(serialize?.Invoke(kv.Value) ?? kv.Value);
}
return this;
}
internal bool IsReadOnlyCommand()
{
var cmdset = CommandSets.Get(_command);
return cmdset != null && ((cmdset.Tag & CommandSets.ServerTag.read) == CommandSets.ServerTag.read || (cmdset.Flag & CommandSets.ServerFlag.@readonly) == CommandSets.ServerFlag.@readonly);
}
internal bool IsBlockingCommand()
{
var cmdset = CommandSets.Get(_command);
return cmdset != null && ((cmdset.Tag & CommandSets.ServerTag.blocking) == CommandSets.ServerTag.blocking);
}
}
static class CommandPacketExtensions
{
public static CommandPacket SubCommand(this string cmd, string subcmd) => new CommandPacket(cmd, subcmd);
public static CommandPacket InputKey(this string cmd, string key) => new CommandPacket(cmd).InputKey(key);
public static CommandPacket Reset(this CommandPacket cmd) => new CommandPacket(cmd._command, cmd._subcommand) { _prefix = cmd._prefix, _IsIgnoreAop = cmd._IsIgnoreAop };
public static CommandPacket InputKey(this string cmd, string key, string arg1) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1);
public static CommandPacket InputKey(this string cmd, string key, string arg1, long arg2) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket InputKey(this string cmd, string key, string arg1, decimal arg2) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket InputKey(this string cmd, string key, string arg1, string arg2) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket InputKey(this string cmd, string key, decimal arg1, string arg2) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket InputKey(this string cmd, string key, string[] arg1) => new CommandPacket(cmd).InputKey(key).Input(arg1);
public static CommandPacket InputKey(this string cmd, string key, long arg1) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1);
public static CommandPacket InputKey(this string cmd, string key, long arg1, long arg2) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket InputKey(this string cmd, string key, int arg1) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1);
public static CommandPacket InputKey(this string cmd, string key, decimal arg1) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1);
public static CommandPacket InputKey(this string cmd, string key, decimal arg1, decimal arg2) => new CommandPacket(cmd).InputKey(key).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket InputKey(this string cmd, string[] keys) => new CommandPacket(cmd).InputKey(keys);
public static CommandPacket InputKey(this string cmd, string[] keys, int arg1) => new CommandPacket(cmd).InputKey(keys).InputRaw(arg1);
public static CommandPacket InputRaw(this string cmd, object arg) => new CommandPacket(cmd).InputRaw(arg);
public static CommandPacket Input(this string cmd, string arg) => new CommandPacket(cmd).InputRaw(arg);
public static CommandPacket Input(this string cmd, long arg) => new CommandPacket(cmd).InputRaw(arg);
public static CommandPacket Input(this string cmd, string arg1, string arg2) => new CommandPacket(cmd).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket Input(this string cmd, string arg1, int arg2) => new CommandPacket(cmd).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket Input(this string cmd, int arg1, int arg2) => new CommandPacket(cmd).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket Input(this string cmd, long arg1, long arg2) => new CommandPacket(cmd).InputRaw(arg1).InputRaw(arg2);
public static CommandPacket Input(this string cmd, string arg1, string arg2, string arg3) => new CommandPacket(cmd).InputRaw(arg1).InputRaw(arg2).InputRaw(arg3);
public static CommandPacket Input(this string cmd, string[] args) => new CommandPacket(cmd).Input(args);
}
}
|
2881099/FreeRedis | 2,404 | src/FreeRedis/RedisClientAsync.cs | #if isasync
using FreeRedis.Internal;
using FreeRedis.Internal.ObjectPool;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
public Task<object> CallAsync(CommandPacket cmd) => Adapter.AdapterCallAsync(cmd, rt => rt.ThrowOrValue());
public Task<TValue> CallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse) => Adapter.AdapterCallAsync(cmd, parse);
async internal Task<T> LogCallAsync<T>(CommandPacket cmd, Func<Task<T>> func)
{
cmd.Prefix(Prefix);
var isnotice = this.Notice != null;
if (isnotice == false && this.Interceptors.Any() == false) return await func();
Exception exception = null;
T ret = default(T);
var isaopval = false;
IInterceptor[] aops = new IInterceptor[this.Interceptors.Count + (isnotice ? 1 : 0)];
Stopwatch[] aopsws = new Stopwatch[aops.Length];
for (var idx = 0; idx < aops.Length; idx++)
{
aopsws[idx] = new Stopwatch();
aopsws[idx].Start();
aops[idx] = isnotice && idx == aops.Length - 1 ? new NoticeCallInterceptor(this) : this.Interceptors[idx]?.Invoke();
var args = new InterceptorBeforeEventArgs(this, cmd, typeof(T));
aops[idx].Before(args);
if (args.ValueIsChanged && args.Value is T argsValue)
{
isaopval = true;
ret = argsValue;
}
}
try
{
if (isaopval == false) ret = await func();
return ret;
}
catch (Exception ex)
{
exception = ex;
throw;
}
finally
{
for (var idx = 0; idx < aops.Length; idx++)
{
aopsws[idx].Stop();
var args = new InterceptorAfterEventArgs(this, cmd, typeof(T), ret, exception, aopsws[idx].ElapsedMilliseconds);
aops[idx].After(args);
}
}
}
}
}
#endif |
2881099/FreeRedis | 18,417 | src/FreeRedis/ClientSideCaching.cs | using FreeRedis.Internal;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace FreeRedis
{
public class ClientSideCachingOptions
{
public int Capacity { get; set; }
/// <summary>
/// true: cache
/// </summary>
public Func<string, bool> KeyFilter { get; set; }
/// <summary>
/// true: expired
/// </summary>
public Func<string, DateTime, bool> CheckExpired { get; set; }
}
public static class ClientSideCachingExtensions
{
public static void UseClientSideCaching(this RedisClient cli, ClientSideCachingOptions options)
{
new ClientSideCachingContext(cli, options)
.Start();
}
class ClientSideCachingContext
{
readonly RedisClient _cli;
readonly ClientSideCachingOptions _options;
IPubSubSubscriber _sub;
Dictionary<string, ClusterTrackingInfo> _clusterTrackings = new Dictionary<string, ClusterTrackingInfo>();
object _clusterTrackingsLock = new object();
class ClusterTrackingInfo
{
public RedisClient Client;
public IPubSubSubscriber PubSub;
}
public ClientSideCachingContext(RedisClient cli, ClientSideCachingOptions options)
{
_cli = cli;
_options = options ?? new ClientSideCachingOptions();
}
public void Start()
{
_sub = _cli.Subscribe("__redis__:invalidate", InValidate) as IPubSubSubscriber;
_cli.Interceptors.Add(() => new MemoryCacheAop(this));
_cli.Unavailable += (_, e) =>
{
lock (_dictLock) _dictSort.Clear();
_dict.Clear();
lock (_clusterTrackingsLock)
{
if (_clusterTrackings.TryGetValue(e.Pool.Key, out var localTracking))
{
_clusterTrackings.Remove(e.Pool.Key);
localTracking.Client.Dispose();
}
}
};
_cli.Connected += (_, e) =>
{
var redirectId = GetOrAddClusterTrackingRedirectId(e.Host, e.Pool);
e.Client.ClientTracking(true, redirectId, null, false, false, false, false);
};
_cli.Disconnected += (_, e) =>
{
var rds = e.Client.Adapter.GetRedisSocket(null);
var keys = _dict.Where(a => a.Value.ClientId2Falgs.ContainsKey(rds.ClientId2)).Select(a => a.Key).ToArray();
RemoveCache(keys);
//例如:释放空闲链接,会导致已经 Tracking 的 key 失效,收不到 __redis__:invalidate
//目前采用 FreeRedis 记录每个链接的 key 有关信息,链接释放的时候移除对应的 client side caching
};
//将已预热好的连接,执行 ClientTracking REDIRECT
if (_cli.Adapter is RedisClient.ClusterAdapter clusterAdapter) clusterAdapter._ib.GetAll().ForEach(pool => LocalTrackingRedirectPool(pool));
if (_cli.Adapter is RedisClient.NormanAdapter normanAdapter) normanAdapter._ib.GetAll().ForEach(pool => LocalTrackingRedirectPool(pool));
if (_cli.Adapter is RedisClient.PoolingAdapter poolingAdapter) LocalTrackingRedirectPool(poolingAdapter._ib.Get(poolingAdapter._masterHost));
if (_cli.Adapter is RedisClient.SentinelAdapter sentinelAdapter)
{
var poolkey = sentinelAdapter.GetIdleBusKey(new CommandPacket("PING"));
if (!string.IsNullOrWhiteSpace(poolkey)) LocalTrackingRedirectPool(sentinelAdapter._ib.Get(poolkey));
}
void LocalTrackingRedirectPool(RedisClientPool pool)
{
if (pool == null) return;
var redirectId = GetOrAddClusterTrackingRedirectId(pool._policy._connectionStringBuilder.Host, pool);
Enumerable.Range(0, pool._freeObjects.Count).Select(b =>
{
var conn = pool.Get();
conn.Value.ClientTracking(true, redirectId, null, false, false, false, false);
return conn;
}).ToList().ForEach(c => c.Dispose());
}
}
long GetOrAddClusterTrackingRedirectId(string host, RedisClientPool pool)
{
var poolkey = pool.Key;
//return _sub.RedisSocket.ClientId;
if (_cli.Adapter.UseType != RedisClient.UseType.Cluster && _sub.RedisSocket.Host == host) return _sub.RedisSocket.ClientId;
ClusterTrackingInfo tracking = null;
lock (_clusterTrackingsLock)
{
if (_clusterTrackings.TryGetValue(poolkey, out tracking) == false)
{
tracking = new ClusterTrackingInfo
{
Client = new RedisClient(new ConnectionStringBuilder
{
Host = host,
MaxPoolSize = 1,
Password = pool._policy._connectionStringBuilder.Password,
ClientName = "client_tracking_redirect",
ConnectTimeout = pool._policy._connectionStringBuilder.ConnectTimeout,
IdleTimeout = pool._policy._connectionStringBuilder.IdleTimeout,
ReceiveTimeout = pool._policy._connectionStringBuilder.ReceiveTimeout,
SendTimeout = pool._policy._connectionStringBuilder.SendTimeout,
Ssl = pool._policy._connectionStringBuilder.Ssl,
User = pool._policy._connectionStringBuilder.User,
})
};
tracking.Client.Unavailable += (_, e) =>
{
lock (_dictLock) _dictSort.Clear();
_dict.Clear();
lock (_clusterTrackingsLock)
{
if (_clusterTrackings.TryGetValue(e.Pool.Key, out var localTracking))
{
_clusterTrackings.Remove(e.Pool.Key);
localTracking.Client.Dispose();
}
}
};
tracking.PubSub = tracking.Client.Subscribe("__redis__:invalidate", InValidate) as IPubSubSubscriber;
_clusterTrackings.Add(poolkey, tracking);
}
}
return tracking.PubSub.RedisSocket.ClientId;
}
void InValidate(string chan, object msg)
{
if (msg == null)
{
//flushall
lock (_dictLock) _dictSort.Clear();
_dict.Clear();
return;
}
var keys = msg as object[];
if (keys != null)
{
foreach (var key in keys)
RemoveCache(string.Concat(key));
_cli.OnNotice(_cli, new NoticeEventArgs(NoticeType.Event, null, "ClientSideCaching:InValidate", keys));
}
}
static readonly DateTime _dt2020 = new DateTime(2020, 1, 1);
static long GetTime() => (long)DateTime.Now.Subtract(_dt2020).TotalSeconds;
/// <summary>
/// key -> Type(string|byte[]|class) -> value
/// </summary>
readonly ConcurrentDictionary<string, DictValue> _dict = new ConcurrentDictionary<string, DictValue>();
readonly SortedSet<string> _dictSort = new SortedSet<string>();
readonly object _dictLock = new object();
bool TryGetCacheValue(string key, Type valueType, out object value)
{
if (_dict.TryGetValue(key, out var cache) && cache.Values.TryGetValue(valueType, out var tryval)
//&& DateTime.Now.Subtract(_dt2020.AddSeconds(tryval.SetTime)) < TimeSpan.FromMinutes(5)
)
{
if (_options.CheckExpired?.Invoke(key, _dt2020.AddSeconds(tryval.SetTime)) == true)
{
RemoveCache(key);
value = null;
return false;
}
var time = GetTime();
if (_options.Capacity > 0)
{
lock (_dictLock)
{
_dictSort.Remove($"{cache.GetTime.ToString("X").PadLeft(16, '0')}{key}");
_dictSort.Add($"{time.ToString("X").PadLeft(16, '0')}{key}");
}
}
Interlocked.Exchange(ref cache.GetTime, time);
value = tryval.Value;
return true;
}
value = null;
return false;
}
void SetCacheValue(CommandPacket cmd, string command, string key, Type valueType, object value)
{
var cache = _dict.GetOrAdd(key, keyTmp =>
{
var time = GetTime();
if (_options.Capacity > 0)
{
string removeKey = null;
lock (_dictLock)
{
if (_dictSort.Count >= _options.Capacity) removeKey = _dictSort.First().Substring(16);
_dictSort.Add($"{time.ToString("X").PadLeft(16, '0')}{key}");
}
if (removeKey != null)
RemoveCache(removeKey);
}
return new DictValue(command, time);
});
cache.Values.AddOrUpdate(valueType, new DictValue.ObjectValue(value), (oldkey, oldval) => new DictValue.ObjectValue(value));
cache.ClientId2Falgs.TryAdd(cmd.ClientId2, true);
}
void RemoveCache(params string[] keys)
{
if (keys?.Any() != true) return;
foreach (var key in keys)
{
if (_dict.TryRemove(key, out var old))
{
if (_options.Capacity > 0)
{
lock (_dictLock)
{
_dictSort.Remove($"{old.GetTime.ToString("X").PadLeft(16, '0')}{key}");
}
}
}
}
}
class DictValue
{
public readonly ConcurrentDictionary<Type, ObjectValue> Values = new ConcurrentDictionary<Type, ObjectValue>();
public readonly string Command;
public long GetTime;
public readonly ConcurrentDictionary<Guid, bool> ClientId2Falgs = new ConcurrentDictionary<Guid, bool>();
public DictValue(string command, long gettime)
{
this.Command = command;
this.GetTime = gettime;
}
public class ObjectValue
{
public readonly object Value;
public readonly long SetTime = (long)DateTime.Now.Subtract(_dt2020).TotalSeconds;
public ObjectValue(object value) => this.Value = value;
}
}
class MemoryCacheAop : IInterceptor
{
ClientSideCachingContext _cscc;
public MemoryCacheAop(ClientSideCachingContext cscc)
{
_cscc = cscc;
}
bool _iscached = false;
public void Before(InterceptorBeforeEventArgs args)
{
switch (args.Command._command)
{
case "GET":
if (_cscc.TryGetCacheValue(args.Command.GetKey(0), args.ValueType, out var getval))
{
args.Value = getval;
_iscached = true;
}
break;
case "MGET":
var mgetValType = args.ValueType.GetElementType();
var mgetKeys = args.Command._keyIndexes.Select((item, index) => args.Command.GetKey(index)).ToArray();
var mgetVals = mgetKeys.Select(a => _cscc.TryGetCacheValue(a, mgetValType, out var mgetval) ?
new DictGetResult { Value = mgetval, Exists = true } : new DictGetResult { Value = null, Exists = false })
.Where(a => a.Exists).Select(a => a.Value).ToArray();
if (mgetVals.Length == mgetKeys.Length)
{
args.Value = args.ValueType.FromObject(mgetVals);
_iscached = true;
}
break;
case "HGETALL":
if (_cscc.TryGetCacheValue(args.Command.GetKey(0), args.ValueType, out var hgetallval))
{
args.Value = hgetallval;
_iscached = true;
}
break;
case "HGET":
if (_cscc.TryGetCacheValue(args.Command.GetKey(0), typeof(Dictionary<string, string>), out var hvals2))
{
var dict = hvals2 as Dictionary<string, string>;
var keyIndex = args.Command._keyIndexes.Max(a => a);
if (dict.TryGetValue(args.Command._input[keyIndex + 1]?.ToString(), out var hval))
{
args.Value = hval;
_iscached = true;
}
}
break;
case "HMGET":
if (_cscc.TryGetCacheValue(args.Command.GetKey(0), typeof(Dictionary<string, string>), out var hvals3))
{
var dict = hvals3 as Dictionary<string, string>;
var keyIndex = args.Command._keyIndexes.Max(a => a);
var vals = new string[args.Command._input.Count - keyIndex - 1];
for (var a = 0; a < vals.Length; a++)
if (dict.TryGetValue(args.Command._input[keyIndex + 1 + a]?.ToString(), out var hval))
vals[a] = hval;
args.Value = vals;
_iscached = true;
}
break;
}
}
public void After(InterceptorAfterEventArgs args)
{
switch (args.Command._command)
{
case "GET":
if (_iscached == false && args.Exception == null)
{
var getkey = args.Command.GetKey(0);
if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
_cscc.SetCacheValue(args.Command, args.Command._command, getkey, args.ValueType, args.Value);
}
break;
case "MGET":
if (_iscached == false && args.Exception == null)
{
if (args.Value is Array valueArr)
{
var valueArrElementType = args.ValueType.GetElementType();
var sourceArrLen = valueArr.Length;
for (var a = 0; a < sourceArrLen; a++)
{
var getkey = args.Command.GetKey(a);
if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
_cscc.SetCacheValue(args.Command, "GET", getkey, valueArrElementType, valueArr.GetValue(a));
}
}
}
break;
case "HGETALL":
if (_iscached == false && args.Exception == null)
{
var getkey = args.Command.GetKey(0);
if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
_cscc.SetCacheValue(args.Command, args.Command._command, getkey, args.ValueType, args.Value);
}
break;
default:
if (args.Command._keyIndexes.Any())
{
var cmdset = CommandSets.Get(args.Command._command);
if (cmdset != null &&
(cmdset.Flag & CommandSets.ServerFlag.write) == CommandSets.ServerFlag.write &&
(cmdset.Tag & CommandSets.ServerTag.write) == CommandSets.ServerTag.write &&
(cmdset.Tag & CommandSets.ServerTag.@string) == CommandSets.ServerTag.@string)
{
_cscc.RemoveCache(args.Command._keyIndexes.Select((item, index) => args.Command.GetKey(index)).ToArray());
}
}
break;
}
}
class DictGetResult
{
public object Value;
public bool Exists;
}
}
}
}
}
|
2881099/FreeRedis | 15,457 | src/FreeRedis/RedisClient.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net.Security;
using System.Text;
namespace FreeRedis
{
public partial class RedisClient : IDisposable, IRedisClient
{
internal protected BaseAdapter Adapter { get; }
internal protected string Prefix { get; }
internal protected ConnectionStringBuilder ConnectionString { get; }
public List<Func<IInterceptor>> Interceptors { get; } = new List<Func<IInterceptor>>();
public event EventHandler<NoticeEventArgs> Notice;
public event EventHandler<ConnectedEventArgs> Connected;
public event EventHandler<DisconnectedEventArgs> Disconnected;
public event EventHandler<UnavailableEventArgs> Unavailable;
protected RedisClient(BaseAdapter adapter)
{
Adapter = adapter;
}
/// <summary>
/// Pooling RedisClient
/// </summary>
public RedisClient(ConnectionStringBuilder connectionString, params ConnectionStringBuilder[] slaveConnectionStrings)
{
Adapter = new PoolingAdapter(this, connectionString, slaveConnectionStrings);
Prefix = connectionString.Prefix;
ConnectionString = connectionString;
}
/// <summary>
/// Cluster RedisClient
/// </summary>
public RedisClient(ConnectionStringBuilder[] clusterConnectionStrings, Dictionary<string, string> hostMappings = null)
{
Adapter = new ClusterAdapter(this, clusterConnectionStrings, hostMappings);
Prefix = clusterConnectionStrings[0].Prefix;
ConnectionString = clusterConnectionStrings[0];
}
/// <summary>
/// Norman RedisClient
/// </summary>
public RedisClient(ConnectionStringBuilder[] connectionStrings, Func<string, string> redirectRule)
{
Adapter = new NormanAdapter(this, connectionStrings, redirectRule);
Prefix = connectionStrings[0].Prefix;
ConnectionString = connectionStrings[0];
}
/// <summary>
/// Sentinel RedisClient
/// </summary>
public RedisClient(ConnectionStringBuilder sentinelConnectionString, string[] sentinels, bool rw_splitting)
{
Adapter = new SentinelAdapter(this, sentinelConnectionString, sentinels, rw_splitting);
Prefix = sentinelConnectionString.Prefix;
ConnectionString = sentinelConnectionString;
}
/// <summary>
/// Single inside RedisClient
/// </summary>
protected internal RedisClient(RedisClient topOwner, string host,
bool ssl, RemoteCertificateValidationCallback certificateValidation, LocalCertificateSelectionCallback certificateSelection,
TimeSpan connectTimeout, TimeSpan receiveTimeout, TimeSpan sendTimeout,
Action<RedisClient> connected, Action<RedisClient> disconnected)
{
Adapter = new SingleInsideAdapter(topOwner ?? this, this, host, ssl, certificateValidation, certificateSelection,
connectTimeout, receiveTimeout, sendTimeout, connected, disconnected);
Prefix = topOwner.Prefix;
ConnectionString = topOwner.ConnectionString;
}
public void Dispose()
{
Adapter.Dispose();
_pubsubPriv?.Dispose();
}
protected void CheckUseTypeOrThrow(params UseType[] useTypes)
{
if (useTypes?.Contains(Adapter.UseType) == true) return;
throw new RedisClientException($"Method cannot be used in {Adapter.UseType} mode.");
}
public object Call(CommandPacket cmd) => Adapter.AdapterCall(cmd, rt => rt.ThrowOrValue());
public TValue Call<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse) => Adapter.AdapterCall(cmd, parse);
internal protected virtual T LogCall<T>(CommandPacket cmd, Func<T> func) => LogCallCtrl(cmd, func, true, true);
internal protected virtual T LogCallCtrl<T>(CommandPacket cmd, Func<T> func, bool aopBefore, bool aopAfter)
{
if (aopBefore) cmd.Prefix(Prefix);
var isnotice = this.Notice != null;
if (isnotice == false && this.Interceptors.Any() == false) return func();
if (cmd.IsIgnoreAop) return func();
Exception exception = null;
T ret = default(T);
var isaopval = false;
IInterceptor[] aops = new IInterceptor[this.Interceptors.Count + (isnotice ? 1 : 0)];
Stopwatch[] aopsws = new Stopwatch[aops.Length];
for (var idx = 0; idx < aops.Length; idx++)
{
aopsws[idx] = new Stopwatch();
aopsws[idx].Start();
if (aopBefore == false && aopAfter == false) continue;
aops[idx] = isnotice && idx == aops.Length - 1 ? new NoticeCallInterceptor(this) : this.Interceptors[idx]?.Invoke();
if (aopBefore == false) continue;
var args = new InterceptorBeforeEventArgs(this, cmd, typeof(T));
aops[idx].Before(args);
if (args.ValueIsChanged && args.Value is T argsValue)
{
isaopval = true;
ret = argsValue;
}
}
try
{
if (isaopval == false) ret = func();
return ret;
}
catch (Exception ex)
{
exception = ex;
throw;
}
finally
{
if (aopAfter)
{
for (var idx = 0; idx < aops.Length; idx++)
{
aopsws[idx].Stop();
var args = new InterceptorAfterEventArgs(this, cmd, typeof(T), ret, exception, aopsws[idx].ElapsedMilliseconds);
aops[idx].After(args);
}
}
}
}
internal bool OnNotice(RedisClient cli, NoticeEventArgs e)
{
var topOwner = Adapter?.TopOwner ?? cli;
if (topOwner?.Notice == null) return false;
topOwner.Notice(topOwner, e);
return true;
}
internal bool OnConnected(RedisClient cli, ConnectedEventArgs e)
{
var topOwner = Adapter?.TopOwner ?? cli;
if (topOwner?.Connected == null) return false;
topOwner.Connected(topOwner, e);
return true;
}
internal bool OnDisconnected(RedisClient cli, DisconnectedEventArgs e)
{
var topOwner = Adapter?.TopOwner ?? cli;
if (topOwner?.Disconnected == null) return false;
topOwner.Disconnected(topOwner, e);
return true;
}
internal bool OnUnavailable(RedisClient cli, UnavailableEventArgs e)
{
var topOwner = Adapter?.TopOwner ?? cli;
if (topOwner?.Unavailable == null) return false;
topOwner.Unavailable(topOwner, e);
return true;
}
#region 序列化写入,反序列化
public Func<object, object> Serialize;
public Func<string, Type, object> Deserialize;
public Func<byte[], Type, object> DeserializeRaw;
internal object SerializeRedisValue(object value)
{
switch (value)
{
case null: return null;
case string _:
case byte[] _: return value;
case bool b: return b ? "1" : "0";
case char c: return value;
case decimal _:
case double _:
case float _:
case int _:
case long _:
case sbyte _:
case short _:
case uint _:
case ulong _:
case ushort _: return value.ToInvariantCultureToString();
case DateTime time: return time.ToString("yyyy-MM-ddTHH:mm:sszzzz", System.Globalization.DateTimeFormatInfo.InvariantInfo);
case DateTimeOffset _: return value.ToString();
case TimeSpan span: return span.Ticks;
case Guid _: return value.ToString();
default:
if (Adapter.TopOwner.Serialize != null) return Adapter.TopOwner.Serialize(value);
return value.ConvertTo<string>();
}
}
internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
{
if (valueRaw == null) return default(T);
var type = typeof(T);
var typename = type.ToString().TrimEnd(']');
if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
if (valueRaw.Length == 0) return default(T);
string valueStr = null;
if (type.IsValueType)
{
valueStr = encoding.GetString(valueRaw);
bool isNullable = typename.StartsWith("System.Nullable`1[");
var basename = isNullable ? typename.Substring(18) : typename;
bool isElse = false;
object obj = null;
switch (basename)
{
case "System.Boolean":
if (valueStr == "1") obj = true;
else if (valueStr == "0") obj = false;
break;
case "System.Byte":
if (byte.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var trybyte)) obj = trybyte;
break;
case "System.Char":
if (valueStr.Length > 0) obj = valueStr[0];
break;
case "System.Decimal":
if (Decimal.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var trydec)) obj = trydec;
break;
case "System.Double":
if (Double.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var trydb)) obj = trydb;
break;
case "System.Single":
if (Single.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var trysg)) obj = trysg;
break;
case "System.Int32":
if (Int32.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryint32)) obj = tryint32;
break;
case "System.Int64":
if (Int64.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryint64)) obj = tryint64;
break;
case "System.SByte":
if (SByte.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var trysb)) obj = trysb;
break;
case "System.Int16":
if (Int16.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryint16)) obj = tryint16;
break;
case "System.UInt32":
if (UInt32.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryuint32)) obj = tryuint32;
break;
case "System.UInt64":
if (UInt64.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryuint64)) obj = tryuint64;
break;
case "System.UInt16":
if (UInt16.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryuint16)) obj = tryuint16;
break;
case "System.DateTime":
if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
break;
case "System.DateTimeOffset":
if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
break;
case "System.TimeSpan":
if (Int64.TryParse(valueStr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out tryint64)) obj = new TimeSpan(tryint64);
break;
case "System.Guid":
if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
break;
default:
isElse = true;
break;
}
if (isElse == false)
{
if (obj == null) return default(T);
return (T)obj;
}
}
if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));
if (valueStr == null) valueStr = encoding.GetString(valueRaw);
if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
return valueStr.ConvertTo<T>();
}
#endregion
}
public class RedisClientException : Exception
{
public RedisClientException(string message) : base(message) { }
}
/// <summary>
/// redis version >=6.2: Added the GT and LT options.
/// </summary>
public enum ZAddThan { gt, lt }
public enum BitOpOperation { and, or, xor, not }
public enum BitFieldOperation { get, overflow_wrap, overflow_sat, overflow_fail, set, incrby }
public enum ClusterSetSlotType { importing, migrating, stable, node }
public enum ClusterResetType { hard, soft }
public enum ClusterFailOverType { force, takeover }
public enum ClientUnBlockType { timeout, error }
public enum ClientReplyType { on, off, skip }
public enum ClientType { normal, master, slave, pubsub }
public enum Collation { asc, desc }
public enum Confirm { yes, no }
public enum GeoUnit { m, km, mi, ft }
public enum InsertDirection { before, after }
public enum KeyType { none, @string, list, set, zset, hash, stream }
public enum RoleType { Master, Slave, Sentinel }
public class KeyValue<T>
{
public readonly string key;
public readonly T value;
public KeyValue(string key, T value) { this.key = key; this.value = value; }
}
public class ScanResult<T>
{
public readonly long cursor;
public readonly T[] items;
public readonly long length;
public ScanResult(long cursor, T[] items) { this.cursor = cursor; this.items = items; this.length = items.LongLength; }
}
public class BitFieldAction
{
public BitFieldOperation operation;
public object[] arguments;
}
}
|
2881099/FreeRedis | 10,280 | src/FreeRedis/RedisSentinelClient.cs | using FreeRedis.Internal;
using System;
using System.Linq;
namespace FreeRedis
{
public partial class RedisSentinelClient : IDisposable
{
readonly IRedisSocket _redisSocket;
public RedisSentinelClient(ConnectionStringBuilder connectionString)
{
_redisSocket = new DefaultRedisSocket(connectionString.Host, connectionString.Ssl, connectionString.CertificateValidation, connectionString.CertificateSelection);
_redisSocket.ReceiveTimeout = connectionString.ReceiveTimeout;
_redisSocket.SendTimeout = connectionString.SendTimeout;
_redisSocket.Encoding = connectionString.Encoding;
_redisSocket.Connected += (_, __) =>
{
if (!string.IsNullOrEmpty(connectionString.User) && !string.IsNullOrEmpty(connectionString.Password))
this.Auth(connectionString.User, connectionString.Password);
else if (!string.IsNullOrEmpty(connectionString.Password))
this.Auth(connectionString.Password);
};
}
public void Dispose()
{
_redisSocket.Dispose();
}
public void Auth(string password) => Call("AUTH".Input(password), rt => rt.ThrowOrValue());
public void Auth(string username, string password) => Call("AUTH".SubCommand(null)
.InputIf(!string.IsNullOrWhiteSpace(username), username)
.InputRaw(password), rt => rt.ThrowOrValue());
public object Call(CommandPacket cmd) => Call(cmd, rt => rt.ThrowOrValue());
protected TValue Call<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
_redisSocket.Write(cmd);
var rt = _redisSocket.Read(cmd);
return parse(rt);
}
public string Ping() => Call("PING", rt => rt.ThrowOrValue<string>());
public string Info() => Call("INFO", rt => rt.ThrowOrValue<string>());
public SentinelRoleResult Role() => Call("ROLE", rt => rt.ThrowOrValueToRole());
public SentinelMasterResult[] Masters() => Call("SENTINEL".SubCommand("MASTERS"), rt => rt.ThrowOrValue((a, _) =>
a.Select(x => x.ConvertTo<string[]>().MapToClass<SentinelMasterResult>(rt.Encoding)).ToArray()));
public SentinelMasterResult Master(string masterName) => Call("SENTINEL".SubCommand("MASTER").InputRaw(masterName), rt => rt.ThrowOrValue(a =>
a.ConvertTo<string[]>().MapToClass<SentinelMasterResult>(rt.Encoding)));
public SentinelSalveResult[] Salves(string masterName) => Call("SENTINEL".SubCommand("SLAVES").InputRaw(masterName), rt => rt.ThrowOrValue((a, _) =>
a.Select(x => x.ConvertTo<string[]>().MapToClass<SentinelSalveResult>(rt.Encoding)).ToArray()));
public SentinelResult[] Sentinels(string masterName) => Call("SENTINEL".SubCommand("SENTINELS").InputRaw(masterName), rt => rt.ThrowOrValue((a, _) =>
a.Select(x => x.ConvertTo<string[]>().MapToClass<SentinelResult>(rt.Encoding)).ToArray()));
public string GetMasterAddrByName(string masterName) => Call("SENTINEL".SubCommand("GET-MASTER-ADDR-BY-NAME").InputRaw(masterName), rt => rt.ThrowOrValue((a, _) =>
$"{a[0]}:{a[1]}"));
public SentinelIsMaterDownByAddrResult IsMasterDownByAddr(string ip, int port, long currentEpoch, string runid) => Call("SENTINEL".SubCommand("IS-MASTER-DOWN-BY-ADDR").Input(ip, port, currentEpoch, runid), rt => rt.ThrowOrValue((a, _) =>
new SentinelIsMaterDownByAddrResult { down_state = a[0].ConvertTo<bool>(), leader = a[1].ConvertTo<string>(), vote_epoch = a[1].ConvertTo<long>() }));
public long Reset(string pattern) => Call("SENTINEL".SubCommand("RESET").InputRaw(pattern), rt => rt.ThrowOrValue<long>());
public void Failover(string masterName) => Call("SENTINEL".SubCommand("FAILOVER").InputRaw(masterName), rt => rt.ThrowOrNothing());
public object PendingScripts() => Call("SENTINEL".SubCommand("PENDING-SCRIPTS"), rt => rt.ThrowOrValue());
public object Monitor(string name, string ip, int port, int quorum) => Call("SENTINEL".SubCommand("MONITOR").Input(name, ip, port, quorum), rt => rt.ThrowOrValue());
public void FlushConfig() => Call("SENTINEL".SubCommand("FLUSHCONFIG"), rt => rt.ThrowOrNothing());
public void Remove(string masterName) => Call("SENTINEL".SubCommand("REMOVE").InputRaw(masterName), rt => rt.ThrowOrNothing());
public string CkQuorum(string masterName) => Call("SENTINEL".SubCommand("CKQUORUM").InputRaw(masterName), rt => rt.ThrowOrValue<string>());
public void Set(string masterName, string option, string value) => Call("SENTINEL".SubCommand("SET").Input(masterName, option, value), rt => rt.ThrowOrNothing());
public object InfoCache(string masterName) => Call<object>("SENTINEL".SubCommand("INFO-CACHE").InputRaw(masterName), rt => rt.ThrowOrValue());
public void SimulateFailure(bool crashAfterElection, bool crashAfterPromotion) => Call<object>("SENTINEL"
.SubCommand("SIMULATE-FAILURE")
.InputIf(crashAfterElection, "crash-after-election")
.InputIf(crashAfterPromotion, "crash-after-promotion"), rt => rt.ThrowOrNothing());
}
#region Model
public class SentinelRoleResult
{
public static implicit operator SentinelRoleResult(RoleResult rt) => new SentinelRoleResult { role = rt.role, masters = rt.data as string[] };
public RoleType role;
public string[] masters;
}
// 1) "name"
// 2) "mymaster"
// 3) "ip"
// 4) "127.0.0.1"
// 5) "port"
// 6) "6381"
// 7) "runid"
// 8) "380dc0424db52c1ff2d1c094659284de55be10fb"
// 9) "flags"
//10) "master"
//11) "link-pending-commands"
//12) "0"
//13) "link-refcount"
//14) "1"
//15) "last-ping-sent"
//16) "0"
//17) "last-ok-ping-reply"
//18) "755"
//19) "last-ping-reply"
//20) "755"
//21) "down-after-milliseconds"
//22) "5000"
//23) "info-refresh"
//24) "5375"
//25) "role-reported"
//26) "master"
//27) "role-reported-time"
//28) "55603"
//29) "config-epoch"
//30) "304"
//31) "num-slaves"
//32) "2"
//33) "num-other-sentinels"
//34) "3"
//35) "quorum"
//36) "2"
//37) "failover-timeout"
//38) "15000"
//39) "parallel-syncs"
//40) "1"
public class SentinelMasterResult
{
public string name;
public string ip;
public int port;
public string runid;
public string flags;
public long link_pending_commands;
public long link_refcount;
public long last_ping_sent;
public long last_ok_ping_reply;
public long last_ping_reply;
public long down_after_milliseconds;
public long info_refresh;
public string role_reported;
public long role_reported_time;
public long config_epoch;
public long num_slaves;
public long num_other_sentinels;
public long quorum;
public long failover_timeout;
public long parallel_syncs;
}
// 1) "name"
// 2) "127.0.0.1:6379"
// 3) "ip"
// 4) "127.0.0.1"
// 5) "port"
// 6) "6379"
// 7) "runid"
// 8) ""
// 9) "flags"
//10) "s_down,slave"
//11) "link-pending-commands"
//12) "100"
//13) "link-refcount"
//14) "1"
//15) "last-ping-sent"
//16) "11188943"
//17) "last-ok-ping-reply"
//18) "11188943"
//19) "last-ping-reply"
//20) "11188943"
//21) "s-down-time"
//22) "11183890"
//23) "down-after-milliseconds"
//24) "5000"
//25) "info-refresh"
//26) "1603036921117"
//27) "role-reported"
//28) "slave"
//29) "role-reported-time"
//30) "11188943"
//31) "master-link-down-time"
//32) "0"
//33) "master-link-status"
//34) "err"
//35) "master-host"
//36) "?"
//37) "master-port"
//38) "0"
//39) "slave-priority"
//40) "100"
//41) "slave-repl-offset"
//42) "0"
public class SentinelSalveResult
{
public string name;
public string ip;
public int port;
public string runid;
public string flags;
public long link_pending_commands;
public long link_refcount;
public long last_ping_sent;
public long last_ok_ping_reply;
public long last_ping_reply;
public long s_down_time;
public long down_after_milliseconds;
public long info_refresh;
public string role_reported;
public long role_reported_time;
public long master_link_down_time;
public string master_link_status;
public string master_host;
public int master_port;
public long slave_priority;
public long slave_repl_offset;
}
// 1) "name"
// 2) "311f72064b0a58ee7f9d49dab078dada24a2b95c"
// 3) "ip"
// 4) "127.0.0.1"
// 5) "port"
// 6) "26479"
// 7) "runid"
// 8) "311f72064b0a58ee7f9d49dab078dada24a2b95c"
// 9) "flags"
//10) "sentinel"
//11) "link-pending-commands"
//12) "0"
//13) "link-refcount"
//14) "1"
//15) "last-ping-sent"
//16) "0"
//17) "last-ok-ping-reply"
//18) "364"
//19) "last-ping-reply"
//20) "364"
//21) "down-after-milliseconds"
//22) "5000"
//23) "last-hello-message"
//24) "325"
//25) "voted-leader"
//26) "?"
//27) "voted-leader-epoch"
//28) "0"
public class SentinelResult
{
public string name;
public string ip;
public int port;
public string runid;
public string flags;
public long pending_commands;
public long link_pending_commands;
public long link_refcount;
public long last_ping_sent;
public long last_ok_ping_reply;
public long last_ping_reply;
public long down_after_milliseconds;
public long last_hello_message;
public string voted_leader;
public long voted_leader_epoch;
}
public class SentinelIsMaterDownByAddrResult
{
public bool down_state;
public string leader;
public long vote_epoch;
}
#endregion
}
|
2881099/FreeRedis | 46,436 | src/FreeRedis/IRedisClient.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace FreeRedis
{
public interface IRedisClient
{
List<Func<IInterceptor>> Interceptors { get; }
event EventHandler<ConnectedEventArgs> Connected;
event EventHandler<NoticeEventArgs> Notice;
event EventHandler<UnavailableEventArgs> Unavailable;
RedisClient.PipelineHook StartPipe();
RedisClient.DatabaseHook GetDatabase(int? index = null);
RedisClient.TransactionHook Multi();
void Auth(string password);
void Auth(string username, string password);
void ClientCaching(Confirm confirm);
string ClientGetName();
long ClientGetRedir();
long ClientId();
void ClientKill(string ipport);
long ClientKill(string ipport, long? clientid, ClientType? type, string username, string addr, Confirm? skipme);
string ClientList(ClientType? type = null);
void ClientPause(long timeoutMilliseconds);
void ClientReply(ClientReplyType type);
void ClientSetName(string connectionName);
void ClientTracking(bool on_off, long? redirect, string[] prefix, bool bcast, bool optin, bool optout, bool noloop);
bool ClientUnBlock(long clientid, ClientUnBlockType? type = null);
string Echo(string message);
Dictionary<string, object> Hello(string protover, string username = null, string password = null, string clientname = null);
string Ping(string message = null);
void Quit();
void Select(int index);
long GeoAdd(string key, params GeoMember[] members);
decimal? GeoDist(string key, string member1, string member2, GeoUnit unit = GeoUnit.m);
string GeoHash(string key, string member);
string[] GeoHash(string key, string[] members);
GeoMember GeoPos(string key, string member);
GeoMember[] GeoPos(string key, string[] members);
GeoRadiusResult[] GeoRadius(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, bool withdoord = false, bool withdist = false, bool withhash = false, long? count = null, Collation? collation = null);
long GeoRadiusStore(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, Collation? collation = null, string storekey = null, string storedistkey = null);
GeoRadiusResult[] GeoRadiusByMember(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m, bool withdoord = false, bool withdist = false, bool withhash = false, long? count = null, Collation? collation = null);
long GeoRadiusByMemberStore(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, Collation? collation = null, string storekey = null, string storedistkey = null);
long HDel(string key, params string[] fields);
bool HExists(string key, string field);
string HGet(string key, string field);
T HGet<T>(string key, string field);
Dictionary<string, string> HGetAll(string key);
Dictionary<string, T> HGetAll<T>(string key);
long HIncrBy(string key, string field, long increment);
decimal HIncrByFloat(string key, string field, decimal increment);
string[] HKeys(string key);
long HLen(string key);
string[] HMGet(string key, params string[] fields);
T[] HMGet<T>(string key, params string[] fields);
void HMSet<T>(string key, string field, T value, params object[] fieldValues);
void HMSet<T>(string key, Dictionary<string, T> keyValues);
ScanResult<KeyValuePair<string, string>> HScan(string key, long cursor, string pattern, long count);
ScanResult<KeyValuePair<string, T>> HScan<T>(string key, long cursor, string pattern, long count);
IEnumerable<KeyValuePair<string, string>[]> HScan(string key, string pattern, long count);
IEnumerable<KeyValuePair<string, T>[]> HScan<T>(string key, string pattern, long count);
long HSet<T>(string key, string field, T value, params object[] fieldValues);
long HSet<T>(string key, Dictionary<string, T> keyValues);
bool HSetNx<T>(string key, string field, T value);
long HStrLen(string key, string field);
string[] HVals(string key);
T[] HVals<T>(string key);
bool PfAdd(string key, params object[] elements);
long PfCount(params string[] keys);
void PfMerge(string destkey, params string[] sourcekeys);
long Del(params string[] keys);
Byte[] Dump(string key);
bool Exists(string key);
long Exists(string[] keys);
bool Expire(string key, int seconds);
bool Expire(string key, TimeSpan expire);
bool ExpireAt(string key, DateTime timestamp);
string[] Keys(string pattern);
void Migrate(string host, int port, string key, int destinationDb, long timeoutMilliseconds, bool copy, bool replace, string authPassword, string auth2Username, string auth2Password, string[] keys);
bool Move(string key, int db);
long? ObjectRefCount(string key);
long ObjectIdleTime(string key);
string ObjectEncoding(string key);
long? ObjectFreq(string key);
bool Persist(string key);
bool PExpire(string key, int milliseconds);
bool PExpireAt(string key, DateTime timestamp);
long PTtl(string key);
string RandomKey();
void Rename(string key, string newkey);
bool RenameNx(string key, string newkey);
void Restore(string key, Byte[] serializedValue);
void Restore(string key, int ttl, Byte[] serializedValue, bool replace = false, bool absTtl = false, int? idleTimeSeconds = null, decimal? frequency = null);
ScanResult<string> Scan(long cursor, string pattern, long count, string type);
IEnumerable<string[]> Scan(string pattern, long count, string type);
string[] Sort(string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false);
long SortStore(string storeDestination, string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false);
long Touch(params string[] keys);
long Ttl(string key);
KeyType Type(string key);
long UnLink(params string[] keys);
long Wait(long numreplicas, long timeoutMilliseconds);
string BLPop(string key, int timeoutSeconds);
T BLPop<T>(string key, int timeoutSeconds);
KeyValue<string> BLPop(string[] keys, int timeoutSeconds);
KeyValue<T> BLPop<T>(string[] keys, int timeoutSeconds);
string BRPop(string key, int timeoutSeconds);
T BRPop<T>(string key, int timeoutSeconds);
KeyValue<string> BRPop(string[] keys, int timeoutSeconds);
KeyValue<T> BRPop<T>(string[] keys, int timeoutSeconds);
string BRPopLPush(string source, string destination, int timeoutSeconds);
T BRPopLPush<T>(string source, string destination, int timeoutSeconds);
string LIndex(string key, long index);
T LIndex<T>(string key, long index);
long LInsert(string key, InsertDirection direction, object pivot, object element);
long LLen(string key);
string LPop(string key);
T LPop<T>(string key);
long LPos<T>(string key, T element, int rank = 0);
long[] LPos<T>(string key, T element, int rank, int count, int maxLen);
long LPush(string key, params object[] elements);
long LPushX(string key, params object[] elements);
string[] LRange(string key, long start, long stop);
T[] LRange<T>(string key, long start, long stop);
long LRem<T>(string key, long count, T element);
void LSet<T>(string key, long index, T element);
void LTrim(string key, long start, long stop);
string RPop(string key);
T RPop<T>(string key);
string RPopLPush(string source, string destination);
T RPopLPush<T>(string source, string destination);
long RPush(string key, params object[] elements);
long RPushX(string key, params object[] elements);
string BfReserve(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false);
bool BfAdd(string key, string item);
bool[] BfMAdd(string key, string[] items);
string BfInsert(string key, string[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false);
bool BfExists(string key, string item);
bool[] BfMExists(string key, string[] items);
ScanResult<Byte[]> BfScanDump(string key, long iter);
string BfLoadChunk(string key, long iter, Byte[] data);
Dictionary<string, string> BfInfo(string key);
RedisClient.LockController Lock(string name, int timeoutSeconds, bool autoDelay = true);
string CmsInitByDim(string key, long width, long depth);
string CmsInitByProb(string key, decimal error, decimal probability);
long CmsIncrBy(string key, string item, long increment);
long[] CmsIncrBy(string key, Dictionary<string, long> itemIncrements);
long[] CmsQuery(string key, string[] items);
string CmsMerge(string dest, long numKeys, string[] src, long[] weights);
Dictionary<string, string> CmsInfo(string key);
string CfReserve(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null);
bool CfAdd(string key, string item);
bool CfAddNx(string key, string item);
string CfInsert(string key, string[] items, long? capacity = null, bool noCreate = false);
string CfInsertNx(string key, string[] items, long? capacity = null, bool noCreate = false);
bool CfExists(string key, string item);
bool CfDel(string key, string item);
long CfCount(string key, string item);
ScanResult<Byte[]> CfScanDump(string key, long iter);
string CfLoadChunk(string key, long iter, Byte[] data);
Dictionary<string, string> CfInfo(string key);
string TopkReserve(string key, long topk, long width, long depth, decimal decay);
string[] TopkAdd(string key, string[] items);
string TopkIncrBy(string key, string item, long increment);
string[] TopkIncrBy(string key, Dictionary<string, long> itemIncrements);
bool[] TopkQuery(string key, string[] items);
long[] TopkCount(string key, string[] items);
string[] TopkList(string key);
Dictionary<string, string> TopkInfo(string key);
string JsonGet(string key, string indent = null, string newline = null, string space = null, params string[] paths);
string[] JsonMGet(string[] keys, string path = "$");
void JsonSet(string key, string value, string path = "$", bool nx = false, bool xx = false);
void JsonMSet(string[] keys, string[] values, string[] paths);
void JsonMerge(string key, string path, string value);
long JsonDel(string key, string path = "$");
long[] JsonArrInsert(string key, string path, long index = 0, params object[] values);
long[] JsonArrAppend(string key, string path, params object[] values);
long[] JsonArrIndex<T>(string key, string path, T value) where T : struct;
long[] JsonArrLen(string key, string path);
object[] JsonArrPop(string key, string path, int index = -1);
long[] JsonArrTrim(string key, string path, int start, int stop);
long JsonClear(string key, string path = "$");
long[] JsonDebugMemory(string key, string path = "$");
long JsonForget(string key, string path = "$");
string JsonNumIncrBy(string key, string path, double value);
string JsonNumMultBy(string key, string path, double value);
string[][] JsonObjKeys(string key, string path = "$");
long[] JsonObjLen(string key, string path = "$");
object[][] JsonResp(string key, string path = "$");
long[] JsonStrAppend(string key, string value, string path = "$");
long[] JsonStrLen(string key, string path = "$");
bool[] JsonToggle(string key, string path = "$");
string[] JsonType(string key, string path = "$");
SubscribeListObject SubscribeList(string listKey, Action<string> onMessage);
SubscribeListObject SubscribeList(string[] listKeys, Action<string, string> onMessage);
SubscribeListBroadcastObject SubscribeListBroadcast(string listKey, string clientId, Action<string> onMessage);
SubscribeStreamObject SubscribeStream(string streamKey, Action<Dictionary<string, string>> onMessage);
long Publish(string channel, string message);
long Publish(string channel, Byte[] message);
string[] PubSubChannels(string pattern = "*");
long PubSubNumSub(string channel);
long[] PubSubNumSub(string[] channels);
long PubSubNumPat();
void PUnSubscribe(params string[] pattern);
void UnSubscribe(params string[] channels);
bool ScriptExists(string sha1);
bool[] ScriptExists(string[] sha1);
void ScriptFlush();
void ScriptKill();
string ScriptLoad(string script);
string[] AclCat(string categoryname = null);
long AclDelUser(params string[] username);
string AclGenPass(int bits = 0);
AclGetUserResult AclGetUser(string username = "default");
string[] AclList();
void AclLoad();
LogResult[] AclLog(long count = 0);
void AclSave();
void AclSetUser(string username, params string[] rule);
string[] AclUsers();
string AclWhoami();
string BgRewriteAof();
string BgSave(string schedule = null);
object[] Command();
long CommandCount();
string[] CommandGetKeys(params string[] command);
object[] CommandInfo(params string[] command);
Dictionary<string, string> ConfigGet(string parameter);
void ConfigResetStat();
void ConfigRewrite();
void ConfigSet<T>(string parameter, T value);
long DbSize();
string DebugObject(string key);
void FlushAll(bool isasync = false);
void FlushDb(bool isasync = false);
string Info(string section = null);
DateTime LastSave();
string LatencyDoctor();
string MemoryDoctor();
string MemoryMallocStats();
void MemoryPurge();
Dictionary<string, object> MemoryStats();
long MemoryUsage(string key, long count = 0);
void ReplicaOf(string host, int port);
RoleResult Role();
void Save();
void SlaveOf(string host, int port);
void SwapDb(int index1, int index2);
DateTime Time();
long SAdd(string key, params object[] members);
long SCard(string key);
string[] SDiff(params string[] keys);
T[] SDiff<T>(params string[] keys);
long SDiffStore(string destination, params string[] keys);
string[] SInter(params string[] keys);
T[] SInter<T>(params string[] keys);
long SInterStore(string destination, params string[] keys);
bool SIsMember<T>(string key, T member);
string[] SMembers(string key);
T[] SMembers<T>(string key);
bool[] SMIsMember(string key, params object[] members);
bool SMove<T>(string source, string destination, T member);
string SPop(string key);
T SPop<T>(string key);
string[] SPop(string key, int count);
T[] SPop<T>(string key, int count);
string SRandMember(string key);
T SRandMember<T>(string key);
string[] SRandMember(string key, int count);
T[] SRandMember<T>(string key, int count);
long SRem(string key, params object[] members);
ScanResult<string> SScan(string key, long cursor, string pattern, long count);
ScanResult<T> SScan<T>(string key, long cursor, string pattern, long count);
IEnumerable<string[]> SScan(string key, string pattern, long count);
IEnumerable<T[]> SScan<T>(string key, string pattern, long count);
string[] SUnion(params string[] keys);
T[] SUnion<T>(params string[] keys);
long SUnionStore(string destination, params string[] keys);
ZMember BZPopMin(string key, int timeoutSeconds);
KeyValue<ZMember> BZPopMin(string[] keys, int timeoutSeconds);
ZMember BZPopMax(string key, int timeoutSeconds);
KeyValue<ZMember> BZPopMax(string[] keys, int timeoutSeconds);
long ZAdd(string key, decimal score, string member, params object[] scoreMembers);
long ZAdd(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false);
long ZAddNx(string key, decimal score, string member, params object[] scoreMembers);
long ZAddNx(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false);
long ZAddXx(string key, decimal score, string member, params object[] scoreMembers);
long ZAddXx(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false);
long ZCard(string key);
long ZCount(string key, decimal min, decimal max);
long ZCount(string key, string min, string max);
decimal ZIncrBy(string key, decimal increment, string member);
long ZInterStore(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null);
long ZLexCount(string key, string min, string max);
ZMember ZPopMin(string key);
ZMember[] ZPopMin(string key, int count);
ZMember ZPopMax(string key);
ZMember[] ZPopMax(string key, int count);
string[] ZRange(string key, decimal start, decimal stop);
ZMember[] ZRangeWithScores(string key, decimal start, decimal stop);
string[] ZRangeByLex(string key, string min, string max, int offset = 0, int count = 0);
string[] ZRangeByScore(string key, decimal min, decimal max, int offset = 0, int count = 0);
string[] ZRangeByScore(string key, string min, string max, int offset = 0, int count = 0);
ZMember[] ZRangeByScoreWithScores(string key, decimal min, decimal max, int offset = 0, int count = 0);
ZMember[] ZRangeByScoreWithScores(string key, string min, string max, int offset = 0, int count = 0);
long? ZRank(string key, string member);
long ZRem(string key, params string[] members);
long ZRemRangeByLex(string key, string min, string max);
long ZRemRangeByRank(string key, long start, long stop);
long ZRemRangeByScore(string key, decimal min, decimal max);
long ZRemRangeByScore(string key, string min, string max);
string[] ZRevRange(string key, decimal start, decimal stop);
ZMember[] ZRevRangeWithScores(string key, decimal start, decimal stop);
string[] ZRevRangeByLex(string key, decimal max, decimal min, int offset = 0, int count = 0);
string[] ZRevRangeByLex(string key, string max, string min, int offset = 0, int count = 0);
string[] ZRevRangeByScore(string key, decimal max, decimal min, int offset = 0, int count = 0);
string[] ZRevRangeByScore(string key, string max, string min, int offset = 0, int count = 0);
ZMember[] ZRevRangeByScoreWithScores(string key, decimal max, decimal min, int offset = 0, int count = 0);
ZMember[] ZRevRangeByScoreWithScores(string key, string max, string min, int offset = 0, int count = 0);
long ZRevRank(string key, string member);
decimal? ZScore(string key, string member);
long ZUnionStore(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null);
string[] ZRandMember(string key, int count, bool repetition);
ZMember[] ZRandMemberWithScores(string key, int count, bool repetition);
ScanResult<ZMember> ZScan(string key, long cursor, string pattern, long count = 0);
IEnumerable<ZMember[]> ZScan(string key, string pattern, long count);
long XAck(string key, string group, params string[] id);
string XAdd<T>(string key, string field, T value, params object[] fieldValues);
string XAdd<T>(string key, long maxlen, string id, string field, T value, params object[] fieldValues);
string XAdd<T>(string key, Dictionary<string, T> fieldValues);
string XAdd<T>(string key, long maxlen, string id, Dictionary<string, T> fieldValues);
StreamsXAutoClaimResult XAutoClaim(string key, string group, string consumer, long minIdleTime, string start, long count = 0);
StreamsEntry[] XClaim(string key, string group, string consumer, long minIdleTime, params string[] id);
StreamsEntry[] XClaim(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force);
string[] XClaimJustId(string key, string group, string consumer, long minIdleTime, params string[] id);
string[] XClaimJustId(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force);
long XDel(string key, params string[] id);
void XGroupCreate(string key, string group, string id = "$", bool MkStream = false);
void XGroupSetId(string key, string group, string id = "$");
bool XGroupDestroy(string key, string group);
void XGroupCreateConsumer(string key, string group, string consumer);
long XGroupDelConsumer(string key, string group, string consumer);
StreamsXInfoStreamResult XInfoStream(string key);
StreamsXInfoStreamFullResult XInfoStreamFull(string key, long count = 10);
StreamsXInfoGroupsResult[] XInfoGroups(string key);
StreamsXInfoConsumersResult[] XInfoConsumers(string key, string group);
long XLen(string key);
StreamsXPendingResult XPending(string key, string group);
StreamsXPendingConsumerResult[] XPending(string key, string group, string start, string end, long count, string consumer = null);
StreamsEntry[] XRange(string key, string start, string end, long count = -1);
StreamsEntry[] XRevRange(string key, string end, string start, long count = -1);
StreamsEntry XRead(long block, string key, string id);
StreamsEntryResult[] XRead(long count, long block, string key, string id, params string[] keyIds);
StreamsEntryResult[] XRead(long count, long block, Dictionary<string, string> keyIds);
StreamsEntry XReadGroup(string group, string consumer, long block, string key, string id);
StreamsEntryResult[] XReadGroup(string group, string consumer, long count, long block, bool noack, string key, string id, params string[] keyIds);
StreamsEntryResult[] XReadGroup(string group, string consumer, long count, long block, bool noack, Dictionary<string, string> keyIds);
long XTrim(string key, long count);
long Append<T>(string key, T value);
long BitCount(string key, long start, long end);
long[] BitField(string key, params BitFieldAction[] actions);
long BitOp(BitOpOperation operation, string destkey, params string[] keys);
long BitPos(string key, bool bit, long? start = null, long? end = null);
long Decr(string key);
long DecrBy(string key, long decrement);
string Get(string key);
string GetDel(string key);
T Get<T>(string key);
T GetDel<T>(string key);
void Get(string key, Stream destination, int bufferSize = 1024);
void GetDel(string key, Stream destination, int bufferSize = 1024);
bool GetBit(string key, long offset);
string GetRange(string key, long start, long end);
T GetRange<T>(string key, long start, long end);
string GetSet<T>(string key, T value);
long Incr(string key);
long IncrBy(string key, long increment);
decimal IncrByFloat(string key, decimal increment);
string[] MGet(params string[] keys);
T[] MGet<T>(params string[] keys);
void MSet(string key, object value, params object[] keyValues);
void MSet<T>(Dictionary<string, T> keyValues);
bool MSetNx(string key, object value, params object[] keyValues);
bool MSetNx<T>(Dictionary<string, T> keyValues);
void PSetEx<T>(string key, long milliseconds, T value);
void Set<T>(string key, T value, int timeoutSeconds = 0);
void Set<T>(string key, T value, TimeSpan timeout);
void Set<T>(string key, T value, bool keepTtl);
bool SetNx<T>(string key, T value, int timeoutSeconds);
bool SetNx<T>(string key, T value, TimeSpan timeout);
bool SetXx<T>(string key, T value, int timeoutSeconds = 0);
bool SetXx<T>(string key, T value, TimeSpan timeout);
bool SetXx<T>(string key, T value, bool keepTtl);
string Set<T>(string key, T value, TimeSpan timeout, bool keepTtl, bool nx, bool xx, bool get);
long SetBit(string key, long offset, bool value);
void SetEx<T>(string key, int seconds, T value);
bool SetNx<T>(string key, T value);
long SetRange<T>(string key, long offset, T value);
long StrLen(string key);
object Call(CommandPacket cmd);
#if isasync
Task<object> CallAsync(CommandPacket cmd);
Task<long> GeoAddAsync(string key, params GeoMember[] members);
Task<decimal?> GeoDistAsync(string key, string member1, string member2, GeoUnit unit = GeoUnit.m);
Task<string> GeoHashAsync(string key, string member);
Task<string[]> GeoHashAsync(string key, string[] members);
Task<GeoMember> GeoPosAsync(string key, string member);
Task<GeoMember[]> GeoPosAsync(string key, string[] members);
Task<GeoRadiusResult[]> GeoRadiusAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, bool withdoord = false, bool withdist = false, bool withhash = false, long? count = null, Collation? collation = null);
Task<long> GeoRadiusStoreAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, Collation? collation = null, string storekey = null, string storedistkey = null);
Task<GeoRadiusResult[]> GeoRadiusByMemberAsync(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m, bool withdoord = false, bool withdist = false, bool withhash = false, long? count = null, Collation? collation = null);
Task<long> GeoRadiusByMemberStoreAsync(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m, long? count = null, Collation? collation = null, string storekey = null, string storedistkey = null);
Task<long> HDelAsync(string key, params string[] fields);
Task<bool> HExistsAsync(string key, string field);
Task<string> HGetAsync(string key, string field);
Task<T> HGetAsync<T>(string key, string field);
Task<Dictionary<string, string>> HGetAllAsync(string key);
Task<Dictionary<string, T>> HGetAllAsync<T>(string key);
Task<long> HIncrByAsync(string key, string field, long increment);
Task<decimal> HIncrByFloatAsync(string key, string field, decimal increment);
Task<string[]> HKeysAsync(string key);
Task<long> HLenAsync(string key);
Task<string[]> HMGetAsync(string key, params string[] fields);
Task<T[]> HMGetAsync<T>(string key, params string[] fields);
Task HMSetAsync<T>(string key, string field, T value, params object[] fieldValues);
Task HMSetAsync<T>(string key, Dictionary<string, T> keyValues);
Task<ScanResult<KeyValuePair<string, string>>> HScanAsync(string key, long cursor, string pattern, long count);
Task<ScanResult<KeyValuePair<string, T>>> HScanAsync<T>(string key, long cursor, string pattern, long count);
Task<long> HSetAsync<T>(string key, string field, T value, params object[] fieldValues);
Task<long> HSetAsync<T>(string key, Dictionary<string, T> keyValues);
Task<bool> HSetNxAsync<T>(string key, string field, T value);
Task<long> HStrLenAsync(string key, string field);
Task<string[]> HValsAsync(string key);
Task<T[]> HValsAsync<T>(string key);
Task<bool> PfAddAsync(string key, params object[] elements);
Task<long> PfCountAsync(params string[] keys);
Task PfMergeAsync(string destkey, params string[] sourcekeys);
Task<long> DelAsync(params string[] keys);
Task<Byte[]> DumpAsync(string key);
Task<bool> ExistsAsync(string key);
Task<long> ExistsAsync(string[] keys);
Task<bool> ExpireAsync(string key, int seconds);
Task<bool> ExpireAsync(string key, TimeSpan expire);
Task<bool> ExpireAtAsync(string key, DateTime timestamp);
Task<string[]> KeysAsync(string pattern);
Task MigrateAsync(string host, int port, string key, int destinationDb, long timeoutMilliseconds, bool copy, bool replace, string authPassword, string auth2Username, string auth2Password, string[] keys);
Task<bool> MoveAsync(string key, int db);
Task<long?> ObjectRefCountAsync(string key);
Task<long> ObjectIdleTimeAsync(string key);
Task<string> ObjectEncodingAsync(string key);
Task<long?> ObjectFreqAsync(string key);
Task<bool> PersistAsync(string key);
Task<bool> PExpireAsync(string key, int milliseconds);
Task<bool> PExpireAtAsync(string key, DateTime timestamp);
Task<long> PTtlAsync(string key);
Task<string> RandomKeyAsync();
Task RenameAsync(string key, string newkey);
Task<bool> RenameNxAsync(string key, string newkey);
Task RestoreAsync(string key, Byte[] serializedValue);
Task RestoreAsync(string key, int ttl, Byte[] serializedValue, bool replace = false, bool absTtl = false, int? idleTimeSeconds = null, decimal? frequency = null);
Task<ScanResult<string>> ScanAsync(long cursor, string pattern, long count, string type);
Task<string[]> SortAsync(string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false);
Task<long> SortStoreAsync(string storeDestination, string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false);
Task<long> TouchAsync(params string[] keys);
Task<long> TtlAsync(string key);
Task<KeyType> TypeAsync(string key);
Task<long> UnLinkAsync(params string[] keys);
Task<long> WaitAsync(long numreplicas, long timeoutMilliseconds);
Task<string> BLPopAsync(string key, int timeoutSeconds);
Task<T> BLPopAsync<T>(string key, int timeoutSeconds);
Task<KeyValue<string>> BLPopAsync(string[] keys, int timeoutSeconds);
Task<KeyValue<T>> BLPopAsync<T>(string[] keys, int timeoutSeconds);
Task<string> BRPopAsync(string key, int timeoutSeconds);
Task<T> BRPopAsync<T>(string key, int timeoutSeconds);
Task<KeyValue<string>> BRPopAsync(string[] keys, int timeoutSeconds);
Task<KeyValue<T>> BRPopAsync<T>(string[] keys, int timeoutSeconds);
Task<string> BRPopLPushAsync(string source, string destination, int timeoutSeconds);
Task<T> BRPopLPushAsync<T>(string source, string destination, int timeoutSeconds);
Task<string> LIndexAsync(string key, long index);
Task<T> LIndexAsync<T>(string key, long index);
Task<long> LInsertAsync(string key, InsertDirection direction, object pivot, object element);
Task<long> LLenAsync(string key);
Task<string> LPopAsync(string key);
Task<T> LPopAsync<T>(string key);
Task<long> LPosAsync<T>(string key, T element, int rank = 0);
Task<long[]> LPosAsync<T>(string key, T element, int rank, int count, int maxLen);
Task<long> LPushAsync(string key, params object[] elements);
Task<long> LPushXAsync(string key, params object[] elements);
Task<string[]> LRangeAsync(string key, long start, long stop);
Task<T[]> LRangeAsync<T>(string key, long start, long stop);
Task<long> LRemAsync<T>(string key, long count, T element);
Task LSetAsync<T>(string key, long index, T element);
Task LTrimAsync(string key, long start, long stop);
Task<string> RPopAsync(string key);
Task<T> RPopAsync<T>(string key);
Task<string> RPopLPushAsync(string source, string destination);
Task<T> RPopLPushAsync<T>(string source, string destination);
Task<long> RPushAsync(string key, params object[] elements);
Task<long> RPushXAsync(string key, params object[] elements);
Task<string> BfReserveAsync(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false);
Task<bool> BfAddAsync(string key, string item);
Task<bool[]> BfMAddAsync(string key, string[] items);
Task<string> BfInsertAsync(string key, string[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false);
Task<bool> BfExistsAsync(string key, string item);
Task<bool[]> BfMExistsAsync(string key, string[] items);
Task<ScanResult<Byte[]>> BfScanDumpAsync(string key, long iter);
Task<string> BfLoadChunkAsync(string key, long iter, Byte[] data);
Task<Dictionary<string, string>> BfInfoAsync(string key);
Task<string> CmsInitByDimAsync(string key, long width, long depth);
Task<string> CmsInitByProbAsync(string key, decimal error, decimal probability);
Task<long> CmsIncrByAsync(string key, string item, long increment);
Task<long[]> CmsIncrByAsync(string key, Dictionary<string, long> itemIncrements);
Task<long[]> CmsQueryAsync(string key, string[] items);
Task<string> CmsMergeAsync(string dest, long numKeys, string[] src, long[] weights);
Task<Dictionary<string, string>> CmsInfoAsync(string key);
Task<string> CfReserveAsync(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null);
Task<bool> CfAddAsync(string key, string item);
Task<bool> CfAddNxAsync(string key, string item);
Task<string> CfInsertAsync(string key, string[] items, long? capacity = null, bool noCreate = false);
Task<string> CfInsertNxAsync(string key, string[] items, long? capacity = null, bool noCreate = false);
Task<bool> CfExistsAsync(string key, string item);
Task<bool> CfDelAsync(string key, string item);
Task<long> CfCountAsync(string key, string item);
Task<ScanResult<Byte[]>> CfScanDumpAsync(string key, long iter);
Task<string> CfLoadChunkAsync(string key, long iter, Byte[] data);
Task<Dictionary<string, string>> CfInfoAsync(string key);
Task<string> TopkReserveAsync(string key, long topk, long width, long depth, decimal decay);
Task<string[]> TopkAddAsync(string key, string[] items);
Task<string> TopkIncrByAsync(string key, string item, long increment);
Task<string[]> TopkIncrByAsync(string key, Dictionary<string, long> itemIncrements);
Task<bool[]> TopkQueryAsync(string key, string[] items);
Task<long[]> TopkCountAsync(string key, string[] items);
Task<string[]> TopkListAsync(string key);
Task<Dictionary<string, string>> TopkInfoAsync(string key);
Task<string> JsonGetAsync(string key, string indent = null, string newline = null, string space = null, params string[] paths);
Task<string[]> JsonMGetAsync(string[] keys, string path = "$");
Task JsonSetAsync(string key, string value, string path = "$", bool nx = false, bool xx = false);
Task JsonMSetAsync(string[] keys, string[] values, string[] paths);
Task JsonMergeAsync(string key, string path, string value);
Task<long> JsonDelAsync(string key, string path = "$");
Task<long[]> JsonArrInsertAsync(string key, string path, long index = 0, params object[] values);
Task<long[]> JsonArrAppendAsync(string key, string path, params object[] values);
Task<long[]> JsonArrIndexAsync<T>(string key, string path, T value) where T : struct;
Task<long[]> JsonArrLenAsync(string key, string path);
Task<object[]> JsonArrPopAsync(string key, string path, int index = -1);
Task<long[]> JsonArrTrimAsync(string key, string path, int start, int stop);
Task<long> JsonClearAsync(string key, string path = "$");
Task<long[]> JsonDebugMemoryAsync(string key, string path = "$");
Task<long> JsonForgetAsync(string key, string path = "$");
Task<string> JsonNumIncrByAsync(string key, string path, double value);
Task<string> JsonNumMultByAsync(string key, string path, double value);
Task<string[][]> JsonObjKeysAsync(string key, string path = "$");
Task<long[]> JsonObjLenAsync(string key, string path = "$");
Task<object[][]> JsonRespAsync(string key, string path = "$");
Task<long[]> JsonStrAppendAsync(string key, string value, string path = "$");
Task<long[]> JsonStrLenAsync(string key, string path = "$");
Task<bool[]> JsonToggleAsync(string key, string path = "$");
Task<string[]> JsonTypeAsync(string key, string path = "$");
Task<long> PublishAsync(string channel, string message);
Task<long> PublishAsync(string channel, Byte[] message);
Task<string[]> PubSubChannelsAsync(string pattern = "*");
Task<long> PubSubNumSubAsync(string channel);
Task<long[]> PubSubNumSubAsync(string[] channels);
Task<long> PubSubNumPatAsync();
IDisposable PSubscribe(string pattern, Action<string, object> handler);
IDisposable PSubscribe(string[] pattern, Action<string, object> handler);
IDisposable Subscribe(string[] channels, Action<string, object> handler);
IDisposable Subscribe(string channel, Action<string, object> handler);
Task<object> EvalAsync(string script, string[] keys = null, params object[] arguments);
Task<object> EvalShaAsync(string sha1, string[] keys = null, params object[] arguments);
Task<bool> ScriptExistsAsync(string sha1);
Task<bool[]> ScriptExistsAsync(string[] sha1);
Task ScriptFlushAsync();
Task ScriptKillAsync();
Task<string> ScriptLoadAsync(string script);
object Eval(string script, string[] keys = null, params object[] arguments);
object EvalSha(string sha1, string[] keys = null, params object[] arguments);
object SlowLog(string subcommand, params string[] argument);
Task<long> SAddAsync(string key, params object[] members);
Task<long> SCardAsync(string key);
Task<string[]> SDiffAsync(params string[] keys);
Task<T[]> SDiffAsync<T>(params string[] keys);
Task<long> SDiffStoreAsync(string destination, params string[] keys);
Task<string[]> SInterAsync(params string[] keys);
Task<T[]> SInterAsync<T>(params string[] keys);
Task<long> SInterStoreAsync(string destination, params string[] keys);
Task<bool> SIsMemberAsync<T>(string key, T member);
Task<string[]> SMembersAsync(string key);
Task<T[]> SMembersAsync<T>(string key);
Task<bool[]> SMIsMemberAsync(string key, params object[] members);
Task<bool> SMoveAsync<T>(string source, string destination, T member);
Task<string> SPopAsync(string key);
Task<T> SPopAsync<T>(string key);
Task<string[]> SPopAsync(string key, int count);
Task<T[]> SPopAsync<T>(string key, int count);
Task<string> SRandMemberAsync(string key);
Task<T> SRandMemberAsync<T>(string key);
Task<string[]> SRandMemberAsync(string key, int count);
Task<T[]> SRandMemberAsync<T>(string key, int count);
Task<long> SRemAsync(string key, params object[] members);
Task<ScanResult<string>> SScanAsync(string key, long cursor, string pattern, long count);
Task<ScanResult<T>> SScanAsync<T>(string key, long cursor, string pattern, long count);
Task<string[]> SUnionAsync(params string[] keys);
Task<T[]> SUnionAsync<T>(params string[] keys);
Task<long> SUnionStoreAsync(string destination, params string[] keys);
Task<ZMember> BZPopMinAsync(string key, int timeoutSeconds);
Task<KeyValue<ZMember>> BZPopMinAsync(string[] keys, int timeoutSeconds);
Task<ZMember> BZPopMaxAsync(string key, int timeoutSeconds);
Task<KeyValue<ZMember>> BZPopMaxAsync(string[] keys, int timeoutSeconds);
Task<long> ZAddAsync(string key, decimal score, string member, params object[] scoreMembers);
Task<long> ZAddAsync(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false);
Task<long> ZAddNxAsync(string key, decimal score, string member, params object[] scoreMembers);
Task<long> ZAddNxAsync(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false);
Task<long> ZAddXxAsync(string key, decimal score, string member, params object[] scoreMembers);
Task<long> ZAddXxAsync(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false);
Task<long> ZCardAsync(string key);
Task<long> ZCountAsync(string key, decimal min, decimal max);
Task<long> ZCountAsync(string key, string min, string max);
Task<decimal> ZIncrByAsync(string key, decimal increment, string member);
Task<long> ZInterStoreAsync(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null);
Task<long> ZLexCountAsync(string key, string min, string max);
Task<ZMember> ZPopMinAsync(string key);
Task<ZMember[]> ZPopMinAsync(string key, int count);
Task<ZMember> ZPopMaxAsync(string key);
Task<ZMember[]> ZPopMaxAsync(string key, int count);
Task<string[]> ZRangeAsync(string key, decimal start, decimal stop);
Task<ZMember[]> ZRangeWithScoresAsync(string key, decimal start, decimal stop);
Task<string[]> ZRangeByLexAsync(string key, string min, string max, int offset = 0, int count = 0);
Task<string[]> ZRangeByScoreAsync(string key, decimal min, decimal max, int offset = 0, int count = 0);
Task<string[]> ZRangeByScoreAsync(string key, string min, string max, int offset = 0, int count = 0);
Task<ZMember[]> ZRangeByScoreWithScoresAsync(string key, decimal min, decimal max, int offset = 0, int count = 0);
Task<ZMember[]> ZRangeByScoreWithScoresAsync(string key, string min, string max, int offset = 0, int count = 0);
Task<long?> ZRankAsync(string key, string member);
Task<long> ZRemAsync(string key, params string[] members);
Task<long> ZRemRangeByLexAsync(string key, string min, string max);
Task<long> ZRemRangeByRankAsync(string key, long start, long stop);
Task<long> ZRemRangeByScoreAsync(string key, decimal min, decimal max);
Task<long> ZRemRangeByScoreAsync(string key, string min, string max);
Task<string[]> ZRevRangeAsync(string key, decimal start, decimal stop);
Task<ZMember[]> ZRevRangeWithScoresAsync(string key, decimal start, decimal stop);
Task<string[]> ZRevRangeByLexAsync(string key, decimal max, decimal min, int offset = 0, int count = 0);
Task<string[]> ZRevRangeByLexAsync(string key, string max, string min, int offset = 0, int count = 0);
Task<string[]> ZRevRangeByScoreAsync(string key, decimal max, decimal min, int offset = 0, int count = 0);
Task<string[]> ZRevRangeByScoreAsync(string key, string max, string min, int offset = 0, int count = 0);
Task<ZMember[]> ZRevRangeByScoreWithScoresAsync(string key, decimal max, decimal min, int offset = 0, int count = 0);
Task<ZMember[]> ZRevRangeByScoreWithScoresAsync(string key, string max, string min, int offset = 0, int count = 0);
Task<long> ZRevRankAsync(string key, string member);
Task<decimal?> ZScoreAsync(string key, string member);
Task<long> ZUnionStoreAsync(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null);
Task<long> XAckAsync(string key, string group, params string[] id);
Task<string> XAddAsync<T>(string key, string field, T value, params object[] fieldValues);
Task<string> XAddAsync<T>(string key, long maxlen, string id, string field, T value, params object[] fieldValues);
Task<string> XAddAsync<T>(string key, Dictionary<string, T> fieldValues);
Task<string> XAddAsync<T>(string key, long maxlen, string id, Dictionary<string, T> fieldValues);
Task<StreamsXAutoClaimResult> XAutoClaimAsync(string key, string group, string consumer, long minIdleTime, string start, long count = 0);
Task<StreamsEntry[]> XClaimAsync(string key, string group, string consumer, long minIdleTime, params string[] id);
Task<StreamsEntry[]> XClaimAsync(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force);
Task<string[]> XClaimJustIdAsync(string key, string group, string consumer, long minIdleTime, params string[] id);
Task<string[]> XClaimJustIdAsync(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force);
Task<long> XDelAsync(string key, params string[] id);
Task XGroupCreateAsync(string key, string group, string id = "$", bool MkStream = false);
Task XGroupSetIdAsync(string key, string group, string id = "$");
Task<bool> XGroupDestroyAsync(string key, string group);
Task XGroupCreateConsumerAsync(string key, string group, string consumer);
Task<long> XGroupDelConsumerAsync(string key, string group, string consumer);
Task<StreamsXInfoStreamResult> XInfoStreamAsync(string key);
Task<StreamsXInfoStreamFullResult> XInfoStreamFullAsync(string key, long count = 10);
Task<StreamsXInfoGroupsResult[]> XInfoGroupsAsync(string key);
Task<StreamsXInfoConsumersResult[]> XInfoConsumersAsync(string key, string group);
Task<long> XLenAsync(string key);
Task<StreamsXPendingResult> XPendingAsync(string key, string group);
Task<StreamsXPendingConsumerResult[]> XPendingAsync(string key, string group, string start, string end, long count, string consumer = null);
Task<StreamsEntry[]> XRangeAsync(string key, string start, string end, long count = -1);
Task<StreamsEntry[]> XRevRangeAsync(string key, string end, string start, long count = -1);
Task<StreamsEntry> XReadAsync(long block, string key, string id);
Task<StreamsEntryResult[]> XReadAsync(long count, long block, string key, string id, params string[] keyIds);
Task<StreamsEntryResult[]> XReadAsync(long count, long block, Dictionary<string, string> keyIds);
Task<StreamsEntry> XReadGroupAsync(string group, string consumer, long block, string key, string id);
Task<StreamsEntryResult[]> XReadGroupAsync(string group, string consumer, long count, long block, bool noack, string key, string id, params string[] keyIds);
Task<StreamsEntryResult[]> XReadGroupAsync(string group, string consumer, long count, long block, bool noack, Dictionary<string, string> keyIds);
Task<long> XTrimAsync(string key, long count);
Task<long> AppendAsync<T>(string key, T value);
Task<long> BitCountAsync(string key, long start, long end);
Task<long[]> BitFieldAsync(string key, params BitFieldAction[] actions);
Task<long> BitOpAsync(BitOpOperation operation, string destkey, params string[] keys);
Task<long> BitPosAsync(string key, bool bit, long? start = null, long? end = null);
Task<long> DecrAsync(string key);
Task<long> DecrByAsync(string key, long decrement);
Task<string> GetAsync(string key);
Task<string> GetDelAsync(string key);
Task<T> GetAsync<T>(string key);
Task<T> GetDelAsync<T>(string key);
Task GetAsync(string key, Stream destination, int bufferSize = 1024);
Task GetDelAsync(string key, Stream destination, int bufferSize = 1024);
Task<bool> GetBitAsync(string key, long offset);
Task<string> GetRangeAsync(string key, long start, long end);
Task<T> GetRangeAsync<T>(string key, long start, long end);
Task<string> GetSetAsync<T>(string key, T value);
Task<long> IncrAsync(string key);
Task<long> IncrByAsync(string key, long increment);
Task<decimal> IncrByFloatAsync(string key, decimal increment);
Task<string[]> MGetAsync(params string[] keys);
Task<T[]> MGetAsync<T>(params string[] keys);
Task MSetAsync(string key, object value, params object[] keyValues);
Task MSetAsync<T>(Dictionary<string, T> keyValues);
Task<bool> MSetNxAsync(string key, object value, params object[] keyValues);
Task<bool> MSetNxAsync<T>(Dictionary<string, T> keyValues);
Task PSetExAsync<T>(string key, long milliseconds, T value);
Task SetAsync<T>(string key, T value, int timeoutSeconds = 0);
Task SetAsync<T>(string key, T value, bool keepTtl);
Task<bool> SetNxAsync<T>(string key, T value, int timeoutSeconds);
Task<bool> SetNxAsync<T>(string key, T value, TimeSpan timeout);
Task<bool> SetXxAsync<T>(string key, T value, int timeoutSeconds = 0);
Task<bool> SetXxAsync<T>(string key, T value, TimeSpan timeout);
Task<bool> SetXxAsync<T>(string key, T value, bool keepTtl);
Task<string> SetAsync<T>(string key, T value, TimeSpan timeout, bool keepTtl, bool nx, bool xx, bool get);
Task SetAsync<T>(string key, T value, TimeSpan timeout);
Task<long> SetBitAsync(string key, long offset, bool value);
Task SetExAsync<T>(string key, int seconds, T value);
Task<bool> SetNxAsync<T>(string key, T value);
Task<long> SetRangeAsync<T>(string key, long offset, T value);
Task<long> StrLenAsync(string key);
#endif
}
} |
2881099/FreeRedis | 5,511 | src/FreeRedis/RedisClientEvents.cs | using System;
using System.Diagnostics;
using System.Text;
using FreeRedis.Internal;
namespace FreeRedis
{
public enum NoticeType
{
Call,
Info,
Event
}
public class NoticeEventArgs : EventArgs
{
public NoticeEventArgs(NoticeType noticeType, Exception exception, string log, object tag)
{
NoticeType = noticeType;
Exception = exception;
Log = log;
Tag = tag;
}
public NoticeType NoticeType { get; }
public Exception Exception { get; }
public string Log { get; }
public object Tag { get; }
}
public class ConnectedEventArgs : EventArgs
{
public ConnectedEventArgs(string host, RedisClientPool pool, RedisClient cli)
{
Host = host;
Pool = pool;
Client = cli;
}
public string Host { get; }
public RedisClientPool Pool { get; }
public RedisClient Client { get; }
}
public class DisconnectedEventArgs : EventArgs
{
public DisconnectedEventArgs(string host, RedisClientPool pool, RedisClient cli)
{
Host = host;
Pool = pool;
Client = cli;
}
public string Host { get; }
public RedisClientPool Pool { get; }
public RedisClient Client { get; }
}
public class UnavailableEventArgs : EventArgs
{
public UnavailableEventArgs(string host, RedisClientPool pool)
{
Host = host;
Pool = pool;
}
public string Host { get; }
public RedisClientPool Pool { get; }
}
public interface IInterceptor
{
void Before(InterceptorBeforeEventArgs args);
void After(InterceptorAfterEventArgs args);
}
public class InterceptorBeforeEventArgs
{
private object _value;
public InterceptorBeforeEventArgs(RedisClient cli, CommandPacket cmd, Type valueType)
{
Client = cli;
Command = cmd;
ValueType = valueType;
}
public long? OperationTimestamp { get; set; }
public RedisClient Client { get; }
public CommandPacket Command { get; }
public Type ValueType { get; }
public object Value
{
get => _value;
set
{
_value = value;
ValueIsChanged = true;
}
}
public bool ValueIsChanged { get; private set; }
}
public class InterceptorAfterEventArgs
{
public InterceptorAfterEventArgs(RedisClient cli, CommandPacket cmd, Type valueType, object value,
Exception exception, long elapsedMilliseconds)
{
Client = cli;
Command = cmd;
ValueType = valueType;
Value = value;
Exception = exception;
ElapsedMilliseconds = elapsedMilliseconds;
}
public long? OperationTimestamp { get; set; }
public RedisClient Client { get; }
public CommandPacket Command { get; }
public Type ValueType { get; }
public object Value { get; }
public Exception Exception { get; }
public long ElapsedMilliseconds { get; }
}
internal class NoticeCallInterceptor : IInterceptor
{
#if NETSTANDARD2_0_OR_GREATER
private static readonly DiagnosticSource _diagnosticListener = new DiagnosticListener(FreeRedisDiagnosticListenerNames.DiagnosticListenerName);
#endif
private readonly RedisClient _cli;
public NoticeCallInterceptor(RedisClient cli)
{
_cli = cli;
}
public void After(InterceptorAfterEventArgs args)
{
#if NETSTANDARD2_0_OR_GREATER
args.OperationTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (_diagnosticListener.IsEnabled(FreeRedisDiagnosticListenerNames.NoticeCallAfter))
_diagnosticListener.Write(FreeRedisDiagnosticListenerNames.NoticeCallAfter, args);
#endif
string log;
if (args.Exception != null)
{
log = $"{args.Exception.Message}";
}
else if (args.Value is Array array)
{
var sb = new StringBuilder().Append("[");
var itemindex = 0;
foreach (var item in array)
{
if (itemindex++ > 0) sb.Append(", ");
sb.Append(item.ToInvariantCultureToString());
}
log = sb.Append("]").ToString();
sb.Clear();
}
else
{
log = $"{args.Value.ToInvariantCultureToString()}";
}
_cli.OnNotice(null, new NoticeEventArgs(
NoticeType.Call,
args.Exception,
$"{(args.Command.WriteTarget ?? "Not connected").PadRight(21)} > {args.Command}\r\n{log}\r\n({args.ElapsedMilliseconds}ms)\r\n",
args.Value));
}
public void Before(InterceptorBeforeEventArgs args)
{
#if NETSTANDARD2_0_OR_GREATER
args.OperationTimestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (_diagnosticListener.IsEnabled(FreeRedisDiagnosticListenerNames.NoticeCallBefore))
_diagnosticListener.Write(FreeRedisDiagnosticListenerNames.NoticeCallBefore, args);
#endif
}
}
} |
2881099/FreeRedis | 7,729 | src/FreeRedis/ConnectionStringBuilder.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Text;
using System.Text.RegularExpressions;
namespace FreeRedis
{
public class ConnectionStringBuilder
{
string _Host;
public string Host
{
get => string.IsNullOrWhiteSpace(_Host) ? "127.0.0.1:6379" : _Host;
set => _Host = string.IsNullOrWhiteSpace(value) ? "127.0.0.1:6379" :
value.StartsWith("localhost", StringComparison.OrdinalIgnoreCase) ? Regex.Replace(value, "localhost", "127.0.0.1", RegexOptions.IgnoreCase) : value;
}
public bool Ssl { get; set; } = false;
public RedisProtocol Protocol { get; set; } = RedisProtocol.RESP2;
public string User { get; set; }
public string Password { get; set; }
public int Database { get; set; } = 0;
public string Prefix { get; set; }
public string ClientName { get; set; }
public Encoding Encoding { get; set; } = Encoding.UTF8;
public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromSeconds(20);
public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(10);
public TimeSpan ReceiveTimeout { get; set; } = TimeSpan.FromSeconds(20);
public TimeSpan SendTimeout { get; set; } = TimeSpan.FromSeconds(20);
public int MaxPoolSize { get; set; } = 100;
public int MinPoolSize { get; set; } = 1;
public int Retry { get; set; } = 0;
public bool ExitAutoDisposePool { get; set; } = true;
public bool SubscribeReadbytes { get; set; } = false;
public int FtDialect { get; set; } = 0;
public string FtLanguage { get; set; }
public RemoteCertificateValidationCallback CertificateValidation;
public LocalCertificateSelectionCallback CertificateSelection;
public static implicit operator ConnectionStringBuilder(string connectionString) => Parse(connectionString);
public static implicit operator string(ConnectionStringBuilder connectionString) => connectionString.ToString();
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(string.IsNullOrWhiteSpace(Host) ? "127.0.0.1:6379" : Host);
if (Ssl) sb.Append(",ssl=true");
if (Protocol == RedisProtocol.RESP3) sb.Append(",protocol=").Append(Protocol);
if (!string.IsNullOrWhiteSpace(User)) sb.Append(",user=").Append(User);
if (!string.IsNullOrEmpty(Password)) sb.Append(",password=").Append(Password);
if (Database > 0) sb.Append(",database=").Append(Database);
if (!string.IsNullOrWhiteSpace(Prefix)) sb.Append(",prefix=").Append(Prefix);
if (!string.IsNullOrWhiteSpace(ClientName)) sb.Append(",client name=").Append(ClientName);
if (Encoding != Encoding.UTF8) sb.Append(",encoding=").Append(Encoding.BodyName);
if (IdleTimeout != TimeSpan.FromSeconds(20)) sb.Append(",idle timeout=").Append((long)IdleTimeout.TotalMilliseconds);
if (ConnectTimeout != TimeSpan.FromSeconds(10)) sb.Append(",connect timeout=").Append((long)ConnectTimeout.TotalMilliseconds);
if (ReceiveTimeout != TimeSpan.FromSeconds(20)) sb.Append(",receive timeout=").Append((long)ReceiveTimeout.TotalMilliseconds);
if (SendTimeout != TimeSpan.FromSeconds(20)) sb.Append(",send timeout=").Append((long)SendTimeout.TotalMilliseconds);
if (MaxPoolSize != 100) sb.Append(",max pool size=").Append(MaxPoolSize);
if (MinPoolSize != 1) sb.Append(",min pool size=").Append(MinPoolSize);
if (Retry != 0) sb.Append(",retry=").Append(Retry);
if (ExitAutoDisposePool != true) sb.Append(",exitAutoDisposePool=false");
if (SubscribeReadbytes != false) sb.Append(",subscribeReadbytes=true");
if (FtDialect != 0) sb.Append(",ftdialect=").Append(FtDialect);
if (!string.IsNullOrWhiteSpace(FtLanguage)) sb.Append(",ftlanguage=").Append(FtLanguage);
return sb.ToString();
}
public static ConnectionStringBuilder Parse(string connectionString)
{
var ret = new ConnectionStringBuilder();
if (string.IsNullOrEmpty(connectionString)) return ret;
//支持密码中带有逗号,将原有 split(',') 改成以下处理方式
var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
ret.Host = vs[0].Trim();
for (var a = 1; a < vs.Length; a += 2)
{
var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
switch (kv[0])
{
case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
case "userid":
case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
case "password": if (kv.Length > 1) ret.Password = kv[1]; break;
case "database":
case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;
case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
case "name":
case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;
case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout >= 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout >= 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout >= 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout >= 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;
case "poolsize":
case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize >= 0) ret.MaxPoolSize = maxPoolSize; break;
case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize >= 0) ret.MinPoolSize = minPoolSize; break;
case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
case "exitautodisposepool": if (kv.Length > 1 && new[] { "false", "0" }.Contains(kv[1].Trim())) ret.ExitAutoDisposePool = false; break;
case "subscriblereadbytes": //history error
case "subscribereadbytes": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.SubscribeReadbytes = true; break;
case "ftdialect": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var dialect) && dialect > 0) ret.FtDialect = dialect; break;
case "ftlanguage": if (kv.Length > 1) ret.FtLanguage = kv[1].Trim(); break;
}
}
return ret;
}
}
}
|
2881099/FreeRedis | 1,983 | src/FreeRedis/FreeRedis.csproj | <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net451;net40</TargetFrameworks>
<AssemblyName>FreeRedis</AssemblyName>
<PackageId>FreeRedis</PackageId>
<RootNamespace>FreeRedis</RootNamespace>
<Version>1.5.0</Version>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageProjectUrl>https://github.com/2881099/FreeRedis</PackageProjectUrl>
<Description>FreeRedis is .NET redis client, supports cluster, sentinel, master-slave, pipeline, transaction and connection pool.</Description>
<RepositoryUrl>https://github.com/2881099/FreeRedis</RepositoryUrl>
<PackageTags>FreeRedis redis-trib cluster rediscluster sentinel</PackageTags>
<RepositoryType>git</RepositoryType>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Title>$(AssemblyName)</Title>
<IsPackable>true</IsPackable>
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
<WarningLevel>3</WarningLevel>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>key.snk</AssemblyOriginatorKeyFile>
<DelaySign>false</DelaySign>
<PackageReadmeFile>readme.md</PackageReadmeFile>
</PropertyGroup>
<ItemGroup>
<None Include="../../readme.md" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<PackageReference Include="System.Diagnostics.DiagnosticSource">
<Version>8.0.1</Version>
</PackageReference>
</ItemGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DocumentationFile>FreeRedis.xml</DocumentationFile>
<WarningLevel>3</WarningLevel>
<NoWarn>1701;1702;1591</NoWarn>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' == 'net40'">
<DefineConstants>net40</DefineConstants>
</PropertyGroup>
<PropertyGroup Condition="'$(TargetFramework)' != 'net40'">
<DefineConstants>isasync</DefineConstants>
</PropertyGroup>
</Project>
|
2881099/FreeRedis | 3,195 | src/FreeRedis/Internal/_net40.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FreeRedis
{
internal static class TaskEx
{
public static Task<T> FromResult<T>(T value)
{
#if net40
return new Task<T>(() => value);
#else
return Task.FromResult(value);
#endif
}
public static Task Run(Action action)
{
#if net40
var tcs = new TaskCompletionSource<object>();
new Thread(() =>
{
try
{
action();
tcs.SetResult(null);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
})
{ IsBackground = true }.Start();
return tcs.Task;
#else
return Task.Run(action);
#endif
}
public static Task<TResult> Run<TResult>(Func<TResult> function)
{
var tcs = new TaskCompletionSource<TResult>();
new Thread(() =>
{
try
{
tcs.SetResult(function());
}
catch (Exception ex)
{
tcs.SetException(ex);
}
})
{ IsBackground = true }.Start();
return tcs.Task;
}
public static Task Delay(TimeSpan timeout)
{
var tcs = new TaskCompletionSource<object>();
var timer = new System.Timers.Timer(timeout.TotalMilliseconds) { AutoReset = false };
timer.Elapsed += delegate { timer.Dispose(); tcs.SetResult(null); };
timer.Start();
return tcs.Task;
}
#if !NET40
public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout, string message = "The operation has timed out.")
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
return await task;
}
else
{
throw new TimeoutException(message);
}
}
}
public static async Task TimeoutAfter(this Task task, TimeSpan timeout, string message = "The operation has timed out.")
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
await task;
}
else
{
throw new TimeoutException(message);
}
}
}
#endif
}
} |
2881099/FreeRedis | 20,683 | src/FreeRedis/Internal/DefaultRedisSocket.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace FreeRedis.Internal
{
public interface IRedisSocketModify
{
void SetClientReply(ClientReplyType value);
void SetClientId(long value);
void SetDatabase(int value);
}
public class DefaultRedisSocket : IRedisSocket, IRedisSocketModify
{
public static TempProxyRedisSocket CreateTempProxy(IRedisSocket rds, Action dispose)
{
if (rds is TempProxyRedisSocket proxy)
return new TempProxyRedisSocket(proxy._owner, dispose);
return new TempProxyRedisSocket(rds, dispose);
}
public class TempProxyRedisSocket : IRedisSocket, IRedisSocketModify
{
public string _poolkey; //flag idlebus key
public RedisClientPool _pool; //flag pooling
public IRedisSocket _owner;
Action _dispose;
public TempProxyRedisSocket(IRedisSocket owner, Action dispose)
{
_owner = owner;
_dispose = dispose;
}
public void Dispose() => _dispose?.Invoke();
public string Host => _owner.Host;
public bool Ssl => _owner.Ssl;
public TimeSpan ConnectTimeout { get => _owner.ConnectTimeout; set => _owner.ConnectTimeout = value; }
public TimeSpan ReceiveTimeout { get => _owner.ReceiveTimeout; set => _owner.ReceiveTimeout = value; }
public TimeSpan SendTimeout { get => _owner.SendTimeout; set => _owner.SendTimeout = value; }
public Socket Socket => _owner.Socket;
public Stream Stream => _owner.Stream;
public bool IsConnected => _owner.IsConnected;
public RedisProtocol Protocol { get => _owner.Protocol; set => _owner.Protocol = value; }
public Encoding Encoding { get => _owner.Encoding; set => _owner.Encoding = value; }
public event EventHandler<EventArgs> Connected { add { _owner.Connected += value; } remove { _owner.Connected -= value; } }
public event EventHandler<EventArgs> Disconnected { add { _owner.Disconnected += value; } remove { _owner.Disconnected -= value; } }
public ClientReplyType ClientReply => _owner.ClientReply;
public long ClientId => _owner.ClientId;
public Guid ClientId2 => _owner.ClientId2;
public int Database => _owner.Database;
public CommandPacket LastCommand => _owner.LastCommand;
void IRedisSocketModify.SetClientReply(ClientReplyType value) => (_owner as IRedisSocketModify).SetClientReply(value);
void IRedisSocketModify.SetClientId(long value) => (_owner as IRedisSocketModify).SetClientId(value);
void IRedisSocketModify.SetDatabase(int value) => (_owner as IRedisSocketModify).SetDatabase(value);
public void Connect() => _owner.Connect();
public void ResetHost(string host) => _owner.ResetHost(host);
public void ReleaseSocket() => _owner.ReleaseSocket();
public void Write(CommandPacket cmd) => _owner.Write(cmd);
public RedisResult Read(CommandPacket cmd) => _owner.Read(cmd);
public void ReadChunk(Stream destination, int bufferSize = 1024) => _owner.ReadChunk(destination, bufferSize);
#if isasync
public Task WriteAsync(CommandPacket cmd) => _owner.WriteAsync(cmd);
public Task<RedisResult> ReadAsync(CommandPacket cmd) => _owner.ReadAsync(cmd);
public Task ReadChunkAsync(Stream destination, int bufferSize = 1024) => _owner.ReadChunkAsync(destination, bufferSize);
#endif
}
public string Host { get; private set; }
public bool Ssl { get; private set; }
string _ip;
int _port;
TimeSpan _receiveTimeout = TimeSpan.FromSeconds(20);
TimeSpan _sendTimeout = TimeSpan.FromSeconds(20);
public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(10);
public TimeSpan ReceiveTimeout
{
get => _receiveTimeout;
set
{
if (_socket != null) _socket.ReceiveTimeout = (int)value.TotalMilliseconds;
_receiveTimeout = value;
}
}
public TimeSpan SendTimeout
{
get => _sendTimeout;
set
{
if (_socket != null) _socket.SendTimeout = (int)value.TotalMilliseconds;
_sendTimeout = value;
}
}
Socket _socket;
public Socket Socket => _socket ?? throw new RedisClientException("Redis socket connection was not opened");
NetworkStream _netStream;
SslStream _sslStream;
public Stream Stream => ((Stream)_sslStream ?? _netStream) ?? throw new RedisClientException("Redis socket connection was not opened");
public bool IsConnected => _socket?.Connected == true && _netStream != null;
public event EventHandler<EventArgs> Connected;
public event EventHandler<EventArgs> Disconnected;
public ClientReplyType ClientReply { get; protected set; } = ClientReplyType.on;
public long ClientId { get; protected set; }
public Guid ClientId2 { get; } = Guid.NewGuid();
public int Database { get; protected set; } = 0;
public CommandPacket LastCommand { get; protected set; }
void IRedisSocketModify.SetClientReply(ClientReplyType value) => this.ClientReply = value;
void IRedisSocketModify.SetClientId(long value) => this.ClientId = value;
void IRedisSocketModify.SetDatabase(int value) => this.Database = value;
RespHelper.Resp3Reader _reader;
RespHelper.Resp3Reader Reader => _reader ?? (_reader = new RespHelper.Resp3Reader(Stream));
public RedisProtocol Protocol { get; set; } = RedisProtocol.RESP2;
public Encoding Encoding { get; set; } = Encoding.UTF8;
RemoteCertificateValidationCallback _certificateValidation;
LocalCertificateSelectionCallback _certificateSelection;
public DefaultRedisSocket(string host, bool ssl, RemoteCertificateValidationCallback certificateValidation, LocalCertificateSelectionCallback certificateSelection)
{
Host = host;
Ssl = ssl;
_certificateValidation = certificateValidation;
_certificateSelection = certificateSelection;
}
void WriteAfter(CommandPacket cmd)
{
switch (cmd._command)
{
case "CLIENT":
switch (cmd._subcommand)
{
case "REPLY":
var type = cmd._input.LastOrDefault().ConvertTo<ClientReplyType>();
if (type != ClientReply) ClientReply = type;
break;
case "ID":
cmd.OnData(rt =>
{
ClientId = rt.ThrowOrValue<long>();
});
break;
}
break;
case "SELECT":
var dbidx = cmd._input.LastOrDefault()?.ConvertTo<int?>();
if (dbidx != null) Database = dbidx.Value;
break;
}
cmd.WriteTarget = $"{this.Host}/{this.Database}";
cmd.ClientId2 = ClientId2;
}
public void Write(CommandPacket cmd)
{
LastCommand = cmd;
if (IsConnected == false) Connect();
using (var ms = new MemoryStream()) //Writing data directly to will be very slow
{
new RespHelper.Resp3Writer(ms, Encoding, Protocol).WriteCommand(cmd);
ms.Position = 0;
try
{
ms.CopyTo(Stream);
}
catch(Exception ex)
{
ReleaseSocket();
throw new ProtocolViolationException($"Socket.Write error: {ex.Message}");
}
finally
{
ms.Close();
}
}
WriteAfter(cmd);
}
public RedisResult Read(CommandPacket cmd)
{
LastCommand = cmd;
if (ClientReply == ClientReplyType.on)
{
if (IsConnected == false) Connect();
RedisResult rt;
try
{
rt = Reader.ReadObject(cmd?._flagReadbytes == true ? null : Encoding);
}
catch (Exception ex)
{
ReleaseSocket();
throw new ProtocolViolationException($"Socket.Read error: {ex.Message}");
}
rt.Encoding = Encoding;
cmd?.OnDataTrigger(rt);
return rt;
}
return new RedisResult(null, true, RedisMessageType.SimpleString) { Encoding = Encoding };
}
public void ReadChunk(Stream destination, int bufferSize = 1024)
{
if (ClientReply == ClientReplyType.on)
{
if (IsConnected == false) Connect();
try
{
Reader.ReadBlobStringChunk(destination, bufferSize);
}
catch (Exception ex)
{
ReleaseSocket();
throw new ProtocolViolationException($"Socket.Read error: {ex.Message}");
}
}
}
#if isasync
async public Task WriteAsync(CommandPacket cmd)
{
LastCommand = cmd;
if (IsConnected == false) Connect();
using (var ms = new MemoryStream()) //Writing data directly to will be very slow
{
new RespHelper.Resp3Writer(ms, Encoding, Protocol).WriteCommand(cmd);
ms.Position = 0;
try
{
await ms.CopyToAsync(Stream);
}
catch (Exception ex)
{
ReleaseSocket();
throw new ProtocolViolationException($"Socket.Write error: {ex.Message}");
}
finally
{
ms.Close();
}
}
WriteAfter(cmd);
}
async public Task<RedisResult> ReadAsync(CommandPacket cmd)
{
LastCommand = cmd;
if (ClientReply == ClientReplyType.on)
{
if (IsConnected == false) Connect();
RedisResult rt;
try
{
rt = await Reader.ReadObjectAsync(cmd?._flagReadbytes == true ? null : Encoding);
}
catch (Exception ex)
{
ReleaseSocket();
throw new ProtocolViolationException($"Socket.Read error: {ex.Message}");
}
rt.Encoding = Encoding;
cmd?.OnDataTrigger(rt);
return rt;
}
return new RedisResult(null, true, RedisMessageType.SimpleString) { Encoding = Encoding };
}
async public Task ReadChunkAsync(Stream destination, int bufferSize = 1024)
{
if (ClientReply == ClientReplyType.on)
{
if (IsConnected == false) Connect();
try
{
await Reader.ReadBlobStringChunkAsync(destination, bufferSize);
}
catch (Exception ex)
{
ReleaseSocket();
throw new ProtocolViolationException($"Socket.Read error: {ex.Message}");
}
}
}
#endif
object _connectLock = new object();
public void Connect()
{
lock (_connectLock)
{
ResetHost(Host);
EndPoint endpoint = IPAddress.TryParse(_ip, out var tryip) ?
(EndPoint)new IPEndPoint(tryip, _port) :
(EndPoint)new IPEndPoint(DnsResolver.Instance.Resolve(_ip)[0], _port);
//new DnsEndPoint(_ip, _port);
var localSocket = endpoint.AddressFamily == AddressFamily.InterNetworkV6 ?
new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp) :
new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
var asyncResult = localSocket.BeginConnect(endpoint, null, null);
if (!asyncResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true))
{
var endpointString = endpoint.ToString();
if (endpointString != $"{_ip}:{_port}") endpointString = $"{_ip}:{_port} -> {endpointString}";
var debugString = "";
if (endpoint is DnsEndPoint)
{
try { debugString = $", DEBUG: Dns.GetHostEntry({_ip})={Dns.GetHostEntry(_ip)}"; }
catch (Exception ex) { debugString = $", DEBUG: {ex.Message}"; }
}
throw new TimeoutException($"Connect to redis-server({endpointString}) timeout{debugString}");
}
localSocket.EndConnect(asyncResult);
}
catch
{
ReleaseSocket(localSocket);
throw;
}
_socket = localSocket;
_socket.ReceiveTimeout = (int)ReceiveTimeout.TotalMilliseconds;
_socket.SendTimeout = (int)SendTimeout.TotalMilliseconds;
_netStream = new NetworkStream(Socket, true);
if (Ssl)
{
_sslStream = new SslStream(_netStream, true, _certificateValidation, _certificateSelection);
var stringHostOnly = endpoint is DnsEndPoint ep1 ? ep1.Host :
(endpoint is IPEndPoint ep2 ? ep2.Address.ToString() : "");
_sslStream.AuthenticateAsClient(stringHostOnly);
}
Connected?.Invoke(this, new EventArgs());
}
}
public void ResetHost(string host)
{
this.Host = host;
ReleaseSocket();
var sh = SplitHost(host);
_ip = sh.Key;
_port = sh.Value;
}
void ReleaseSocket(Socket socket)
{
if (socket == null) return;
try { socket.Shutdown(SocketShutdown.Both); } catch { }
try { socket.Close(); } catch { }
try { socket.Dispose(); } catch { }
}
public void ReleaseSocket()
{
lock (_connectLock)
{
if (_socket != null)
{
ReleaseSocket(_socket);
_socket = null;
}
if (_sslStream != null)
{
try { _sslStream.Close(); } catch { }
try { _sslStream.Dispose(); } catch { }
_sslStream = null;
}
if (_netStream != null)
{
try { _netStream.Close(); } catch { }
try { _netStream.Dispose(); } catch { }
_netStream = null;
}
_reader = null;
Disconnected?.Invoke(this, new EventArgs());
}
}
public void Dispose()
{
ReleaseSocket();
}
public static KeyValuePair<string, int> SplitHost(string host)
{
if (string.IsNullOrWhiteSpace(host?.Trim()))
return new KeyValuePair<string, int>("127.0.0.1", 6379);
host = host.Trim();
var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(),
int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);
var spt = (host ?? "").Split(':');
if (spt.Length == 1) //ipv4 or domain
return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);
if (spt.Length == 2) //ipv4:port or domain:port
{
if (int.TryParse(spt.Last().Trim(), out var testPort2))
return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);
return new KeyValuePair<string, int>(host, 6379);
}
if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
return new KeyValuePair<string, int>(host, 6379);
if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
{
var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
return new KeyValuePair<string, int>(testHost, 6379);
}
return new KeyValuePair<string, int>(host, 6379);
}
class DnsResolver
{
public static DnsResolver Instance { get; set; } = new DnsResolver();
public TimeSpan Expire { set; get; } = TimeSpan.FromMinutes(5);
private readonly ConcurrentDictionary<string, DnsItem> _cache = new ConcurrentDictionary<string, DnsItem>();
public IPAddress[] Resolve(string host)
{
if (_cache.TryGetValue(host, out var item))
{
if (item.UpdateTime.Add(Expire) <= DateTime.Now)
#if isasync
Task.Run(() => ResolveCore(host, item, false));
#else
ResolveCore(host, item, false);
#endif
}
else
item = ResolveCore(host, item, true);
return item?.Addresses;
}
DnsItem ResolveCore(string host, DnsItem item, Boolean throwError)
{
try
{
#if isasync
var task = Dns.GetHostAddressesAsync(host);
if (!task.Wait(5000))
{
if (throwError) throw new TaskCanceledException();
return null;
}
var addrs = task.ConfigureAwait(false).GetAwaiter().GetResult();
#else
var addrs = Dns.GetHostAddresses(host);
#endif
if (addrs != null && addrs.Length > 0)
{
if (item == null)
{
_cache[host] = item = new DnsItem
{
Host = host,
Addresses = addrs,
CreateTime = DateTime.Now,
UpdateTime = DateTime.Now
};
}
else
{
item.Addresses = addrs;
item.UpdateTime = DateTime.Now;
}
}
}
catch
{
if (item != null) return item;
if (throwError) throw;
}
return item;
}
class DnsItem
{
public string Host { get; set; }
public IPAddress[] Addresses { get; set; }
public DateTime CreateTime { get; set; }
public DateTime UpdateTime { get; set; }
}
}
}
}
|
2881099/FreeRedis | 58,216 | src/FreeRedis/Internal/RespHelper.cs | using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Text;
namespace FreeRedis
{
public static partial class RespHelper
{
public partial class Resp3Reader
{
internal Stream _stream;
public Resp3Reader(Stream stream)
{
_stream = stream;
}
public void ReadBlobStringChunk(Stream destination, int bufferSize)
{
char c = (char)_stream.ReadByte();
switch (c)
{
case '$':
case '=':
case '!': ReadBlobString(c, null, destination, bufferSize); break;
default: throw new ProtocolViolationException($"Expecting fail MessageType '{c}'");
}
}
object ReadBlobString(char msgtype, Encoding encoding, Stream destination, int bufferSize)
{
var clob = ReadClob();
if (encoding == null) return clob;
if (clob == null) return null;
return encoding.GetString(clob);
byte[] ReadClob()
{
MemoryStream ms = null;
try
{
if (destination == null) destination = ms = new MemoryStream();
var lenstr = ReadLine(null);
if (int.TryParse(lenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var len))
{
if (len < 0) return null;
if (len > 0) Read(destination, len, bufferSize);
ReadLine(null);
if (len == 0) return new byte[0];
return ms?.ToArray();
}
if (lenstr == "?")
{
while (true)
{
char c = (char)_stream.ReadByte();
if (c != ';') throw new ProtocolViolationException($"Expecting fail Streamed strings ';', got '{c}'");
var clenstr = ReadLine(null);
if (int.TryParse(clenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var clen))
{
if (clen == 0) break;
if (clen > 0)
{
Read(destination, clen, bufferSize);
ReadLine(null);
continue;
}
}
throw new ProtocolViolationException($"Expecting fail Streamed strings ';0', got ';{clenstr}'");
}
return ms?.ToArray();
}
throw new ProtocolViolationException($"Expecting fail Blob string '{msgtype}0', got '{msgtype}{lenstr}'");
}
finally
{
ms?.Close();
ms?.Dispose();
}
}
}
string ReadSimpleString()
{
return ReadLine(null);
//byte[] ReadClob()
//{
// MemoryStream ms = null;
// try
// {
// ms = new MemoryStream();
// ReadLine(ms);
// return ms.ToArray();
// }
// finally
// {
// ms?.Close();
// ms?.Dispose();
// }
//}
}
long ReadNumber(char msgtype)
{
var numstr = ReadLine(null);
if (long.TryParse(numstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var num)) return num;
throw new ProtocolViolationException($"Expecting fail Number '{msgtype}0', got '{msgtype}{numstr}'");
}
BigInteger ReadBigNumber(char msgtype)
{
var numstr = ReadLine(null);
if (BigInteger.TryParse(numstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var num)) return num;
throw new ProtocolViolationException($"Expecting fail BigNumber '{msgtype}0', got '{msgtype}{numstr}'");
}
double ReadDouble(char msgtype)
{
var numstr = ReadLine(null);
switch (numstr)
{
case "inf": return double.PositiveInfinity;
case "-inf": return double.NegativeInfinity;
}
if (double.TryParse(numstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var num)) return num;
throw new ProtocolViolationException($"Expecting fail Double '{msgtype}1.23', got '{msgtype}{numstr}'");
}
bool ReadBoolean(char msgtype)
{
var boolstr = ReadLine(null);
switch (boolstr)
{
case "t": return true;
case "f": return false;
}
throw new ProtocolViolationException($"Expecting fail Boolean '{msgtype}t', got '{msgtype}{boolstr}'");
}
object[] ReadArray(char msgtype, Encoding encoding)
{
var lenstr = ReadLine(null);
if (int.TryParse(lenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var len))
{
if (len < 0) return null;
var arr = new object[len];
for (var a = 0; a < len; a++)
arr[a] = ReadObject(encoding).Value;
//if (len == 1 && arr[0] == null) return new object[0];
return arr;
}
if (lenstr == "?")
{
var arr = new List<object>();
while (true)
{
var ro = ReadObject(encoding);
if (ro.IsEnd) break;
arr.Add(ro.Value);
}
return arr.ToArray();
}
throw new ProtocolViolationException($"Expecting fail Array '{msgtype}3', got '{msgtype}{lenstr}'");
}
object[] ReadMap(char msgtype, Encoding encoding)
{
var lenstr = ReadLine(null);
if (int.TryParse(lenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var len))
{
if (len < 0) return null;
var arr = new object[len * 2];
for (var a = 0; a < len; a++)
{
arr[a * 2] = ReadObject(encoding).Value;
arr[a * 2 + 1] = ReadObject(encoding).Value;
}
return arr;
}
if (lenstr == "?")
{
var arr = new List<object>();
while (true)
{
var rokey = ReadObject(encoding);
if (rokey.IsEnd) break;
var roval = ReadObject(encoding);
arr.Add(rokey.Value);
arr.Add(roval.Value);
}
return arr.ToArray();
}
throw new ProtocolViolationException($"Expecting fail Map '{msgtype}3', got '{msgtype}{lenstr}'");
}
//public static int debugger = 0;
public RedisResult ReadObject(Encoding encoding)
{
while (true)
{
var b = _stream.ReadByte();
var c = (char)b;
//debugger++;
//if (debugger > 10000 && debugger % 10 == 0)
// throw new ProtocolViolationException($"Expecting fail MessageType '{b},{string.Join(",", ReadAll())}'");
switch (c)
{
case '$': return new RedisResult(ReadBlobString(c, encoding, null, 1024), false, RedisMessageType.BlobString);
case '+': return new RedisResult(ReadSimpleString(), false, RedisMessageType.SimpleString);
case '=': return new RedisResult(ReadBlobString(c, encoding, null, 1024), false, RedisMessageType.VerbatimString);
case '-':
{
var simpleError = ReadSimpleString();
if (simpleError == "NOAUTH Authentication required.")
throw new ProtocolViolationException(simpleError);
return new RedisResult(simpleError, false, RedisMessageType.SimpleError);
}
case '!': return new RedisResult(ReadBlobString(c, encoding, null, 1024), false, RedisMessageType.BlobError);
case ':': return new RedisResult(ReadNumber(c), false, RedisMessageType.Number);
case '(': return new RedisResult(ReadBigNumber(c), false, RedisMessageType.BigNumber);
case '_': ReadLine(null); return new RedisResult(null, false, RedisMessageType.Null);
case ',': return new RedisResult(ReadDouble(c), false, RedisMessageType.Double);
case '#': return new RedisResult(ReadBoolean(c), false, RedisMessageType.Boolean);
case '*': return new RedisResult(ReadArray(c, encoding), false, RedisMessageType.Array);
case '~': return new RedisResult(ReadArray(c, encoding), false, RedisMessageType.Set);
case '>': return new RedisResult(ReadArray(c, encoding), false, RedisMessageType.Push);
case '%': return new RedisResult(ReadMap(c, encoding), false, RedisMessageType.Map);
case '|': return new RedisResult(ReadMap(c, encoding), false, RedisMessageType.Attribute);
case '.': ReadLine(null); return new RedisResult(null, true, RedisMessageType.SimpleString); //无类型
case ' ': continue;
default:
if (b == -1) return new RedisResult(null, true, RedisMessageType.Null);
//if (b == -1) return new RedisResult(null, true, RedisMessageType.Null);
var allBytes = DebugReadAll();
throw new ProtocolViolationException($"Expecting fail MessageType '{b},{string.Join(",", allBytes)}'");
}
}
}
Byte[] DebugReadAll()
{
var ns = _stream as NetworkStream;
if (ns != null)
{
using (var ms = new MemoryStream())
{
try
{
var data = new byte[1024];
while (ns.DataAvailable && ns.CanRead)
{
int numBytesRead = numBytesRead = ns.Read(data, 0, data.Length);
if (numBytesRead <= 0) break;
ms.Write(data, 0, numBytesRead);
if (numBytesRead < data.Length) break;
}
}
catch { }
return ms.ToArray();
}
}
var ss = _stream as SslStream;
if (ss != null)
{
using (var ms = new MemoryStream())
{
try
{
var data = new byte[1024];
while (ss.CanRead)
{
int numBytesRead = numBytesRead = ss.Read(data, 0, data.Length);
if (numBytesRead <= 0) break;
ms.Write(data, 0, numBytesRead);
if (numBytesRead < data.Length) break;
}
}
catch { }
return ms.ToArray();
}
}
return new byte[0];
}
void Read(Stream outStream, int len, int bufferSize = 1024)
{
if (len <= 0) return;
var buffer = new byte[Math.Min(bufferSize, len)];
var bufferLength = buffer.Length;
while (true)
{
var readed = _stream.Read(buffer, 0, bufferLength);
if (readed <= 0) throw new ProtocolViolationException($"Expecting fail Read surplus length: {len}");
if (readed > 0) outStream.Write(buffer, 0, readed);
len = len - readed;
if (len <= 0) break;
if (len < buffer.Length) bufferLength = len;
}
}
string ReadLine(Stream outStream)
{
var sb = outStream == null ? new StringBuilder() : null;
var buffer = new byte[1];
var should_break = false;
while (true)
{
var readed = _stream.Read(buffer, 0, 1);
if (readed <= 0) throw new ProtocolViolationException($"Expecting fail ReadLine end of stream");
if (buffer[0] == 13)
should_break = true;
else if (buffer[0] == 10 && should_break)
break;
else
{
if (outStream == null) sb.Append((char)buffer[0]);
else outStream.WriteByte(buffer[0]);
should_break = false;
}
}
return sb?.ToString();
}
}
public class Resp3Writer
{
internal Stream _stream;
internal Encoding _encoding;
internal RedisProtocol _protocol;
public Resp3Writer(Stream stream, Encoding encoding, RedisProtocol protocol)
{
_stream = stream;
_encoding = encoding ?? Encoding.UTF8;
_protocol = protocol;
}
public void WriteCommand(List<object> cmd)
{
WriteNumber('*', cmd.Count);
foreach (var c in cmd)
{
if (c is byte[]) WriteClob(c as byte[]);
else if (c is Enum) WriteBlobString(c.ToInvariantCultureToString()); //.ToUpper()); geo km
else WriteBlobString(c.ToInvariantCultureToString());
}
}
static readonly byte[] Crlf = new byte[] { 13, 10 };
static readonly byte[] Null = new byte[] { 93, 13, 10 }; //_\r\n
Resp3Writer WriteBlobString(string text, char msgtype = '$')
{
if (text == null) return WriteNull();
return WriteClob(_encoding.GetBytes(text), msgtype);
}
Resp3Writer WriteClob(byte[] data, char msgtype = '$')
{
if (data == null) return WriteNull();
var size = _encoding.GetBytes($"{msgtype}{data.Length}\r\n");
_stream.Write(size, 0, size.Length);
_stream.Write(data, 0, data.Length);
_stream.Write(Crlf, 0, Crlf.Length);
return this;
}
Resp3Writer WriteSimpleString(string text)
{
if (text == null) return WriteNull();
if (text.Contains("\r\n")) return WriteBlobString(text);
return WriteRaw($"+{text}\r\n");
}
Resp3Writer WriteVerbatimString(string text) => WriteBlobString(text, '=');
Resp3Writer WriteBlobError(string error) => WriteBlobString(error, '!');
Resp3Writer WriteSimpleError(string error)
{
if (error == null) return WriteNull();
if (error.Contains("\r\n"))
{
if (_protocol == RedisProtocol.RESP2) return WriteSimpleString(error.Replace("\r\n", " "));
return WriteBlobError(error);
}
return WriteRaw($"-{error}\r\n");
}
Resp3Writer WriteNumber(char mstype, object number)
{
if (number == null) return WriteNull();
return WriteRaw($"{mstype}{number.ToInvariantCultureToString()}\r\n");
}
Resp3Writer WriteDouble(double? number)
{
if (number == null) return WriteNull();
if (_protocol == RedisProtocol.RESP2) return WriteBlobString(number.ToInvariantCultureToString());
switch (number)
{
case double.PositiveInfinity: return WriteRaw($",inf\r\n");
case double.NegativeInfinity: return WriteRaw($",-inf\r\n");
default: return WriteRaw($",{number.ToInvariantCultureToString()}\r\n");
}
}
Resp3Writer WriteBoolean(bool? val)
{
if (val == null) return WriteNull();
if (_protocol == RedisProtocol.RESP2) return WriteNumber(':', val.Value ? 1 : 0);
return WriteRaw(val.Value ? $"#t\r\n" : "#f\r\n");
}
Resp3Writer WriteNull()
{
if (_protocol == RedisProtocol.RESP2) return WriteBlobString("");
_stream.Write(Null, 0, Null.Length);
return this;
}
Resp3Writer WriteRaw(string raw)
{
if (string.IsNullOrWhiteSpace(raw)) return this;
var data = _encoding.GetBytes($"{raw.ToInvariantCultureToString()}");
_stream.Write(data, 0, data.Length);
return this;
}
public Resp3Writer WriteObject(object obj)
{
if (obj == null) WriteNull();
if (obj is string str) return WriteBlobString(str);
if (obj is byte[] byt) return WriteClob(byt);
var objtype = obj.GetType();
if (_dicIsNumberType.Value.TryGetValue(objtype, out var tryval))
{
switch (tryval)
{
case 1: return WriteNumber(':', obj);
case 2: return WriteDouble((double?)obj);
case 3: return WriteNumber(',', obj);
}
}
objtype = objtype.NullableTypeOrThis();
if (objtype == typeof(bool)) return WriteBoolean((bool?)obj);
if (objtype.IsEnum) return WriteNumber(':', obj);
if (objtype == typeof(char)) return WriteBlobString(obj.ToString());
if (objtype == typeof(DateTime)) return WriteBlobString(obj.ToString());
if (objtype == typeof(DateTimeOffset)) return WriteBlobString(((DateTimeOffset)obj).ToString("yyyy-MM-dd HH:mm:ss.fff zzzz"));
if (objtype == typeof(TimeSpan)) return WriteBlobString(obj.ToInvariantCultureToString());
if (objtype == typeof(BigInteger)) return WriteNumber('(', obj);
if (obj is Exception ex) return WriteSimpleError(ex.Message);
if (obj is IDictionary dic)
{
if (_protocol == RedisProtocol.RESP2) WriteNumber('*', dic.Count * 2);
else WriteNumber('%', dic.Count);
foreach (var key in dic.Keys)
WriteObject(key).WriteObject(dic[key]);
return this;
}
if (obj is IEnumerable ie)
{
using (var ms = new MemoryStream())
{
var msWriter = new Resp3Writer(ms, _encoding, _protocol);
var idx = 0;
foreach (var z in ie)
{
msWriter.WriteObject(z);
idx++;
}
if (idx > 0 && ms.Length > 0)
{
WriteNumber('*', idx);
ms.Position = 0;
ms.CopyTo(_stream);
}
ms.Close();
}
return this;
}
var ps = objtype.GetPropertiesDictIgnoreCase().Values;
if (_protocol == RedisProtocol.RESP2) WriteNumber('*', ps.Count * 2);
else WriteNumber('%', ps.Count);
foreach (var p in ps)
{
var pvalue = p.GetValue(obj, null);
WriteObject(p.Name).WriteObject(pvalue);
}
return this;
}
}
#region ExpressionTree
static int SetSetPropertyOrFieldValueSupportExpressionTreeFlag = 1;
static ConcurrentDictionary<Type, ConcurrentDictionary<string, Action<object, string, object>>> _dicSetPropertyOrFieldValue = new ConcurrentDictionary<Type, ConcurrentDictionary<string, Action<object, string, object>>>();
public static void SetPropertyOrFieldValue(this Type entityType, object entity, string propertyName, object value)
{
if (entity == null) return;
if (entityType == null) entityType = entity.GetType();
if (SetSetPropertyOrFieldValueSupportExpressionTreeFlag == 0)
{
if (GetPropertiesDictIgnoreCase(entityType).TryGetValue(propertyName, out var prop))
{
prop.SetValue(entity, value, null);
return;
}
if (GetFieldsDictIgnoreCase(entityType).TryGetValue(propertyName, out var field))
{
field.SetValue(entity, value);
return;
}
throw new Exception($"The property({propertyName}) was not found in the type({entityType.DisplayCsharp()})");
}
Action<object, string, object> func = null;
try
{
func = _dicSetPropertyOrFieldValue
.GetOrAdd(entityType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
.GetOrAdd(propertyName, pn =>
{
var t = entityType;
MemberInfo memberinfo = entityType.GetPropertyOrFieldIgnoreCase(pn);
var parm1 = Expression.Parameter(typeof(object));
var parm2 = Expression.Parameter(typeof(string));
var parm3 = Expression.Parameter(typeof(object));
var var1Parm = Expression.Variable(t);
var exps = new List<Expression>(new Expression[] {
Expression.Assign(var1Parm, Expression.TypeAs(parm1, t))
});
if (memberinfo != null)
{
exps.Add(
Expression.Assign(
Expression.MakeMemberAccess(var1Parm, memberinfo),
Expression.Convert(
parm3,
memberinfo.GetPropertyOrFieldType()
)
)
);
}
return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
});
}
catch
{
System.Threading.Interlocked.Exchange(ref SetSetPropertyOrFieldValueSupportExpressionTreeFlag, 0);
SetPropertyOrFieldValue(entityType, entity, propertyName, value);
return;
}
func(entity, propertyName, value);
}
#endregion
#region 常用缓存的反射方法
static Lazy<Dictionary<Type, byte>> _dicIsNumberType = new Lazy<Dictionary<Type, byte>>(() => new Dictionary<Type, byte>
{
[typeof(sbyte)] = 1,
[typeof(sbyte?)] = 1,
[typeof(short)] = 1,
[typeof(short?)] = 1,
[typeof(int)] = 1,
[typeof(int?)] = 1,
[typeof(long)] = 1,
[typeof(long?)] = 1,
[typeof(byte)] = 1,
[typeof(byte?)] = 1,
[typeof(ushort)] = 1,
[typeof(ushort?)] = 1,
[typeof(uint)] = 1,
[typeof(uint?)] = 1,
[typeof(ulong)] = 1,
[typeof(ulong?)] = 1,
[typeof(double)] = 2,
[typeof(double?)] = 2,
[typeof(float)] = 2,
[typeof(float?)] = 2,
[typeof(decimal)] = 3,
[typeof(decimal?)] = 3
});
internal static bool IsIntegerType(this Type that) => that == null ? false : (_dicIsNumberType.Value.TryGetValue(that, out var tryval) ? tryval == 1 : false);
internal static bool IsNumberType(this Type that) => that == null ? false : _dicIsNumberType.Value.ContainsKey(that);
internal static bool IsNullableType(this Type that) => that.IsArray == false && that?.FullName.StartsWith("System.Nullable`1[") == true;
internal static bool IsAnonymousType(this Type that) => that?.FullName.StartsWith("<>f__AnonymousType") == true;
internal static bool IsArrayOrList(this Type that) => that == null ? false : (that.IsArray || typeof(IList).IsAssignableFrom(that));
internal static Type NullableTypeOrThis(this Type that) => that?.IsNullableType() == true ? that.GetGenericArguments().First() : that;
internal static string DisplayCsharp(this Type type, bool isNameSpace = true)
{
if (type == null) return null;
if (type == typeof(void)) return "void";
if (type.IsGenericParameter) return type.Name;
if (type.IsArray) return $"{DisplayCsharp(type.GetElementType())}[]";
var sb = new StringBuilder();
var nestedType = type;
while (nestedType.IsNested)
{
sb.Insert(0, ".").Insert(0, DisplayCsharp(nestedType.DeclaringType, false));
nestedType = nestedType.DeclaringType;
}
if (isNameSpace && string.IsNullOrWhiteSpace(nestedType.Namespace) == false)
sb.Insert(0, ".").Insert(0, nestedType.Namespace);
if (type.IsGenericType == false)
return sb.Append(type.Name).ToString();
var genericParameters = type.GetGenericArguments();
if (type.IsNested && type.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in type.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any() == false)
return sb.Append(type.Name).ToString();
var idxof = type.Name.IndexOf('`');
if (idxof == -1) return sb.Append(type.Name).ToString();
sb.Append(type.Name.Remove(type.Name.IndexOf('`'))).Append("<");
var genericTypeIndex = 0;
foreach (var genericType in genericParameters)
{
if (genericTypeIndex++ > 0) sb.Append(", ");
sb.Append(DisplayCsharp(genericType, true));
}
return sb.Append(">").ToString();
}
public static string DisplayCsharp(this MethodInfo method, bool isOverride)
{
if (method == null) return null;
var sb = new StringBuilder();
if (method.IsPublic) sb.Append("public ");
if (method.IsAssembly) sb.Append("internal ");
if (method.IsFamily) sb.Append("protected ");
if (method.IsPrivate) sb.Append("private ");
if (method.IsPrivate) sb.Append("private ");
if (method.IsStatic) sb.Append("static ");
if (method.IsAbstract && method.DeclaringType.IsInterface == false) sb.Append("abstract ");
if (method.IsVirtual && method.DeclaringType.IsInterface == false) sb.Append(isOverride ? "override " : "virtual ");
sb.Append(method.ReturnType.DisplayCsharp()).Append(" ").Append(method.Name);
var genericParameters = method.GetGenericArguments();
if (method.DeclaringType.IsNested && method.DeclaringType.DeclaringType.IsGenericType)
{
var dic = genericParameters.ToDictionary(a => a.Name);
foreach (var nestedGenericParameter in method.DeclaringType.DeclaringType.GetGenericArguments())
if (dic.ContainsKey(nestedGenericParameter.Name))
dic.Remove(nestedGenericParameter.Name);
genericParameters = dic.Values.ToArray();
}
if (genericParameters.Any())
sb.Append("<")
.Append(string.Join(", ", genericParameters.Select(a => a.DisplayCsharp())))
.Append(">");
sb.Append("(").Append(string.Join(", ", method.GetParameters().Select(a => LocalDisplayCsharpParameter(a)))).Append(")");
return sb.ToString();
string LocalDisplayCsharpParameter(ParameterInfo lp)
{
var pstr = "";
object[] pattrs = new object[0];
try { pattrs = lp.GetCustomAttributes(false); } catch { }
if (pattrs.Any(a => a is ParamArrayAttribute)) pstr = "params ";
pstr = $"{pstr}{lp.ParameterType.DisplayCsharp()} {lp.Name}";
#if net40
if (pattrs.Any(a => a is System.Runtime.InteropServices.OptionalAttribute) == false) return pstr;
#else
if (lp.HasDefaultValue == false) return pstr;
#endif
if (lp.DefaultValue == null) return $"{pstr} = null";
if (lp.ParameterType == typeof(string)) return $"{pstr} = \"{lp.DefaultValue.ToString().Replace("\"", "\\\"").Replace("\r\n", "\\r\\n").Replace("\n", "\\n")}\"";
if (lp.ParameterType == typeof(bool) || lp.ParameterType == typeof(bool?)) return $"{pstr} = {lp.DefaultValue.ToString().Replace("False", "false").Replace("True", "true")}";
if (lp.ParameterType.IsEnum) return $"{pstr} = {lp.ParameterType.DisplayCsharp(false)}.{lp.DefaultValue}";
return $"{pstr} = {lp.DefaultValue}";
}
}
internal static object CreateInstanceGetDefaultValue(this Type that)
{
if (that == null) return null;
if (that == typeof(string)) return default(string);
if (that == typeof(Guid)) return default(Guid);
if (that == typeof(byte[])) return default(byte[]);
if (that.IsArray) return Array.CreateInstance(that.GetElementType(), 0);
if (that.IsInterface || that.IsAbstract) return null;
var ctorParms = that.InternalGetTypeConstructor0OrFirst(false)?.GetParameters();
if (ctorParms == null || ctorParms.Any() == false) return Activator.CreateInstance(that, true);
return Activator.CreateInstance(that, ctorParms
.Select(a => a.ParameterType.IsInterface || a.ParameterType.IsAbstract || a.ParameterType == typeof(string) || a.ParameterType.IsArray ?
null :
Activator.CreateInstance(a.ParameterType, null)).ToArray());
}
static ConcurrentDictionary<Type, ConstructorInfo> _dicInternalGetTypeConstructor0OrFirst = new ConcurrentDictionary<Type, ConstructorInfo>();
static ConstructorInfo InternalGetTypeConstructor0OrFirst(this Type that, bool isThrow = true)
{
var ret = _dicInternalGetTypeConstructor0OrFirst.GetOrAdd(that, tp =>
tp.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null) ??
tp.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault());
if (ret == null && isThrow) throw new ArgumentException($"{that.FullName} has no method to access constructor");
return ret;
}
static ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>> _dicGetPropertiesDictIgnoreCase = new ConcurrentDictionary<Type, Dictionary<string, PropertyInfo>>();
public static Dictionary<string, PropertyInfo> GetPropertiesDictIgnoreCase(this Type that) => that == null ? null : _dicGetPropertiesDictIgnoreCase.GetOrAdd(that, tp =>
{
var props = that.GetProperties().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, PropertyInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var prop in props)
{
if (dict.TryGetValue(prop.Name, out var existsProp))
{
if (existsProp.DeclaringType != prop) dict[prop.Name] = prop;
continue;
}
dict.Add(prop.Name, prop);
}
return dict;
});
static ConcurrentDictionary<Type, Dictionary<string, FieldInfo>> _dicGetFieldsDictIgnoreCase = new ConcurrentDictionary<Type, Dictionary<string, FieldInfo>>();
public static Dictionary<string, FieldInfo> GetFieldsDictIgnoreCase(this Type that) => that == null ? null : _dicGetFieldsDictIgnoreCase.GetOrAdd(that, tp =>
{
var fields = that.GetFields().GroupBy(p => p.DeclaringType).Reverse().SelectMany(p => p); //将基类的属性位置放在前面 #164
var dict = new Dictionary<string, FieldInfo>(StringComparer.CurrentCultureIgnoreCase);
foreach (var field in fields)
{
if (dict.ContainsKey(field.Name)) dict[field.Name] = field;
else dict.Add(field.Name, field);
}
return dict;
});
public static MemberInfo GetPropertyOrFieldIgnoreCase(this Type that, string name)
{
if (GetPropertiesDictIgnoreCase(that).TryGetValue(name, out var prop)) return prop;
if (GetFieldsDictIgnoreCase(that).TryGetValue(name, out var field)) return field;
return null;
}
public static Type GetPropertyOrFieldType(this MemberInfo that)
{
if (that is PropertyInfo prop) return prop.PropertyType;
if (that is FieldInfo field) return field.FieldType;
return null;
}
#endregion
#region 类型转换
internal static string ToInvariantCultureToString(this object obj) => obj is string objstr ? objstr : string.Format(CultureInfo.InvariantCulture, @"{0}", obj);
public static void MapSetListValue(this object[] list, Dictionary<string, Func<object[], object>> valueHandlers)
{
if (list == null) return;
for (int idx = list.Length - 2, c = 0; idx >= 0 && c < 2; idx -= 2)
{
if (valueHandlers.TryGetValue(list[idx]?.ToString(), out var tryFunc))
{
c++;
var value = list[idx + 1] as object[];
if (value != null) list[idx + 1] = tryFunc(value);
}
}
}
public static T MapToClass<T>(this Dictionary<string, object> dict)
{
if (dict == null) return default(T);
var ttype = typeof(T);
var ret = (T)ttype.CreateInstanceGetDefaultValue();
foreach(var kv in dict)
{
var name = kv.Key.Replace("-", "_");
var prop = ttype.GetPropertyOrFieldIgnoreCase(name);
if (prop == null) continue; // throw new ArgumentException($"{typeof(T).DisplayCsharp()} undefined Property {list[a]}");
if (kv.Value == null) continue;
ttype.SetPropertyOrFieldValue(ret, prop.Name, prop.GetPropertyOrFieldType().FromObject(kv.Value));
}
return ret;
}
public static T MapToClass<T>(this object[] list, Encoding encoding)
{
if (list == null) return default(T);
if (list.Length % 2 != 0) throw new ArgumentException(nameof(list));
var ttype = typeof(T);
var ret = (T)ttype.CreateInstanceGetDefaultValue();
for (var a = 0; a < list.Length; a += 2)
{
var name = list[a].ToString().Replace("-", "_");
var prop = ttype.GetPropertyOrFieldIgnoreCase(name);
if (prop == null) continue; // throw new ArgumentException($"{typeof(T).DisplayCsharp()} undefined Property {list[a]}");
if (list[a + 1] == null) continue;
ttype.SetPropertyOrFieldValue(ret, prop.Name, prop.GetPropertyOrFieldType().FromObject(list[a + 1], encoding));
}
return ret;
}
public static Dictionary<string, T> MapToHash<T>(this object[] list, Encoding encoding)
{
if (list == null) return null;
if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even");
var dic = new Dictionary<string, T>();
for (var a = 0; a < list.Length; a += 2)
{
var key = list[a].ToInvariantCultureToString();
if (dic.ContainsKey(key)) continue;
var val = list[a + 1];
if (val == null) dic.Add(key, default(T));
else dic.Add(key, val is T conval ? conval : (T)typeof(T).FromObject(val, encoding));
}
return dic;
}
public static List<KeyValuePair<string, T>> MapToKvList<T>(this object[] list, Encoding encoding)
{
if (list == null) return null;
if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even");
var ret = new List<KeyValuePair<string, T>>();
for (var a = 0; a < list.Length; a += 2)
{
var key = list[a].ToInvariantCultureToString();
var val = list[a + 1];
if (val == null) ret.Add(new KeyValuePair<string, T>(key, default(T)));
else ret.Add(new KeyValuePair<string, T>(key, val is T conval ? conval : (T)typeof(T).FromObject(val, encoding)));
}
return ret;
}
public static List<T> MapToList<T>(this object[] list, Func<object, object, T> selector)
{
if (list == null) return null;
if (list.Length % 2 != 0) throw new ArgumentException($"Array {nameof(list)} length is not even");
var ret = new List<T>();
for (var a = 0; a < list.Length; a += 2)
{
var selval = selector(list[a], list[a + 1]);
if (selval != null) ret.Add(selval);
}
return ret;
}
internal static T ConvertTo<T>(this object value) => (T)typeof(T).FromObject(value);
static ConcurrentDictionary<Type, Func<string, object>> _dicFromObject = new ConcurrentDictionary<Type, Func<string, object>>();
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(string))
{
if (valueIsNull) return null;
if (valueType == typeof(byte[])) return encoding.GetString(value as byte[]);
return value.ToInvariantCultureToString();
}
else if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
var targetElementType = targetType.GetElementType();
if (value is Array valueArr)
{
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
if (value is IList valueList)
{
var sourceArrLen = valueList.Count;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
return target;
}
}
else if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(List<>))
{
var targetElementType = targetType.GetGenericArguments()[0];
if (value is Array valueArr)
{
var sourceArrLen = valueArr.Length;
var target = Activator.CreateInstance(targetType) as IList;
for (var a = 0; a < sourceArrLen; a++) target.Add(targetElementType.FromObject(valueArr.GetValue(a), encoding));
return target;
}
if (value is IList valueList)
{
var sourceArrLen = valueList.Count;
var target = Activator.CreateInstance(targetType) as IList;
for (var a = 0; a < sourceArrLen; a++) target.Add(targetElementType.FromObject(valueList[a], encoding));
return target;
}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
if (valueIsNull) return func(null);
if (valueType == typeof(byte[])) return func(encoding.GetString(value as byte[]));
var valueType2 = valueType.NullableTypeOrThis();
if (valueType2.IsEnum && targetType.IsNumberType()) return func(Convert.ChangeType(value, valueType2.GetEnumUnderlyingType()).ToInvariantCultureToString());
return func(value.ToInvariantCultureToString());
}
#endregion
}
public class RedisServerException : Exception
{
public RedisServerException(string message) : base(message) { }
}
public class RedisResult
{
public object Value { get; internal set; }
protected internal bool IsEnd { get; protected set; }
public RedisMessageType MessageType { get; protected set; }
public bool IsError => this.MessageType == RedisMessageType.SimpleError || this.MessageType == RedisMessageType.BlobError;
internal string SimpleError { get; set; }
public Encoding Encoding { get; internal set; }
internal RedisResult(object value, bool isend, RedisMessageType msgtype)
{
this.IsEnd = isend;
this.MessageType = msgtype;
if (IsError) this.SimpleError = value?.ConvertTo<string>();
else this.Value = value;
}
public RedisResult ThrowOrNothing()
{
if (IsError) throw new RedisServerException(this.SimpleError);
return this;
}
public TValue ThrowOrValue<TValue>(Func<object, TValue> value)
{
if (IsError) throw new RedisServerException(this.SimpleError);
var newval = value(this.Value);
if (newval == null && typeof(TValue).IsArray) newval = (TValue)typeof(TValue).CreateInstanceGetDefaultValue();
this.Value = newval;
return newval;
}
public TValue ThrowOrValue<TValue>(Func<object[], bool, TValue> value)
{
if (IsError) throw new RedisServerException(this.SimpleError);
var newval = value(this.Value as object[] ?? new object[0], false);
if (newval == null && typeof(TValue).IsArray) newval = (TValue)typeof(TValue).CreateInstanceGetDefaultValue();
this.Value = newval;
return newval;
}
public object ThrowOrValue()
{
if (IsError) throw new RedisServerException(this.SimpleError);
return this.Value;
}
public TValue ThrowOrValue<TValue>(bool useDefaultValue = false)
{
if (IsError) throw new RedisServerException(this.SimpleError);
if (useDefaultValue == false)
{
var newval = this.Value.ConvertTo<TValue>();
if (newval == null && typeof(TValue).IsArray) newval = (TValue)typeof(TValue).CreateInstanceGetDefaultValue();
this.Value = newval;
return newval;
}
var defval = default(TValue);
if (typeof(TValue).IsArray) defval = (TValue)typeof(TValue).CreateInstanceGetDefaultValue();
this.Value = defval;
return defval;
}
}
public enum RedisMessageType
{
/// <summary>
/// $11\r\nhelloworld\r\n
/// </summary>
BlobString,
/// <summary>
/// +hello world\r\n
/// </summary>
SimpleString,
/// <summary>
/// =15\r\ntxt:Some string\r\n
/// </summary>
VerbatimString,
/// <summary>
/// -ERR this is the error description\r\n<para></para>
/// The first word in the error is in upper case and describes the error code.
/// </summary>
SimpleError,
/// <summary>
/// !21\r\nSYNTAX invalid syntax\r\n<para></para>
/// The first word in the error is in upper case and describes the error code.
/// </summary>
BlobError,
/// <summary>
/// :1234\r\n
/// </summary>
Number,
/// <summary>
/// (3492890328409238509324850943850943825024385\r\n
/// </summary>
BigNumber,
/// <summary>
/// _\r\n
/// </summary>
Null,
/// <summary>
/// ,1.23\r\n<para></para>
/// ,inf\r\n<para></para>
/// ,-inf\r\n
/// </summary>
Double,
/// <summary>
/// #t\r\n<para></para>
/// #f\r\n
/// </summary>
Boolean,
/// <summary>
/// *3\r\n:1\r\n:2\r\n:3\r\n<para></para>
/// [1, 2, 3]
/// </summary>
Array,
/// <summary>
/// ~5\r\n+orange\r\n+apple\r\n#t\r\n:100\r\n:999\r\n
/// </summary>
Set,
/// <summary>
/// >4\r\n+pubsub\r\n+message\r\n+somechannel\r\n+this is the message\r\n
/// </summary>
Push,
/// <summary>
/// %2\r\n+first\r\n:1\r\n+second\r\n:2\r\n<para></para>
/// { "first": 1, "second": 2 }
/// </summary>
Map,
/// <summary>
/// |2\r\n+first\r\n:1\r\n+second\r\n:2\r\n<para></para>
/// { "first": 1, "second": 2 }
/// </summary>
Attribute,
}
public enum RedisProtocol { RESP2, RESP3 }
} |
2881099/FreeRedis | 12,627 | src/FreeRedis/Internal/RedisClientPool.cs | using FreeRedis.Internal.ObjectPool;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
namespace FreeRedis.Internal
{
public class RedisClientPool : ObjectPool<RedisClient>, IDisposable
{
public RedisClientPool(ConnectionStringBuilder connectionString, RedisClient topOwner) : base(null)
{
_policy = new RedisClientPoolPolicy
{
_pool = this
};
_policy.Connected += (s, o) =>
{
var cli = s as RedisClient;
var rds = cli.Adapter.GetRedisSocket(null);
var adapter = cli.Adapter as RedisClient.SingleInsideAdapter;
rds.Socket.ReceiveTimeout = (int)connectionString.ReceiveTimeout.TotalMilliseconds;
rds.Socket.SendTimeout = (int)connectionString.SendTimeout.TotalMilliseconds;
rds.Encoding = connectionString.Encoding;
var isIgnoreAop = rds.LastCommand.IsIgnoreAop;
var cmds = new List<CommandPacket>();
if (connectionString.Protocol == RedisProtocol.RESP3)
{
//未开启 ACL 的情况
if (string.IsNullOrWhiteSpace(connectionString.User) && !string.IsNullOrWhiteSpace(connectionString.Password))
cmds.Add("AUTH".SubCommand(null)
.Input(connectionString.Password)
.OnData(rt =>
{
if (rt.IsError && rt.SimpleError != "ERR Client sent AUTH, but no password is set")
rt.ThrowOrNothing();
rds.Protocol = RedisProtocol.RESP3;
}));
cmds.Add("HELLO"
.Input(3)
.InputIf(!string.IsNullOrWhiteSpace(connectionString.User) && !string.IsNullOrWhiteSpace(connectionString.Password), "AUTH", connectionString.User, connectionString.Password)
.InputIf(!string.IsNullOrWhiteSpace(connectionString.ClientName), "SETNAME", connectionString.ClientName)
.OnData(rt =>
{
rt.ThrowOrNothing();
rds.Protocol = RedisProtocol.RESP3;
}));
}
else if (!string.IsNullOrEmpty(connectionString.User) && !string.IsNullOrEmpty(connectionString.Password))
cmds.Add("AUTH".SubCommand(null)
.InputIf(!string.IsNullOrWhiteSpace(connectionString.User), connectionString.User)
.Input(connectionString.Password)
.OnData(rt =>
{
rt.ThrowOrNothing();
}));
else if (!string.IsNullOrEmpty(connectionString.Password))
cmds.Add("AUTH".SubCommand(null)
.Input(connectionString.Password)
.OnData(rt =>
{
if (rt.IsError && rt.SimpleError != "ERR Client sent AUTH, but no password is set")
rt.ThrowOrNothing();
}));
if (connectionString.Database > 0)
cmds.Add("SELECT".Input(connectionString.Database)
.OnData(rt =>
{
if (rt.IsError)
{
if (rt.SimpleError == "ERR SELECT is not allowed in cluster mode" ||
rt.SimpleError == "ERR invalid database index.") //Garnet
connectionString.Database = 0;
else
rt.ThrowOrNothing();
}
(rds as IRedisSocketModify).SetDatabase(connectionString.Database);
}));
if (!string.IsNullOrEmpty(connectionString.ClientName) && connectionString.Protocol == RedisProtocol.RESP2)
cmds.Add("CLIENT".SubCommand("SETNAME").InputRaw(connectionString.ClientName)
.OnData(rt =>
{
rt.ThrowOrNothing();
}));
cmds.Add("CLIENT".SubCommand("ID")
.OnData(rt =>
{
if (rt.IsError) return; //ERR Syntax error, try CLIENT (LIST | KILL | GETNAME | SETNAME | PAUSE | REPLY)
(rds as IRedisSocketModify).SetClientId(rt.ThrowOrValue<long>());
}));
cmds.ForEach(cmd =>
{
topOwner.LogCallCtrl(cmd, () => 1, true, false); // aop before
});
using (var ms = new MemoryStream()) {
var writer = new RespHelper.Resp3Writer(ms, rds.Encoding, RedisProtocol.RESP2);
cmds.ForEach(cmd =>
{
cmd.WriteTarget = $"{rds.Host}/{rds.Database}";
writer.WriteCommand(cmd);
});
ms.Position = 0;
ms.CopyTo(rds.Stream);
ms.Close();
ms.Dispose();
}
cmds.ForEach(cmd =>
{
topOwner.LogCallCtrl(cmd, () =>
{
var rt = rds.Read(cmd);
return rt.Value;
}, false, true); //aop after
});
topOwner?.OnConnected(TopOwner, new ConnectedEventArgs(connectionString.Host, this, cli));
if (isIgnoreAop == false)
topOwner?.OnNotice(TopOwner, new NoticeEventArgs(NoticeType.Info, null, $"{connectionString.Host.PadRight(21)} > Connected, ClientId: {rds.ClientId}, Database: {rds.Database}, Pool: {_freeObjects.Count}/{_allObjects.Count}", cli));
};
this.Policy = _policy;
this.TopOwner = topOwner;
_policy._connectionStringBuilder = connectionString;
if (connectionString.MinPoolSize > 0)
RedisClientPoolPolicy.PrevReheatConnectionPool(this, connectionString.MinPoolSize);
}
internal bool CheckAvailable() => base.LiveCheckAvailable();
internal RedisClientPoolPolicy _policy;
public string Key => _policy.Key;
public string Prefix => _policy._connectionStringBuilder.Prefix;
internal RedisClient TopOwner;
}
public class RedisClientPoolPolicy : IPolicy<RedisClient>
{
internal RedisClientPool _pool;
internal ConnectionStringBuilder _connectionStringBuilder = new ConnectionStringBuilder();
internal string Key => $"{_connectionStringBuilder.Host}/{_connectionStringBuilder.Database}";
public event EventHandler Connected;
public string Name { get => Key; set => throw new NotSupportedException(); }
public int PoolSize { get => _connectionStringBuilder.MaxPoolSize; set => _connectionStringBuilder.MaxPoolSize = value; }
public TimeSpan IdleTimeout { get => _connectionStringBuilder.IdleTimeout; set => _connectionStringBuilder.IdleTimeout = value; }
public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10);
public int AsyncGetCapacity { get; set; } = 100000;
public bool IsThrowGetTimeoutException { get; set; } = true;
public bool IsAutoDisposeWithSystem { get => _connectionStringBuilder.ExitAutoDisposePool; set => _connectionStringBuilder.ExitAutoDisposePool = value; }
public TimeSpan AvailableCheckInterval { get; set; } = TimeSpan.FromSeconds(3);
public TimeSpan ToleranceWindow { get; set; } = TimeSpan.FromSeconds(5);
public TimeSpan ToleranceCheckInterval { get; set; } = TimeSpan.FromSeconds(1);
public bool OnCheckAvailable(Object<RedisClient> obj)
{
obj.ResetValue();
CommandPacket cmd = "PING";
cmd.IsIgnoreAop = true;
return obj.Value.Call(cmd) as string == "PONG";
}
public RedisClient OnCreate()
{
return new RedisClient(_pool.TopOwner, _connectionStringBuilder.Host,
_connectionStringBuilder.Ssl, _connectionStringBuilder.CertificateValidation, _connectionStringBuilder.CertificateSelection,
_connectionStringBuilder.ConnectTimeout,
_connectionStringBuilder.ReceiveTimeout, _connectionStringBuilder.SendTimeout,
cli => Connected(cli, new EventArgs()),
cli =>
{
_pool.TopOwner?.OnDisconnected(_pool.TopOwner, new DisconnectedEventArgs(_connectionStringBuilder.Host, _pool, cli));
});
}
public void OnDestroy(RedisClient obj)
{
if (obj != null)
{
//if (obj.IsConnected) try { obj.Quit(); } catch { } 此行会导致,服务器主动断开后,执行该命令超时停留10-20秒
try { obj.Dispose(); } catch { }
}
}
public void OnReturn(Object<RedisClient> obj) { }
public void OnGet(Object<RedisClient> obj)
{
if (_pool.IsAvailable)
{
if (DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 || obj.Value.Adapter.GetRedisSocket(null).IsConnected == false)
{
try
{
CommandPacket cmd = "PING";
cmd.IsIgnoreAop = true;
obj.Value.Call(cmd);
}
catch
{
obj.ResetValue();
}
}
}
}
#if !NET40
async public Task OnGetAsync(Object<RedisClient> obj)
{
if (_pool.IsAvailable)
{
if (DateTime.Now.Subtract(obj.LastReturnTime).TotalSeconds > 60 || obj.Value.Adapter.GetRedisSocket(null).IsConnected == false)
{
try
{
CommandPacket cmd = "PING";
cmd.IsIgnoreAop = true;
await obj.Value.CallAsync(cmd);
}
catch
{
obj.ResetValue();
}
}
}
}
#endif
public void OnGetTimeout() { }
public void OnAvailable() { }
public void OnUnavailable()
{
_pool.TopOwner?.OnUnavailable(_pool.TopOwner, new UnavailableEventArgs(_connectionStringBuilder.Host, _pool));
_pool.TopOwner?.OnNotice(_pool.TopOwner, new NoticeEventArgs(NoticeType.Info, null, $"{_connectionStringBuilder.Host.PadRight(21)} > Unavailable", null));
}
public static void PrevReheatConnectionPool(ObjectPool<RedisClient> pool, int minPoolSize)
{
if (minPoolSize <= 0) minPoolSize = Math.Min(5, pool.Policy.PoolSize);
if (minPoolSize > pool.Policy.PoolSize) minPoolSize = pool.Policy.PoolSize;
var initTestOk = true;
var initStartTime = DateTime.Now;
var initConns = new ConcurrentBag<Object<RedisClient>>();
try
{
var conn = pool.Get();
initConns.Add(conn);
CommandPacket cmd = "PING";
cmd.IsIgnoreAop = true;
conn.Value.Call(cmd);
}
catch (Exception ex)
{
initTestOk = false; //预热一次失败,后面将不进行
pool.SetUnavailable(ex, DateTime.Now);
}
for (var a = 1; initTestOk && a < minPoolSize; a += 10)
{
if (initStartTime.Subtract(DateTime.Now).TotalSeconds > 3) break; //预热耗时超过3秒,退出
var b = Math.Min(minPoolSize - a, 10); //每10个预热
var initTasks = new Task[b];
for (var c = 0; c < b; c++)
{
initTasks[c] = TaskEx.Run(() =>
{
try
{
var conn = pool.Get();
initConns.Add(conn);
}
catch
{
initTestOk = false; //有失败,下一组退出预热
}
});
}
Task.WaitAll(initTasks);
}
while (initConns.TryTake(out var conn)) pool.Return(conn);
}
}
}
|
2881099/FreeRedis | 1,579 | src/FreeRedis/Internal/IRedisSocket.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace FreeRedis.Internal
{
public interface IRedisSocket : IDisposable
{
string Host { get; }
bool Ssl { get; }
TimeSpan ConnectTimeout { get; set; }
TimeSpan ReceiveTimeout { get; set; }
TimeSpan SendTimeout { get; set; }
Socket Socket { get; }
Stream Stream { get; }
bool IsConnected { get; }
event EventHandler<EventArgs> Connected;
event EventHandler<EventArgs> Disconnected;
RedisProtocol Protocol { get; set; }
Encoding Encoding { get; set; }
CommandPacket LastCommand { get; }
void Write(CommandPacket cmd);
RedisResult Read(CommandPacket cmd);
void ReadChunk(Stream destination, int bufferSize = 1024);
#if isasync
Task WriteAsync(CommandPacket cmd);
Task<RedisResult> ReadAsync(CommandPacket cmd);
Task ReadChunkAsync(Stream destination, int bufferSize = 1024);
#endif
ClientReplyType ClientReply { get; }
/// <summary>
/// Redis-server ClientID
/// </summary>
long ClientId { get; }
/// <summary>
/// FreeRedis 本地专用 ID
/// </summary>
Guid ClientId2 { get; }
int Database { get; }
void Connect();
void ResetHost(string host);
void ReleaseSocket();
}
}
|
2881099/FreeRedis | 9,989 | src/FreeRedis/Internal/RespHelperAsync.cs | #if isasync
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RespHelper
{
partial class Resp3Reader
{
async public Task ReadBlobStringChunkAsync(Stream destination, int bufferSize)
{
char c = (char)_stream.ReadByte();
switch (c)
{
case '$':
case '=':
case '!': await ReadBlobStringAsync(c, null, destination, bufferSize); break;
default: throw new ProtocolViolationException($"Expecting fail MessageType '{c}'");
}
}
async Task<object> ReadBlobStringAsync(char msgtype, Encoding encoding, Stream destination, int bufferSize)
{
var clob = await ReadClobAsync();
if (encoding == null) return clob;
if (clob == null) return null;
return encoding.GetString(clob);
async Task<byte[]> ReadClobAsync()
{
MemoryStream ms = null;
try
{
if (destination == null) destination = ms = new MemoryStream();
var lenstr = ReadLine(null);
if (int.TryParse(lenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var len))
{
if (len < 0) return null;
if (len > 0) await ReadAsync(destination, len, bufferSize);
ReadLine(null);
if (len == 0) return new byte[0];
return ms?.ToArray();
}
if (lenstr == "?")
{
while (true)
{
char c = (char)_stream.ReadByte();
if (c != ';') throw new ProtocolViolationException($"Expecting fail Streamed strings ';', got '{c}'");
var clenstr = ReadLine(null);
if (int.TryParse(clenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var clen))
{
if (clen == 0) break;
if (clen > 0)
{
await ReadAsync(destination, clen, bufferSize);
ReadLine(null);
continue;
}
}
throw new ProtocolViolationException($"Expecting fail Streamed strings ';0', got ';{clenstr}'");
}
return ms?.ToArray();
}
throw new ProtocolViolationException($"Expecting fail Blob string '{msgtype}0', got '{msgtype}{lenstr}'");
}
finally
{
ms?.Close();
ms?.Dispose();
}
}
}
async Task<object[]> ReadArrayAsync(char msgtype, Encoding encoding)
{
var lenstr = ReadLine(null);
if (int.TryParse(lenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var len))
{
if (len < 0) return null;
var arr = new object[len];
for (var a = 0; a < len; a++)
arr[a] = (await ReadObjectAsync(encoding)).Value;
if (len == 1 && arr[0] == null) return new object[0];
return arr;
}
if (lenstr == "?")
{
var arr = new List<object>();
while (true)
{
var ro = await ReadObjectAsync(encoding);
if (ro.IsEnd) break;
arr.Add(ro.Value);
}
return arr.ToArray();
}
throw new ProtocolViolationException($"Expecting fail Array '{msgtype}3', got '{msgtype}{lenstr}'");
}
async Task<object[]> ReadMapAsync(char msgtype, Encoding encoding)
{
var lenstr = ReadLine(null);
if (int.TryParse(lenstr, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var len))
{
if (len < 0) return null;
var arr = new object[len * 2];
for (var a = 0; a < len; a++)
{
arr[a * 2] = (await ReadObjectAsync(encoding)).Value;
arr[a * 2 + 1] = (await ReadObjectAsync(encoding)).Value;
}
return arr;
}
if (lenstr == "?")
{
var arr = new List<object>();
while (true)
{
var rokey = await ReadObjectAsync(encoding);
if (rokey.IsEnd) break;
var roval = await ReadObjectAsync(encoding);
arr.Add(rokey.Value);
arr.Add(roval.Value);
}
return arr.ToArray();
}
throw new ProtocolViolationException($"Expecting fail Map '{msgtype}3', got '{msgtype}{lenstr}'");
}
async public Task<RedisResult> ReadObjectAsync(Encoding encoding)
{
while (true)
{
var b = _stream.ReadByte();
var c = (char)b;
//debugger++;
//if (debugger > 10000 && debugger % 10 == 0)
// throw new ProtocolViolationException($"Expecting fail MessageType '{b},{string.Join(",", ReadAll())}'");
switch (c)
{
case '$': return new RedisResult(await ReadBlobStringAsync(c, encoding, null, 1024), false, RedisMessageType.BlobString);
case '+': return new RedisResult(ReadSimpleString(), false, RedisMessageType.SimpleString);
case '=': return new RedisResult(await ReadBlobStringAsync(c, encoding, null, 1024), false, RedisMessageType.VerbatimString);
case '-':
{
var simpleError = ReadSimpleString();
if (simpleError == "NOAUTH Authentication required.")
throw new ProtocolViolationException(simpleError);
return new RedisResult(simpleError, false, RedisMessageType.SimpleError);
}
case '!': return new RedisResult(await ReadBlobStringAsync(c, encoding, null, 1024), false, RedisMessageType.BlobError);
case ':': return new RedisResult(ReadNumber(c), false, RedisMessageType.Number);
case '(': return new RedisResult(ReadBigNumber(c), false, RedisMessageType.BigNumber);
case '_': ReadLine(null); return new RedisResult(null, false, RedisMessageType.Null);
case ',': return new RedisResult(ReadDouble(c), false, RedisMessageType.Double);
case '#': return new RedisResult(ReadBoolean(c), false, RedisMessageType.Boolean);
case '*': return new RedisResult(await ReadArrayAsync(c, encoding), false, RedisMessageType.Array);
case '~': return new RedisResult(await ReadArrayAsync(c, encoding), false, RedisMessageType.Set);
case '>': return new RedisResult(await ReadArrayAsync(c, encoding), false, RedisMessageType.Push);
case '%': return new RedisResult(await ReadMapAsync(c, encoding), false, RedisMessageType.Map);
case '|': return new RedisResult(await ReadMapAsync(c, encoding), false, RedisMessageType.Attribute);
case '.': ReadLine(null); return new RedisResult(null, true, RedisMessageType.SimpleString); //无类型
case ' ': continue;
default:
if (b == -1) return new RedisResult(null, true, RedisMessageType.Null);
//if (b == -1) return new RedisResult(null, true, RedisMessageType.Null);
var allBytes = DebugReadAll();
throw new ProtocolViolationException($"Expecting fail MessageType '{b},{string.Join(",", allBytes)}'");
}
}
}
async Task ReadAsync(Stream outStream, int len, int bufferSize = 1024)
{
if (len <= 0) return;
var buffer = new byte[Math.Min(bufferSize, len)];
var bufferLength = buffer.Length;
while (true)
{
var readed = await _stream.ReadAsync(buffer, 0, bufferLength);
if (readed <= 0) throw new ProtocolViolationException($"Expecting fail Read surplus length: {len}");
if (readed > 0) await outStream.WriteAsync(buffer, 0, readed);
len = len - readed;
if (len <= 0) break;
if (len < buffer.Length) bufferLength = len;
}
}
}
}
}
#endif |
2881099/FreeRedis | 12,256 | src/FreeRedis/RedisClient/Server.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace FreeRedis
{
partial class RedisClient
{
public string[] AclCat(string categoryname = null) => Call("ACL"
.SubCommand("CAT")
.InputIf(string.IsNullOrWhiteSpace(categoryname) == false, categoryname), rt => rt.ThrowOrValue<string[]>());
public long AclDelUser(params string[] username) => Call("ACL".SubCommand("DELUSER").Input(username), rt => rt.ThrowOrValue<long>());
public string AclGenPass(int bits = 0) => Call("ACL"
.SubCommand("GENPASS")
.InputIf(bits > 0, bits), rt => rt.ThrowOrValue<string>());
public AclGetUserResult AclGetUser(string username = "default") => Call("ACL".SubCommand("GETUSER").InputRaw(username), rt => rt.ThrowOrValue((a, _) =>
{
for (var x = 0; x < a.Length; x += 2)
{
switch (a[x])
{
case "flags":
case "passwords":
a[x + 1] = a[x + 1]?.ConvertTo<string[]>();
break;
case "selectors":
var selectors = a[x + 1] as object[];
if (selectors != null)
{
var selectorResults = new AclGetUserResult.SelectorResult[selectors.Length];
for (var y = 0; y < selectors.Length; y++)
selectorResults[y] = (selectors[y] as object[])?.MapToClass<AclGetUserResult.SelectorResult>(rt.Encoding);
a[x + 1] = selectorResults;
}
break;
}
}
return a.MapToClass<AclGetUserResult>(rt.Encoding);
}));
public string[] AclList() => Call("ACL".SubCommand("LIST"), rt => rt.ThrowOrValue<string[]>());
public void AclLoad() => Call("ACL".SubCommand("LOAD"), rt => rt.ThrowOrValue());
public LogResult[] AclLog(long count = 0) => Call("ACL"
.SubCommand("LOG")
.InputIf(count > 0, count), rt => rt
.ThrowOrValue((a, _) => a.Select(x => x.ConvertTo<object[]>().MapToClass<LogResult>(rt.Encoding)).ToArray()));
public void AclSave() => Call("ACL".SubCommand("SAVE"), rt => rt.ThrowOrValue());
public void AclSetUser(string username, params string[] rule) => Call("ACL".SubCommand("SETUSER").InputRaw(username).Input(rule), rt => rt.ThrowOrValue());
public string[] AclUsers() => Call("ACL".SubCommand("USERS"), rt => rt.ThrowOrValue<string[]>());
public string AclWhoami() => Call("ACL".SubCommand("WHOAMI"), rt => rt.ThrowOrValue<string>());
public string BgRewriteAof() => Call("BGREWRITEAOF", rt => rt.ThrowOrValue<string>());
public string BgSave(string schedule = null) => Call("BGSAVE".SubCommand(null).InputIf(string.IsNullOrEmpty(schedule) == false, schedule), rt => rt.ThrowOrValue<string>());
public object[] Command() => Call("COMMAND", rt => rt.ThrowOrValue((a, _) => a));
public long CommandCount() => Call("COMMAND".SubCommand("COUNT"), rt => rt.ThrowOrValue<long>());
public string[] CommandGetKeys(params string[] command) => Call("COMMAND".SubCommand("GETKEYS").Input(command), rt => rt.ThrowOrValue<string[]>());
public object[] CommandInfo(params string[] command) => Call("COMMAND".SubCommand("INFO").Input(command), rt => rt.ThrowOrValue<object[]>());
public Dictionary<string, string> ConfigGet(string parameter) => Call("CONFIG".SubCommand("GET").InputRaw(parameter), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
public void ConfigResetStat() => Call("CONFIG".SubCommand("RESETSTAT"), rt => rt.ThrowOrValue());
public void ConfigRewrite() => Call("CONFIG".SubCommand("REWRITE"), rt => rt.ThrowOrValue());
public void ConfigSet<T>(string parameter, T value) => Call("CONFIG".SubCommand("SET").InputRaw(parameter).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue());
public long DbSize() => Call("DBSIZE", rt => rt.ThrowOrValue<long>());
public string DebugObject(string key) => Call("DEBUG".SubCommand("OBJECT").InputKey(key), rt => rt.ThrowOrValue<string>());
public void FlushAll(bool isasync = false) => Call("FLUSHALL".SubCommand(null).InputIf(isasync, "ASYNC"), rt => rt.ThrowOrValue());
public void FlushDb(bool isasync = false) => Call("FLUSHDB".SubCommand(null).InputIf(isasync, "ASYNC"), rt => rt.ThrowOrValue());
public string Info(string section = null) => Call("INFO".SubCommand(null).InputIf(!string.IsNullOrWhiteSpace(section), section), rt => rt.ThrowOrValue<string>());
public DateTime LastSave() => Call("LASTSAVE", rt => rt.ThrowOrValue(a => _epoch.AddSeconds(a.ConvertTo<long>()).ToLocalTime()));
public string LatencyDoctor() => Call("LATENCY".SubCommand("DOCTOR"), rt => rt.ThrowOrValue<string>());
//public string LatencyGraph(string @event) => Call("LATENCY".SubCommand("GRAPH").InputRaw(@event), rt => rt.ThrowOrValue<string>());
//public object LatencyHistory(string @event) => Call("LATENCY".SubCommand("HISTORY").InputRaw(@event), rt => rt.ThrowOrValue());
//public object LatencyLatest() => Call("LATENCY".SubCommand("LATEST"), rt => rt.ThrowOrValue());
//public long LatencyReset(string @event) => Call("LATENCY".SubCommand("RESET").InputRaw(@event), rt => rt.ThrowOrValue<long>());
//public string Lolwut(string version) => Call("LOLWUT".SubCommand(null).InputIf(string.IsNullOrWhiteSpace(version) == false, "VERSION", version), rt => rt.ThrowOrValue<string>());
public string MemoryDoctor() => Call("MEMORY".SubCommand("DOCTOR"), rt => rt.ThrowOrValue<string>());
public string MemoryMallocStats() => Call("MEMORY".SubCommand("MALLOC-STATS"), rt => rt.ThrowOrValue<string>());
public void MemoryPurge() => Call("MEMORY".SubCommand("PURGE"), rt => rt.ThrowOrValue());
public Dictionary<string, object> MemoryStats() => Call("MEMORY".SubCommand("STATS"), rt => rt.ThrowOrValue((a, _) => a.MapToHash<object>(rt.Encoding)));
public long MemoryUsage(string key, long count = 0) => Call("MEMORY"
.SubCommand("USAGE")
.InputKey(key)
.InputIf(count > 0, "SAMPLES", count), rt => rt.ThrowOrValue<long>());
//public string[][] ModuleList() => Call("MODULE".SubCommand("LIST"), rt => rt.ThrowOrValue<string[][]>());
//public string ModuleLoad(string path, params string[] args) => Call("MODULE".SubCommand("LOAD").InputRaw(path).InputIf(args?.Any() == true, args), rt => rt.ThrowOrValue<string>());
//public string ModuleUnload(string name) => Call("MODULE".SubCommand("UNLOAD").InputRaw(name), rt => rt.ThrowOrValue<string>());
//public RedisClient Monitor(Action<object> onData)
//{
// IRedisSocket rds = null;
// rds = CallReadWhile(onData, () => rds.IsConnected, "MONITOR");
// return rds.Client;
//}
//public void PSync(string replicationid, string offset, Action<string> onData) => SendCommandListen(onData, "PSYNC", replicationid, offset);
public void ReplicaOf(string host, int port) => Call("REPLICAOF".Input(host, port), rt => rt.ThrowOrValue());
public RoleResult Role() => Call("ROLE", rt => rt.ThrowOrValueToRole());
public void Save() => Call("SAVE", rt => rt.ThrowOrValue());
//public void Shutdown(bool save) => Call("SHUTDOWN".Input(save ? "SAVE" : "NOSAVE"), rt => rt.ThrowOrValue());
public void SlaveOf(string host, int port) => Call("SLAVEOF".Input(host, port), rt => rt.ThrowOrValue());
public object SlowLog(string subcommand, params string[] argument) => Call("SLOWLOG".SubCommand(subcommand).Input(argument), rt => rt.ThrowOrValue());
public void SwapDb(int index1, int index2) => Call("SWAPDB".Input(index1, index2), rt => rt.ThrowOrValue());
//public void Sync(Action<string> onData) => SendCommandListen(onData, "SYNC");
public DateTime Time() => Call("TIME", rt => rt.ThrowOrValue((a, _) => _epoch.AddSeconds(a[0].ConvertTo<long>()).AddTicks(a[1].ConvertTo<long>() * 10).ToLocalTime()));
static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
#region Model
static partial class RedisResultThrowOrValueExtensions
{
public static RoleResult ThrowOrValueToRole(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a?.Any() != true) return null;
var role = new RoleResult { role = a[0].ConvertTo<RoleType>() };
switch (role.role)
{
case RoleType.Master:
role.data = new RoleResult.MasterInfo
{
_replication_offset = a[1].ConvertTo<long>(),
_slaves = (a[2] as object[])?.Select(x =>
{
var xs = x as object[];
return new RoleResult.MasterInfo.Slave
{
ip = xs[0].ConvertTo<string>(),
port = xs[1].ConvertTo<int>(),
slave_offset = xs[2].ConvertTo<long>()
};
}).ToArray()
};
break;
case RoleType.Slave:
role.data = new RoleResult.Slave
{
master_ip = a[1].ConvertTo<string>(),
master_port = a[2].ConvertTo<int>(),
replication_state = a[3].ConvertTo<string>(),
data_received = a[4].ConvertTo<long>()
};
break;
case RoleType.Sentinel:
role.data = a[1].ConvertTo<string[]>();
break;
}
return role;
});
}
//1) "master"
//2) (integer) 15891
//3) 1) 1) "127.0.0.1"
// 2) "6380"
// 3) "15617"
//1) "slave"
//2) "127.0.0.1"
//3) (integer) 6381
//4) "connected"
//5) (integer) 74933
//1) "sentinel"
//2) 1) "mymaster"
public class RoleResult
{
public RoleType role;
public object data;
public class MasterInfo
{
public long _replication_offset;
public Slave[] _slaves;
public override string ToString() => $"{_replication_offset} {string.Join("], [", _slaves.Select(a => a?.ToString()))}";
public class Slave
{
public string ip;
public int port;
public long slave_offset;
public override string ToString() => $"{ip}:{port} {slave_offset}";
}
}
public class Slave
{
public string master_ip;
public int master_port;
public string replication_state;
public long data_received;
public override string ToString() => $"{master_ip}:{master_port} {replication_state} {data_received}";
}
public override string ToString() => $"{role}, {data}";
}
public class AclGetUserResult
{
public string[] flags;
public string[] passwords;
public string commands;
public string keys;
public string channels;
public SelectorResult[] selectors;
public class SelectorResult
{
public string commands;
public string keys;
public string channels;
}
}
public class LogResult
{
public long count;
public string reason;
public string context;
public string @object;
public string username;
public decimal age_seconds;
public string client_info;
}
#endregion
}
|
2881099/FreeRedis | 2,819 | src/FreeRedis/RedisClient/SPubSub.cs | //using FreeRedis.Internal;
//using System;
//using System.Collections.Generic;
//using System.Collections.Concurrent;
//using System.Linq;
//using System.Threading;
//using System.Threading.Tasks;
//namespace FreeRedis
//{
// partial class RedisClient
// {
//#if isasync
// #region async (copy from sync)
// /// <summary>
// /// redis 7.0 shard pub/sub
// /// </summary>
// public Task<long> SPublishAsync(string shardchannel, string message) => CallAsync("SPUBLISH".InputKey(shardchannel).Input(message), rt => rt.ThrowOrValue<long>());
// public Task<string[]> PubSubShardChannelsAsync(string pattern = "*") => CallAsync("PUBSUB".SubCommand("SHARDCHANNELS").Input(pattern), rt => rt.ThrowOrValue<string[]>());
// public Task<long> PubSubShardNumSubAsync(string channel) => CallAsync("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channel), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).FirstOrDefault()));
// public Task<long[]> PubSubShardNumSubAsync(string[] channels) => CallAsync("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channels), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).ToArray()));
// #endregion
//#endif
// /// <summary>
// /// redis 7.0 shard pub/sub
// /// </summary>
// public long SPublish(string shardchannel, string message) => Call("SPUBLISH".InputKey(shardchannel).Input(message), rt => rt.ThrowOrValue<long>());
// public string[] PubSubShardChannels(string pattern = "*") => Call("PUBSUB".SubCommand("SHARDCHANNELS").Input(pattern), rt => rt.ThrowOrValue<string[]>());
// public long PubSubShardNumSub(string channel) => Call("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channel), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).FirstOrDefault()));
// public long[] PubSubShardNumSub(string[] channels) => Call("PUBSUB".SubCommand("SHARDNUMSUB").InputKey(channels), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).ToArray()));
// /// <summary>
// /// redis 7.0 shard pub/sub
// /// </summary>
// public IDisposable SSubscribe(string shardchannel, Action<string, object> handler)
// {
// if (string.IsNullOrEmpty(shardchannel)) throw new ArgumentNullException(nameof(shardchannel));
// if (handler == null) throw new ArgumentNullException(nameof(handler));
// return _pubsub.Subscribe(false, true, new[] { shardchannel }, (p, k, d) => handler(k, d));
// }
// /// <summary>
// /// redis 7.0 shard pub/sub
// /// </summary>
// public void SUnSubscribe(string shardchannel) => _pubsub.UnSubscribe(false, true, new[] { shardchannel });
// }
//} |
2881099/FreeRedis | 69,924 | src/FreeRedis/RedisClient/Keys.cs | using FreeRedis.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
/// <summary>
/// DEL command (An Asynchronous Version) <br /><br />
/// <br />
/// Removes the specified keys. A key is ignored if it does not exist.<br /><br />
/// <br />
/// 移除指定的键。如果键不存在,则忽略之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/del <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys that were removed.</returns>
public Task<long> DelAsync(params string[] keys) => CallAsync("DEL".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DUMP command (An Asynchronous Version) <br /><br />
/// <br />
/// Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command.<br /><br />
/// <br />
/// 以 Redis 特有格式序列化指定的键值,并返回给用户。可结合 RESTORE 命令将序列化的结果重新写回 Redis。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/dump <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The serialized value.</returns>
public Task<byte[]> DumpAsync(string key) => CallAsync("DUMP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue<byte[]>());
/// <summary>
/// EXISTS command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns if key exists.<br /><br />
/// <br />
/// 返回键是否存在。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/exists <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Specifically: True if the key exists. False if the key does not exist.</returns>
public Task<bool> ExistsAsync(string key) => CallAsync("EXISTS".InputKey(key), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// EXISTS command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns if key exists.<br /><br />
/// <br />
/// 返回键是否存在。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/exists <br />
/// Available since 3.0.3.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys existing among the ones specified as arguments. Keys mentioned multiple times and existing are counted multiple times.</returns>
public Task<long> ExistsAsync(string[] keys) => CallAsync("EXISTS".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// EXPIRE command (An Asynchronous Version) <br /><br />
/// <br />
/// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
/// <br />
/// 设置键的超时时间。到期后,键将被自动删除。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expire <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="seconds">Expires time (seconds)</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public Task<bool> ExpireAsync(string key, int seconds) => CallAsync("EXPIRE".InputKey(key, seconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// EXPIRE command (An Asynchronous Version) <br /><br />
/// <br />
/// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
/// <br />
/// 设置键的超时时间。到期后,键将被自动删除。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expire <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="expire">Expires TimeSpan</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public Task<bool> ExpireAsync(string key, TimeSpan expire) => CallAsync("EXPIRE".InputKey(key, (long)expire.TotalSeconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// EXPIREAT command (An Asynchronous Version) <br /><br />
/// <br />
/// EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970). A timestamp in the past will delete the key immediately.<br /><br />
/// <br />
/// EXPIREAT 具有与 EXPIRE 相同的作用和语义,但是它没有指定表示 TTL(生存时间)的秒数,而是使用了绝对的 Unix 时间戳(自1970年1月1日以来的秒数)。时间戳一旦过期就会被删除。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expireat <br />
/// Available since 1.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="timestamp">UNIX Timestamp</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public Task<bool> ExpireAtAsync(string key, DateTime timestamp) => CallAsync("EXPIREAT".InputKey(key, (long) timestamp.ToUniversalTime().Subtract(_epoch).TotalSeconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// KEYS command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns all keys matching pattern.<br /><br />
/// <br />
/// 返回所有与模式匹配的键。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/keys <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="pattern">Pattern</param>
/// <returns>List of keys matching pattern.</returns>
public Task<string[]> KeysAsync(string pattern) => CallAsync("KEYS".Input(pattern), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// MIGRATE command (An Asynchronous Version) <br /><br />
/// <br />
/// Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance and is guaranteed to exist in the target instance.<br /><br />
/// <br />
/// 原子地将键从 Redis 源实例转移到目标实例。转移成功后,Key 将从源实例中删除,并确保保存在目标实例之中。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/migrate <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="host">Destination Instance's Host</param>
/// <param name="port">Destination Instance's Port</param>
/// <param name="key">Key</param>
/// <param name="destinationDb">Destination Instance's Database</param>
/// <param name="timeoutMilliseconds">Timeout milliseconds</param>
/// <param name="copy">Do not remove the key from the local instance. Available since 3.0.0. </param>
/// <param name="replace">Replace existing key on the remote instance. Available since 3.0.0. </param>
/// <param name="authPassword">Authenticate with the given password to the remote instance. Available since 4.0.7. </param>
/// <param name="auth2Username">Authenticate with the given username (Redis 6 or greater ACL auth style).</param>
/// <param name="auth2Password">Authenticate with the given password (Redis 6 or greater ACL auth style).</param>
/// <param name="keys">If the key argument is an empty string, the command will instead migrate all the keys that follow the KEYS option (see the above section for more info). Available since 3.0.6. </param>
public Task MigrateAsync(string host, int port, string key, int destinationDb, long timeoutMilliseconds, bool copy, bool replace, string authPassword, string auth2Username, string auth2Password, string[] keys) => CallAsync("MIGRATE"
.Input(host, port)
.InputKey(key ?? "")
.Input(destinationDb, timeoutMilliseconds)
.InputIf(copy, "COPY")
.InputIf(replace, "REPLACE")
.InputIf(!string.IsNullOrWhiteSpace(authPassword), "AUTH", authPassword)
.InputIf(!string.IsNullOrWhiteSpace(auth2Username) && !string.IsNullOrWhiteSpace(auth2Password), "AUTH2", auth2Username, auth2Password)
.InputKey(keys), rt => rt.ThrowOrValue<string>());
/// <summary>
/// MOVE command (An Asynchronous Version) <br /><br />
/// <br />
/// Move key from the currently selected database (see SELECT) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use MOVE as a locking primitive because of this. <br /><br />
/// <br />
/// 将指定的 Key 从当前数据库移动到目标数据库。<br />
/// 如果目标数据库中已存在该键,或源数据库中不存在该键,则什么都不做。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/move <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="db">Database</param>
/// <returns>Specifically: True if key was moved. False if key was not moved.</returns>
public Task<bool> MoveAsync(string key, int db) => CallAsync("MOVE".InputKey(key, db), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// OBJECT REFCOUNT command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the number of references of the value associated with the specified key. This command is mainly useful for debugging.<br /><br />
/// <br />
/// 返回与指定键关联的值的引用数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the number of references of the value associated with the specified key.</returns>
public Task<long?> ObjectRefCountAsync(string key) => CallAsync("OBJECT".SubCommand("REFCOUNT").InputKey(key), rt => rt.ThrowOrValue<long?>());
/// <summary>
/// OBJECT IDLETIME command (An Asynchronous Version) <br /><br />
/// <br />
/// returns the number of seconds since the object stored at the specified key is idle (not requested by read or write operations). While the value is returned in seconds the actual resolution of this timer is 10 seconds, but may vary in future implementations. This subcommand is available when maxmemory-policy is set to an LRU policy or noeviction and maxmemory is set. <br /><br />
/// <br />
/// 返回指定键值的空闲时间,单位为秒。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the number of seconds since the object stored at the specified key is idle</returns>
public Task<long> ObjectIdleTimeAsync(string key) => CallAsync("OBJECT".SubCommand("IDLETIME").InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// OBJECT ENCODING command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the kind of internal representation used in order to store the value associated with a key.<br /><br />
/// <br />
/// 返回用于存储与键关联的值的内部表示形式的类型。
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the kind of internal representation used in order to store the value associated with a key.</returns>
public Task<string> ObjectEncodingAsync(string key) => CallAsync("OBJECT".SubCommand("ENCODING").InputKey(key), rt => rt.ThrowOrValue<string>());
/// <summary>
/// OBJECT FREQ command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the logarithmic access frequency counter of the object stored at the specified key. This subcommand is available when maxmemory-policy is set to an LFU policy.<br /><br />
/// <br />
/// 返回存储在指定键处的对象的对数访问频率计数器。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the logarithmic access frequency counter of the object stored at the specified key.</returns>
public Task<long?> ObjectFreqAsync(string key) => CallAsync("OBJECT".SubCommand("FREQ").InputKey(key), rt => rt.ThrowOrValue<long?>());
/// <summary>
/// PERSIST command (An Asynchronous Version) <br /><br />
/// <br />
/// Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated).<br /><br />
/// <br />
/// 将指定键的超时设置移除,将键从可变键转换为持久键。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/persist <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Specifically: True if the timeout was removed. False if key does not exist or does not have an associated timeout.</returns>
public Task<bool> PersistAsync(string key) => CallAsync("PERSIST".InputKey(key), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// PEXPIRE command (An Asynchronous Version) <br /><br />
/// <br />
/// This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// 此命令与 EXPIRE 相同,区别仅仅在于时间单位是毫秒,不是秒。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expire <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="milliseconds">Expires time (milliseconds)</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public Task<bool> PExpireAsync(string key, int milliseconds) => CallAsync("PEXPIRE".InputKey(key, milliseconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// PEXPIREAT command (An Asynchronous Version) <br /><br />
/// <br />
/// PEXPIREAT has the same effect and semantic as EXPIREAT, but the Unix time at which the key will expire is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// PEXPIREAT 具有与 EXPIREAT 相同的作用和语义,但 Key 的时间戳使用的是毫秒,而不是秒。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/pexpireat <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="timestamp">UNIX Timestamp</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
/// <returns></returns>
public Task<bool> PExpireAtAsync(string key, DateTime timestamp) => CallAsync("PEXPIREAT".InputKey(key, (long) timestamp.ToUniversalTime().Subtract(_epoch).TotalMilliseconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// PTTL command (An Asynchronous Version) <br /><br />
/// <br />
/// Like TTL this command returns the remaining time to live of a key that has an expire set, with the sole difference that TTL returns the amount of remaining time in seconds while PTTL returns it in milliseconds.<br />
/// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
/// Starting with Redis 2.8 the return value in case of error changed: <br />
/// - The command returns -2 if the key does not exist.<br />
/// - The command returns -1 if the key exists but has no associated expire.<br /><br />
/// <br />
/// 与 TTL 命令一样,返回键的剩余生存时间,唯一的区别是 TTL 以秒为单位返回剩余时间,而 PTTL 以毫秒为单位返回。<br />
/// 在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
/// 从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
/// - 如果 Key 不存在,则返回 -2 <br />
/// - 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/pttl <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>TTL in milliseconds, or a negative value in order to signal an error (see the description above).</returns>
public Task<long> PTtlAsync(string key) => CallAsync("PTTL".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// RANDOMKEY command (An Asynchronous Version) <br /><br />
/// <br />
/// Return a random key from the currently selected database. <br /><br />
/// <br />
/// 从当前选择的数据库返回一个随机密钥。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/randomkey <br />
/// Available since 1.0.0.
/// </summary>
/// <returns>The random key, or nil when the database is empty.</returns>
public Task<string> RandomKeyAsync() => CallAsync("RANDOMKEY", rt => rt.ThrowOrValue<string>());
/// <summary>
/// RENAME command (An Asynchronous Version) <br /><br />
/// <br />
/// Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
/// - Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
/// <br />
/// 将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
/// 如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
/// - 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/rename <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="newkey">New key</param>
public Task RenameAsync(string key, string newkey) => CallAsync("RENAME".InputKey(key).InputKey(newkey), rt => rt.ThrowOrValue<string>());
/// <summary>
/// RENAMENX command (An Asynchronous Version) <br /><br />
/// <br />
/// Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
/// - Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
/// <br />
/// 将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
/// 如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
/// - 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/renamenx <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="newkey">New key</param>
/// <returns>specifically: True if key was renamed to newkey. False if newkey already exists.</returns>
public Task<bool> RenameNxAsync(string key, string newkey) => CallAsync("RENAMENX".InputKey(key).InputKey(newkey), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// RESTORE command (An Asynchronous Version) <br /><br />
/// <br />
/// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
/// <br />
/// 将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/restore <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="serializedValue">Serialized value</param>
public Task RestoreAsync(string key, byte[] serializedValue) => RestoreAsync(key, 0, serializedValue);
/// <summary>
/// RESTORE command (An Asynchronous Version) <br /><br />
/// <br />
/// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
/// <br />
/// 将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/restore <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="ttl">If ttl is 0 the key is created without any expire, otherwise the specified expire time (in milliseconds) is set.</param>
/// <param name="serializedValue">Serialized value</param>
/// <param name="replace">REPLACE modifier: If the Key already exists, replace it. Available since 3.0.0.</param>
/// <param name="absTtl">Absolute Unix timestamp (in milliseconds) in which the key will expire. Available since 5.0.0.</param>
/// <param name="idleTimeSeconds">IDLETIME modifier. Available since 5.0.0.</param>
/// <param name="frequency">FREQ modifier. Available since 5.0.0.</param>
public Task RestoreAsync(string key, int ttl, byte[] serializedValue, bool replace = false, bool absTtl = false, int? idleTimeSeconds = null, decimal? frequency = null) => CallAsync("RESTORE"
.InputKey(key, ttl)
.InputRaw(serializedValue)
.InputIf(replace, "REPLACE")
.InputIf(absTtl, "ABSTTL")
.InputIf(idleTimeSeconds != null, "IDLETIME", idleTimeSeconds)
.InputIf(frequency != null, "FREQ", frequency), rt => rt.ThrowOrValue<string>());
/// <summary>
/// SCAN command (An Asynchronous Version) <br /><br />
/// <br />
/// The SCAN command and the closely related commands SSCAN, HSCAN and ZSCAN are used in order to incrementally iterate over a collection of elements.<br /><br />
/// <br />
/// 使用 SCAN 命令及其关联的 SSCAN、HSCAN、ZSCAN 等命令来迭代返回元素集合。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/scan <br />
/// Available since 2.8.0.
/// </summary>
/// <param name="cursor">Cursor</param>
/// <param name="pattern">MATCH option</param>
/// <param name="count">COUNT option: while SCAN does not provide guarantees about the number of elements returned at every iteration, it is possible to empirically adjust the behavior of SCAN using the COUNT option, default is 10</param>
/// <param name="type">TYPE option: the type argument is the same string name that the TYPE command returns. Available since 6.0</param>
/// <returns>Return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements.</returns>
public Task<ScanResult<string>> ScanAsync(long cursor, string pattern, long count, string type) => CallAsync("SCAN"
.Input(cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count > 0, "COUNT", count)
.InputIf(!string.IsNullOrWhiteSpace(type), "TYPE", type), rt => rt
.ThrowOrValue((a, _) => new ScanResult<string>(a[0].ConvertTo<long>(), a[1].ConvertTo<string[]>())));
/// <summary>
/// SORT command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns or stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
/// <br />
/// 返回含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/sort <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Keys</param>
/// <param name="byPattern">BY modifier</param>
/// <param name="offset">The number of elements to skip.</param>
/// <param name="count">Specifying the number of elements to return from starting at offset.</param>
/// <param name="getPatterns">GET modifier</param>
/// <param name="collation">ASC | DESC modifier</param>
/// <param name="alpha">ALPHA modifier, sort by lexicographically.</param>
/// <returns>A list of sorted elements</returns>
public Task<string[]> SortAsync(string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false) => CallAsync("SORT"
.InputKey(key)
.InputIf(!string.IsNullOrWhiteSpace(byPattern), "BY", byPattern)
.InputIf(offset != 0 || count != 0, "LIMIT", offset, count)
.InputIf(getPatterns?.Any() == true, getPatterns.Select(a => new[] {"GET", a}).SelectMany(a => a).ToArray())
.InputIf(collation != null, collation)
.InputIf(alpha, "ALPHA"), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// SORT command (An Asynchronous Version) <br /><br />
/// <br />
/// Stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
/// <br />
/// 存储包含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/sort <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="storeDestination">Storing the result of a SORT operation to the destination key.</param>
/// <param name="key">Keys</param>
/// <param name="byPattern">BY modifier</param>
/// <param name="offset">The number of elements to skip.</param>
/// <param name="count">Specifying the number of elements to return from starting at offset.</param>
/// <param name="getPatterns">GET modifier</param>
/// <param name="collation">ASC | DESC modifier</param>
/// <param name="alpha">ALPHA modifier, sort by lexicographically.</param>
/// <returns>The number of sorted elements in the destination list.</returns>
public Task<long> SortStoreAsync(string storeDestination, string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false) => CallAsync("SORT"
.InputKey(key)
.InputIf(!string.IsNullOrWhiteSpace(byPattern), "BY", byPattern)
.InputIf(offset != 0 || count != 0, "LIMIT", offset, count)
.InputIf(getPatterns?.Any() == true, getPatterns.Select(a => new[] {"GET", a}).SelectMany(a => a).ToArray())
.InputIf(collation != null, collation)
.InputIf(alpha, "ALPHA")
.InputIf(!string.IsNullOrWhiteSpace(storeDestination), "STORE")
.InputKeyIf(!string.IsNullOrWhiteSpace(storeDestination), storeDestination), rt => rt.ThrowOrValue<long>());
/// <summary>
/// TOUCH command (An Asynchronous Version) <br /><br />
/// <br />
/// Alters the last access time of a key(s). A key is ignored if it does not exist.<br /><br />
/// <br />
/// 更改 Key(s) 最后访问时间。如果键不存在,则忽略之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/touch <br />
/// Available since 3.2.1.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys that were touched.</returns>
public Task<long> TouchAsync(params string[] keys) => CallAsync("TOUCH".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// TTL command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.<br />
/// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
/// Starting with Redis 2.8 the return value in case of error changed: <br />
/// - The command returns -2 if the key does not exist.<br />
/// - The command returns -1 if the key exists but has no associated expire.<br /><br />
/// <br />
/// 返回键的剩余生存时间。这种自省能力允许 Redis 客户端检查指定键还能再数据集中生存多少秒。<br />
/// 在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
/// 从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
/// - 如果 Key 不存在,则返回 -2 <br />
/// - 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/ttl <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>TTL in seconds, or a negative value in order to signal an error (see the description above).</returns>
public Task<long> TtlAsync(string key) => CallAsync("TTL".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// TYPE command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset, hash and stream.<br /><br />
/// <br />
/// 获取键对应值的类型的字符串表达形式。可以返回的类型是:string,list,set,zset,hash 以及 stream。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/type <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The type of key, or none when key does not exist.</returns>
public Task<KeyType> TypeAsync(string key) => CallAsync("TYPE".InputKey(key), rt => rt.ThrowOrValue<KeyType>());
/// <summary>
/// UNLINK command (An Asynchronous Version) <br /><br />
/// <br />
/// This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. <br /><br />
/// <br />
/// 本命令与 DEL 相似,能删除指定的键值;如果键不存在,则忽略。与 DEL 不同的是,本命令将在另一个线程中执行实际的内存回收,因此是非阻塞的。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/unlink <br />
/// Available since 4.0.0.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys that were unlinked.</returns>
public Task<long> UnLinkAsync(params string[] keys) => CallAsync("UNLINK".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// WAIT command (An Asynchronous Version) <br /><br />
/// <br />
/// This command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of replicas. If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of replicas were not yet reached. <br /><br />
/// <br />
/// 本命令将阻塞当前客户端,直到所有写命令成功发送、且大于等于指定数量的副本进行了确认。<br />
/// 如果超时(单位为毫秒),即便没能获得指定数量副本的确认,命令也会返回。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/wait <br />
/// Available since 3.0.0.
/// </summary>
/// <param name="numreplicas">The number of replicas</param>
/// <param name="timeoutMilliseconds">Timeout milliseconds</param>
/// <returns>The command returns the number of replicas reached by all the writes performed in the context of the current connection.</returns>
public Task<long> WaitAsync(long numreplicas, long timeoutMilliseconds) => CallAsync("WAIT".Input(numreplicas, timeoutMilliseconds), rt => rt.ThrowOrValue<long>());
#endregion
#endif
/// <summary>
/// DEL command (A Synchronized Version) <br /><br />
/// <br />
/// Removes the specified keys. A key is ignored if it does not exist.<br /><br />
/// <br />
/// 移除指定的键。如果键不存在,则忽略之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/del <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys that were removed.</returns>
public long Del(params string[] keys) => Call("DEL".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DUMP command (A Synchronized Version) <br /><br />
/// <br />
/// Serialize the value stored at key in a Redis-specific format and return it to the user. The returned value can be synthesized back into a Redis key using the RESTORE command.<br /><br />
/// <br />
/// 以 Redis 特有格式序列化指定的键值,并返回给用户。可结合 RESTORE 命令将序列化的结果重新写回 Redis。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/dump <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The serialized value.</returns>
public byte[] Dump(string key) => Call("DUMP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue<byte[]>());
/// <summary>
/// EXISTS command (A Synchronized Version) <br /><br />
/// <br />
/// Returns if key exists.<br /><br />
/// <br />
/// 返回键是否存在。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/exists <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Specifically: True if the key exists. False if the key does not exist.</returns>
public bool Exists(string key) => Call("EXISTS".InputKey(key), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// EXISTS command (A Synchronized Version) <br /><br />
/// <br />
/// Returns if key exists.<br /><br />
/// <br />
/// 返回键是否存在。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/exists <br />
/// Available since 3.0.3.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys existing among the ones specified as arguments. Keys mentioned multiple times and existing are counted multiple times.</returns>
public long Exists(string[] keys) => Call("EXISTS".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// EXPIRE command (A Synchronized Version) <br /><br />
/// <br />
/// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
/// <br />
/// 设置键的超时时间。到期后,键将被自动删除。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expire <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="seconds">Expires time (seconds)</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public bool Expire(string key, int seconds) => Call("EXPIRE".InputKey(key, seconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// EXPIRE command (A Synchronized Version) <br /><br />
/// <br />
/// Set a timeout on key. After the timeout has expired, the key will automatically be deleted. A key with an associated timeout is often said to be volatile in Redis terminology.<br /><br />
/// <br />
/// 设置键的超时时间。到期后,键将被自动删除。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expire <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="expire">Expires TimeSpan</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public bool Expire(string key, TimeSpan expire) => Call("EXPIRE".InputKey(key, (long)expire.TotalSeconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// EXPIREAT command (A Synchronized Version) <br /><br />
/// <br />
/// EXPIREAT has the same effect and semantic as EXPIRE, but instead of specifying the number of seconds representing the TTL (time to live), it takes an absolute Unix timestamp (seconds since January 1, 1970). A timestamp in the past will delete the key immediately.<br /><br />
/// <br />
/// EXPIREAT 具有与 EXPIRE 相同的作用和语义,但是它没有指定表示 TTL(生存时间)的秒数,而是使用了绝对的 Unix 时间戳(自1970年1月1日以来的秒数)。时间戳一旦过期就会被删除。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expireat <br />
/// Available since 1.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="timestamp">UNIX Timestamp</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public bool ExpireAt(string key, DateTime timestamp) => Call("EXPIREAT".InputKey(key, (long) timestamp.ToUniversalTime().Subtract(_epoch).TotalSeconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// KEYS command (A Synchronized Version) <br /><br />
/// <br />
/// Returns all keys matching pattern.<br /><br />
/// <br />
/// 返回所有与模式匹配的键。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/keys <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="pattern">Pattern</param>
/// <returns>List of keys matching pattern.</returns>
public string[] Keys(string pattern) => Call("KEYS".Input(pattern), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// MIGRATE command (A Synchronized Version) <br /><br />
/// <br />
/// Atomically transfer a key from a source Redis instance to a destination Redis instance. On success the key is deleted from the original instance and is guaranteed to exist in the target instance.<br /><br />
/// <br />
/// 原子地将键从 Redis 源实例转移到目标实例。转移成功后,Key 将从源实例中删除,并确保保存在目标实例之中。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/migrate <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="host">Destination Instance's Host</param>
/// <param name="port">Destination Instance's Port</param>
/// <param name="key">Key</param>
/// <param name="destinationDb">Destination Instance's Database</param>
/// <param name="timeoutMilliseconds">Timeout milliseconds</param>
/// <param name="copy">Do not remove the key from the local instance. Available since 3.0.0. </param>
/// <param name="replace">Replace existing key on the remote instance. Available since 3.0.0. </param>
/// <param name="authPassword">Authenticate with the given password to the remote instance. Available since 4.0.7. </param>
/// <param name="auth2Username">Authenticate with the given username (Redis 6 or greater ACL auth style).</param>
/// <param name="auth2Password">Authenticate with the given password (Redis 6 or greater ACL auth style).</param>
/// <param name="keys">If the key argument is an empty string, the command will instead migrate all the keys that follow the KEYS option (see the above section for more info). Available since 3.0.6. </param>
public void Migrate(string host, int port, string key, int destinationDb, long timeoutMilliseconds, bool copy, bool replace, string authPassword, string auth2Username, string auth2Password, string[] keys) => Call("MIGRATE"
.Input(host, port)
.InputKey(key ?? "")
.Input(destinationDb, timeoutMilliseconds)
.InputIf(copy, "COPY")
.InputIf(replace, "REPLACE")
.InputIf(!string.IsNullOrWhiteSpace(authPassword), "AUTH", authPassword)
.InputIf(!string.IsNullOrWhiteSpace(auth2Username) && !string.IsNullOrWhiteSpace(auth2Password), "AUTH2", auth2Username, auth2Password)
.InputKey(keys), rt => rt.ThrowOrValue<string>());
/// <summary>
/// MOVE command (A Synchronized Version) <br /><br />
/// <br />
/// Move key from the currently selected database (see SELECT) to the specified destination database. When key already exists in the destination database, or it does not exist in the source database, it does nothing. It is possible to use MOVE as a locking primitive because of this. <br /><br />
/// <br />
/// 将指定的 Key 从当前数据库移动到目标数据库。<br />
/// 如果目标数据库中已存在该键,或源数据库中不存在该键,则什么都不做。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/move <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="db">Database</param>
/// <returns>Specifically: True if key was moved. False if key was not moved.</returns>
public bool Move(string key, int db) => Call("MOVE".InputKey(key, db), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// OBJECT REFCOUNT command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the number of references of the value associated with the specified key. This command is mainly useful for debugging.<br /><br />
/// <br />
/// 返回与指定键关联的值的引用数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the number of references of the value associated with the specified key.</returns>
public long? ObjectRefCount(string key) => Call("OBJECT".SubCommand("REFCOUNT").InputKey(key), rt => rt.ThrowOrValue<long?>());
/// <summary>
/// OBJECT IDLETIME command (A Synchronized Version) <br /><br />
/// <br />
/// returns the number of seconds since the object stored at the specified key is idle (not requested by read or write operations). While the value is returned in seconds the actual resolution of this timer is 10 seconds, but may vary in future implementations. This subcommand is available when maxmemory-policy is set to an LRU policy or noeviction and maxmemory is set. <br /><br />
/// <br />
/// 返回指定键值的空闲时间,单位为秒。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the number of seconds since the object stored at the specified key is idle</returns>
public long ObjectIdleTime(string key) => Call("OBJECT".SubCommand("IDLETIME").InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// OBJECT ENCODING command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the kind of internal representation used in order to store the value associated with a key.<br /><br />
/// <br />
/// 返回用于存储与键关联的值的内部表示形式的类型。
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the kind of internal representation used in order to store the value associated with a key.</returns>
public string ObjectEncoding(string key) => Call("OBJECT".SubCommand("ENCODING").InputKey(key), rt => rt.ThrowOrValue<string>());
/// <summary>
/// OBJECT FREQ command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the logarithmic access frequency counter of the object stored at the specified key. This subcommand is available when maxmemory-policy is set to an LFU policy.<br /><br />
/// <br />
/// 返回存储在指定键处的对象的对数访问频率计数器。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/object <br />
/// Available since 2.2.3.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Returns the logarithmic access frequency counter of the object stored at the specified key.</returns>
public long? ObjectFreq(string key) => Call("OBJECT".SubCommand("FREQ").InputKey(key), rt => rt.ThrowOrValue<long?>());
/// <summary>
/// PERSIST command (A Synchronized Version) <br /><br />
/// <br />
/// Remove the existing timeout on key, turning the key from volatile (a key with an expire set) to persistent (a key that will never expire as no timeout is associated).<br /><br />
/// <br />
/// 将指定键的超时设置移除,将键从可变键转换为持久键。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/persist <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>Specifically: True if the timeout was removed. False if key does not exist or does not have an associated timeout.</returns>
public bool Persist(string key) => Call("PERSIST".InputKey(key), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// PEXPIRE command (A Synchronized Version) <br /><br />
/// <br />
/// This command works exactly like EXPIRE but the time to live of the key is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// 此命令与 EXPIRE 相同,区别仅仅在于时间单位是毫秒,不是秒。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/expire <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="milliseconds">Expires time (milliseconds)</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
public bool PExpire(string key, int milliseconds) => Call("PEXPIRE".InputKey(key, milliseconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// PEXPIREAT command (A Synchronized Version) <br /><br />
/// <br />
/// PEXPIREAT has the same effect and semantic as EXPIREAT, but the Unix time at which the key will expire is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// PEXPIREAT 具有与 EXPIREAT 相同的作用和语义,但 Key 的时间戳使用的是毫秒,而不是秒。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/pexpireat <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="timestamp">UNIX Timestamp</param>
/// <returns>Specifically: True if the timeout was set.False if key does not exist.</returns>
/// <returns></returns>
public bool PExpireAt(string key, DateTime timestamp) => Call("PEXPIREAT".InputKey(key, (long) timestamp.ToUniversalTime().Subtract(_epoch).TotalMilliseconds), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// PTTL command (A Synchronized Version) <br /><br />
/// <br />
/// Like TTL this command returns the remaining time to live of a key that has an expire set, with the sole difference that TTL returns the amount of remaining time in seconds while PTTL returns it in milliseconds.<br />
/// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
/// Starting with Redis 2.8 the return value in case of error changed: <br />
/// - The command returns -2 if the key does not exist.<br />
/// - The command returns -1 if the key exists but has no associated expire.<br /><br />
/// <br />
/// 与 TTL 命令一样,返回键的剩余生存时间,唯一的区别是 TTL 以秒为单位返回剩余时间,而 PTTL 以毫秒为单位返回。<br />
/// 在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
/// 从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
/// - 如果 Key 不存在,则返回 -2 <br />
/// - 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/pttl <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>TTL in milliseconds, or a negative value in order to signal an error (see the description above).</returns>
public long PTtl(string key) => Call("PTTL".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// RANDOMKEY command (A Synchronized Version) <br /><br />
/// <br />
/// Return a random key from the currently selected database. <br /><br />
/// <br />
/// 从当前选择的数据库返回一个随机密钥。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/randomkey <br />
/// Available since 1.0.0.
/// </summary>
/// <returns>The random key, or nil when the database is empty.</returns>
public string RandomKey() => Call("RANDOMKEY", rt => rt.ThrowOrValue<string>());
/// <summary>
/// RENAME command (A Synchronized Version) <br /><br />
/// <br />
/// Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
/// - Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
/// <br />
/// 将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
/// 如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
/// - 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/rename <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="newkey">New key</param>
public void Rename(string key, string newkey) => Call("RENAME".InputKey(key).InputKey(newkey), rt => rt.ThrowOrValue<string>());
/// <summary>
/// RENAMENX command (A Synchronized Version) <br /><br />
/// <br />
/// Renames key to newkey. It returns an error when key does not exist. If newkey already exists it is overwritten, when this happens RENAME executes an implicit DEL operation, so if the deleted key contains a very big value it may cause high latency even if RENAME itself is usually a constant-time operation.<br />
/// - Before Redis 3.2.0, an error is returned if source and destination names are the same.<br /><br />
/// <br />
/// 将 Key 重命名为 New Key。如果键不存在,返回错误。<br />
/// 如果 New Key 已存在,则将被覆盖,此时类似 DEL 命令,由于 RENAME 是 constant-time operation,因此当删除的键有很大的值时会有较大的延迟。<br />
/// - 在 Redis 3.2 之前,如果 Key 和 New Key 名字一样,将返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/renamenx <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="newkey">New key</param>
/// <returns>specifically: True if key was renamed to newkey. False if newkey already exists.</returns>
public bool RenameNx(string key, string newkey) => Call("RENAMENX".InputKey(key).InputKey(newkey), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// RESTORE command (A Synchronized Version) <br /><br />
/// <br />
/// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
/// <br />
/// 将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/restore <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="serializedValue">Serialized value</param>
public void Restore(string key, byte[] serializedValue) => Restore(key, 0, serializedValue);
/// <summary>
/// RESTORE command (A Synchronized Version) <br /><br />
/// <br />
/// Create a key associated with a value that is obtained by deserializing the provided serialized value (obtained via DUMP).<br /><br />
/// <br />
/// 将经由 DUMP 命令序列化的值反序列化后,作为给定键的值进行保存。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/restore <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="ttl">If ttl is 0 the key is created without any expire, otherwise the specified expire time (in milliseconds) is set.</param>
/// <param name="serializedValue">Serialized value</param>
/// <param name="replace">REPLACE modifier: If the Key already exists, replace it. Available since 3.0.0.</param>
/// <param name="absTtl">Absolute Unix timestamp (in milliseconds) in which the key will expire. Available since 5.0.0.</param>
/// <param name="idleTimeSeconds">IDLETIME modifier. Available since 5.0.0.</param>
/// <param name="frequency">FREQ modifier. Available since 5.0.0.</param>
public void Restore(string key, int ttl, byte[] serializedValue, bool replace = false, bool absTtl = false, int? idleTimeSeconds = null, decimal? frequency = null) => Call("RESTORE"
.InputKey(key, ttl)
.InputRaw(serializedValue)
.InputIf(replace, "REPLACE")
.InputIf(absTtl, "ABSTTL")
.InputIf(idleTimeSeconds != null, "IDLETIME", idleTimeSeconds)
.InputIf(frequency != null, "FREQ", frequency), rt => rt.ThrowOrValue<string>());
/// <summary>
/// SCAN command (A Synchronized Version) <br /><br />
/// <br />
/// The SCAN command and the closely related commands SSCAN, HSCAN and ZSCAN are used in order to incrementally iterate over a collection of elements.<br /><br />
/// <br />
/// 使用 SCAN 命令及其关联的 SSCAN、HSCAN、ZSCAN 等命令来迭代返回元素集合。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/scan <br />
/// Available since 2.8.0.
/// </summary>
/// <param name="cursor">Cursor</param>
/// <param name="pattern">MATCH option</param>
/// <param name="count">COUNT option: while SCAN does not provide guarantees about the number of elements returned at every iteration, it is possible to empirically adjust the behavior of SCAN using the COUNT option, default is 10</param>
/// <param name="type">TYPE option: the type argument is the same string name that the TYPE command returns. Available since 6.0</param>
/// <returns>Return a two elements multi-bulk reply, where the first element is a string representing an unsigned 64 bit number (the cursor), and the second element is a multi-bulk with an array of elements.</returns>
public ScanResult<string> Scan(long cursor, string pattern, long count, string type) => Call("SCAN"
.Input(cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count > 0, "COUNT", count)
.InputIf(!string.IsNullOrWhiteSpace(type), "TYPE", type), rt => rt
.ThrowOrValue((a, _) => new ScanResult<string>(a[0].ConvertTo<long>(), a[1].ConvertTo<string[]>())));
public IEnumerable<string[]> Scan(string pattern, long count, string type) => new ScanCollection<string>(this, "scan", (cli, cursor) => cli.Scan(cursor, pattern, count, type));
#region Scan IEnumerable
class ScanCollection<T> : IEnumerable<T[]>
{
public IEnumerator<T[]> GetEnumerator()
{
long cursor = 0;
if (_cli.Adapter.UseType == UseType.Cluster && _scanName == "scan")
{
var cluster = (_cli.Adapter as ClusterAdapter);
var ibkeys = new List<string>();
#region get ibkeys
var testConnection = cluster._clusterConnectionStrings.FirstOrDefault();
var cnodes = _cli.Call("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>()).Split('\n');
foreach (var cnode in cnodes)
{
if (string.IsNullOrEmpty(cnode)) continue;
var dt = cnode.Trim().Split(' ');
if (dt.Length < 9) continue;
if (!dt[2].StartsWith("master") && !dt[2].EndsWith("master")) continue;
if (dt[7] != "connected") continue;
var endpoint = dt[1];
var at40 = endpoint.IndexOf('@');
if (at40 != -1) endpoint = endpoint.Remove(at40);
if (endpoint.StartsWith("127.0.0.1"))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
else if (endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
ibkeys.Add(endpoint);
}
#endregion
foreach (var poolkey in ibkeys)
{
cursor = 0;
var pool = cluster._ib.Get(poolkey);
if (pool?.IsAvailable != true) continue;
var cli = pool.Get();
var rds = cli.Value.Adapter.GetRedisSocket(null);
using (var rdsproxy = DefaultRedisSocket.CreateTempProxy(rds, () => pool.Return(cli)))
{
rdsproxy._poolkey = poolkey;
rdsproxy._pool = pool;
while (true)
{
var rt = _scanFunc(cli.Value, cursor);
cursor = rt.cursor;
if (rt.length > 0) yield return rt.items;
if (cursor <= 0) break;
}
}
}
yield break;
}
else
{
while (true)
{
var rt = _scanFunc(_cli, cursor);
cursor = rt.cursor;
if (rt.length > 0) yield return rt.items;
if (cursor <= 0) break;
}
yield break;
}
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
readonly RedisClient _cli;
readonly string _scanName;
readonly Func<RedisClient, long, ScanResult<T>> _scanFunc;
public ScanCollection(RedisClient cli, string scanName, Func<RedisClient, long, ScanResult<T>> scanFunc)
{
_cli = cli;
_scanName = scanName;
_scanFunc = scanFunc;
}
}
#endregion
/// <summary>
/// SORT command (A Synchronized Version) <br /><br />
/// <br />
/// Returns or stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
/// <br />
/// 返回含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/sort <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Keys</param>
/// <param name="byPattern">BY modifier</param>
/// <param name="offset">The number of elements to skip.</param>
/// <param name="count">Specifying the number of elements to return from starting at offset.</param>
/// <param name="getPatterns">GET modifier</param>
/// <param name="collation">ASC | DESC modifier</param>
/// <param name="alpha">ALPHA modifier, sort by lexicographically.</param>
/// <returns>A list of sorted elements</returns>
public string[] Sort(string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false) => Call("SORT"
.InputKey(key)
.InputIf(!string.IsNullOrWhiteSpace(byPattern), "BY", byPattern)
.InputIf(offset != 0 || count != 0, "LIMIT", offset, count)
.InputIf(getPatterns?.Any() == true, getPatterns.Select(a => new[] {"GET", a}).SelectMany(a => a).ToArray())
.InputIf(collation != null, collation)
.InputIf(alpha, "ALPHA"), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// SORT command (A Synchronized Version) <br /><br />
/// <br />
/// Stores the elements contained in the list, set or sorted set at key. By default, sorting is numeric and elements are compared by their value interpreted as double precision floating point number. <br /><br />
/// <br />
/// 存储包含在 LIST、SET、ZSET 中的元素。默认情况下,排序是数字形式的,并且将元素的值进行比较以解释为双精度浮点数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/sort <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="storeDestination">Storing the result of a SORT operation to the destination key.</param>
/// <param name="key">Keys</param>
/// <param name="byPattern">BY modifier</param>
/// <param name="offset">The number of elements to skip.</param>
/// <param name="count">Specifying the number of elements to return from starting at offset.</param>
/// <param name="getPatterns">GET modifier</param>
/// <param name="collation">ASC | DESC modifier</param>
/// <param name="alpha">ALPHA modifier, sort by lexicographically.</param>
/// <returns>The number of sorted elements in the destination list.</returns>
public long SortStore(string storeDestination, string key, string byPattern = null, long offset = 0, long count = 0, string[] getPatterns = null, Collation? collation = null, bool alpha = false) => Call("SORT"
.InputKey(key)
.InputIf(!string.IsNullOrWhiteSpace(byPattern), "BY", byPattern)
.InputIf(offset != 0 || count != 0, "LIMIT", offset, count)
.InputIf(getPatterns?.Any() == true, getPatterns.Select(a => new[] {"GET", a}).SelectMany(a => a).ToArray())
.InputIf(collation != null, collation)
.InputIf(alpha, "ALPHA")
.InputIf(!string.IsNullOrWhiteSpace(storeDestination), "STORE")
.InputKeyIf(!string.IsNullOrWhiteSpace(storeDestination), storeDestination), rt => rt.ThrowOrValue<long>());
/// <summary>
/// TOUCH command (A Synchronized Version) <br /><br />
/// <br />
/// Alters the last access time of a key(s). A key is ignored if it does not exist.<br /><br />
/// <br />
/// 更改 Key(s) 最后访问时间。如果键不存在,则忽略之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/touch <br />
/// Available since 3.2.1.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys that were touched.</returns>
public long Touch(params string[] keys) => Call("TOUCH".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// TTL command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the remaining time to live of a key that has a timeout. This introspection capability allows a Redis client to check how many seconds a given key will continue to be part of the dataset.<br />
/// In Redis 2.6 or older the command returns -1 if the key does not exist or if the key exist but has no associated expire. <br />
/// Starting with Redis 2.8 the return value in case of error changed: <br />
/// - The command returns -2 if the key does not exist.<br />
/// - The command returns -1 if the key exists but has no associated expire.<br /><br />
/// <br />
/// 返回键的剩余生存时间。这种自省能力允许 Redis 客户端检查指定键还能再数据集中生存多少秒。<br />
/// 在 Redis 2.6 之前,如果 Key 不存在或 Key 未设置过期时间,则返回 -1<br />
/// 从 Redis 2.8 开始,将针对不同的错误情况返回不同的值:<br />
/// - 如果 Key 不存在,则返回 -2 <br />
/// - 如果 Key 存在,但没有设置过过期时间,则返回 -1 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/ttl <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>TTL in seconds, or a negative value in order to signal an error (see the description above).</returns>
public long Ttl(string key) => Call("TTL".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// TYPE command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the string representation of the type of the value stored at key. The different types that can be returned are: string, list, set, zset, hash and stream.<br /><br />
/// <br />
/// 获取键对应值的类型的字符串表达形式。可以返回的类型是:string,list,set,zset,hash 以及 stream。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/type <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The type of key, or none when key does not exist.</returns>
public KeyType Type(string key) => Call("TYPE".InputKey(key), rt => rt.ThrowOrValue<KeyType>());
/// <summary>
/// UNLINK command (A Synchronized Version) <br /><br />
/// <br />
/// This command is very similar to DEL: it removes the specified keys. Just like DEL a key is ignored if it does not exist. However the command performs the actual memory reclaiming in a different thread, so it is not blocking, while DEL is. <br /><br />
/// <br />
/// 本命令与 DEL 相似,能删除指定的键值;如果键不存在,则忽略。与 DEL 不同的是,本命令将在另一个线程中执行实际的内存回收,因此是非阻塞的。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/unlink <br />
/// Available since 4.0.0.
/// </summary>
/// <param name="keys">Keys</param>
/// <returns>The number of keys that were unlinked.</returns>
public long UnLink(params string[] keys) => Call("UNLINK".InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// WAIT command (A Synchronized Version) <br /><br />
/// <br />
/// This command blocks the current client until all the previous write commands are successfully transferred and acknowledged by at least the specified number of replicas. If the timeout, specified in milliseconds, is reached, the command returns even if the specified number of replicas were not yet reached. <br /><br />
/// <br />
/// 本命令将阻塞当前客户端,直到所有写命令成功发送、且大于等于指定数量的副本进行了确认。<br />
/// 如果超时(单位为毫秒),即便没能获得指定数量副本的确认,命令也会返回。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/wait <br />
/// Available since 3.0.0.
/// </summary>
/// <param name="numreplicas">The number of replicas</param>
/// <param name="timeoutMilliseconds">Timeout milliseconds</param>
/// <returns>The command returns the number of replicas reached by all the writes performed in the context of the current connection.</returns>
public long Wait(long numreplicas, long timeoutMilliseconds) => Call("WAIT".Input(numreplicas, timeoutMilliseconds), rt => rt.ThrowOrValue<long>());
}
} |
2881099/FreeRedis | 26,260 | src/FreeRedis/RedisClient/SortedSets.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
async public Task<ZMember> BZPopMinAsync(string key, int timeoutSeconds) => (await BZPopAsync(false, new[] { key }, timeoutSeconds))?.value;
public Task<KeyValue<ZMember>> BZPopMinAsync(string[] keys, int timeoutSeconds) => BZPopAsync(false, keys, timeoutSeconds);
async public Task<ZMember> BZPopMaxAsync(string key, int timeoutSeconds) => (await BZPopAsync(true, new[] { key }, timeoutSeconds))?.value;
public Task<KeyValue<ZMember>> BZPopMaxAsync(string[] keys, int timeoutSeconds) => BZPopAsync(true, keys, timeoutSeconds);
Task<KeyValue<ZMember>> BZPopAsync(bool ismax, string[] keys, int timeoutSeconds) => CallAsync((ismax ? "BZPOPMAX" : "BZPOPMIN")
.InputKey(keys, timeoutSeconds), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? null : new KeyValue<ZMember>(a[0].ConvertTo<string>(), new ZMember(a[1].ConvertTo<string>(), a[2].ConvertTo<decimal>().ConvertTo<decimal>()))));
public Task<long> ZAddAsync(string key, decimal score, string member, params object[] scoreMembers) => ZAddAsync<long>(key, false, false, null, false, false, score, member, scoreMembers);
public Task<long> ZAddAsync(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false) => ZAddAsync<long>(key, false, false, than, ch, false, scoreMembers);
public Task<long> ZAddNxAsync(string key, decimal score, string member, params object[] scoreMembers) => ZAddAsync<long>(key, true, false, null, false, false, score, member, scoreMembers);
public Task<long> ZAddNxAsync(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false) => ZAddAsync<long>(key, true, false, than, ch, false, scoreMembers);
public Task<long> ZAddXxAsync(string key, decimal score, string member, params object[] scoreMembers) => ZAddAsync<long>(key, false, true, null, false, false, score, member, scoreMembers);
public Task<long> ZAddXxAsync(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false) => ZAddAsync<long>(key, false, true, than, ch, false, scoreMembers);
Task<T> ZAddAsync<T>(string key, bool nx, bool xx, ZAddThan? than, bool ch, bool incr, decimal score, string member, params object[] scoreMembers)
{
if (scoreMembers?.Length > 0)
{
var members = scoreMembers.MapToList((sco, mem) => new ZMember(mem.ConvertTo<string>(), sco.ConvertTo<decimal>()));
members.Insert(0, new ZMember(member, score));
return ZAddAsync<T>(key, nx, xx, than, ch, incr, members);
}
return ZAddAsync<T>(key, nx, xx, than, ch, incr, new[] { new ZMember(member, score) });
}
Task<TReturn> ZAddAsync<TReturn>(string key, bool nx, bool xx, ZAddThan? than, bool ch, bool incr, IEnumerable<ZMember> scoreMembers)
{
var cmd = "ZADD"
.InputKey(key)
.InputIf(nx, "NX")
.InputIf(xx, "XX")
.InputIf(than != null, than)
.InputIf(ch, "CH")
.InputIf(incr, "INCR");
foreach (var sm in scoreMembers) cmd.InputRaw(sm.score).InputRaw(sm.member);
return CallAsync(cmd, rt => rt.ThrowOrValue<TReturn>());
}
public Task<long> ZCardAsync(string key) => CallAsync("ZCARD".InputKey(key), rt => rt.ThrowOrValue<long>());
public Task<long> ZCountAsync(string key, decimal min, decimal max) => CallAsync("ZCOUNT".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public Task<long> ZCountAsync(string key, string min, string max) => CallAsync("ZCOUNT".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public Task<decimal> ZIncrByAsync(string key, decimal increment, string member) => CallAsync("ZINCRBY".InputKey(key, increment, member), rt => rt.ThrowOrValue<decimal>());
public Task<long> ZInterStoreAsync(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null) => ZStoreAsync(true, destination, keys, weights, aggregate);
public Task<long> ZLexCountAsync(string key, string min, string max) => CallAsync("ZLEXCOUNT".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public Task<ZMember> ZPopMinAsync(string key) => ZPopAsync(false, key);
public Task<ZMember[]> ZPopMinAsync(string key, int count) => ZPopAsync(false, key, count);
public Task<ZMember> ZPopMaxAsync(string key) => ZPopAsync(true, key);
public Task<ZMember[]> ZPopMaxAsync(string key, int count) => ZPopAsync(true, key, count);
Task<ZMember> ZPopAsync(bool ismax, string key) => CallAsync((ismax ? "ZPOPMAX" : "ZPOPMIN").InputKey(key), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? null : new ZMember(a[0].ConvertTo<string>(), a[1].ConvertTo<decimal>())));
Task<ZMember[]> ZPopAsync(bool ismax, string key, int count) => CallAsync((ismax ? "ZPOPMAX" : "ZPOPMIN").InputKey(key, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<string[]> ZRangeAsync(string key, decimal start, decimal stop) => CallAsync("ZRANGE".InputKey(key, start, stop), rt => rt.ThrowOrValue<string[]>());
public Task<ZMember[]> ZRangeWithScoresAsync(string key, decimal start, decimal stop) => CallAsync("ZRANGE"
.InputKey(key, start, stop)
.Input("WITHSCORES"), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<string[]> ZRangeByLexAsync(string key, string min, string max, int offset = 0, int count = 0) => CallAsync("ZRANGEBYLEX"
.InputKey(key, min, max)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<string[]> ZRangeByScoreAsync(string key, decimal min, decimal max, int offset = 0, int count = 0) => CallAsync("ZRANGEBYSCORE"
.InputKey(key, min, max)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<string[]> ZRangeByScoreAsync(string key, string min, string max, int offset = 0, int count = 0) => CallAsync("ZRANGEBYSCORE"
.InputKey(key, min, max)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<ZMember[]> ZRangeByScoreWithScoresAsync(string key, decimal min, decimal max, int offset = 0, int count = 0) => CallAsync("ZRANGEBYSCORE"
.InputKey(key, min, max)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<ZMember[]> ZRangeByScoreWithScoresAsync(string key, string min, string max, int offset = 0, int count = 0) => CallAsync("ZRANGEBYSCORE"
.InputKey(key, min, max)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<long?> ZRankAsync(string key, string member) => CallAsync("ZRANK".InputKey(key, member), rt => rt.ThrowOrValue<long?>());
public Task<long> ZRemAsync(string key, params string[] members) => CallAsync("ZREM".InputKey(key, members), rt => rt.ThrowOrValue<long>());
public Task<long> ZRemRangeByLexAsync(string key, string min, string max) => CallAsync("ZREMRANGEBYLEX".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public Task<long> ZRemRangeByRankAsync(string key, long start, long stop) => CallAsync("ZREMRANGEBYRANK".InputKey(key, start, stop), rt => rt.ThrowOrValue<long>());
public Task<long> ZRemRangeByScoreAsync(string key, decimal min, decimal max) => CallAsync("ZREMRANGEBYSCORE".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public Task<long> ZRemRangeByScoreAsync(string key, string min, string max) => CallAsync("ZREMRANGEBYSCORE".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public Task<string[]> ZRevRangeAsync(string key, decimal start, decimal stop) => CallAsync("ZREVRANGE".InputKey(key, start, stop), rt => rt.ThrowOrValue<string[]>());
public Task<ZMember[]> ZRevRangeWithScoresAsync(string key, decimal start, decimal stop) => CallAsync("ZREVRANGE"
.InputKey(key, start, stop)
.Input("WITHSCORES"), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<string[]> ZRevRangeByLexAsync(string key, decimal max, decimal min, int offset = 0, int count = 0) => CallAsync("ZREVRANGEBYLEX"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<string[]> ZRevRangeByLexAsync(string key, string max, string min, int offset = 0, int count = 0) => CallAsync("ZREVRANGEBYLEX"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<string[]> ZRevRangeByScoreAsync(string key, decimal max, decimal min, int offset = 0, int count = 0) => CallAsync("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<string[]> ZRevRangeByScoreAsync(string key, string max, string min, int offset = 0, int count = 0) => CallAsync("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public Task<ZMember[]> ZRevRangeByScoreWithScoresAsync(string key, decimal max, decimal min, int offset = 0, int count = 0) => CallAsync("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<ZMember[]> ZRevRangeByScoreWithScoresAsync(string key, string max, string min, int offset = 0, int count = 0) => CallAsync("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public Task<long> ZRevRankAsync(string key, string member) => CallAsync("ZREVRANK".InputKey(key, member), rt => rt.ThrowOrValue<long>());
//ZSCAN key cursor [MATCH pattern] [COUNT count]
public Task<decimal?> ZScoreAsync(string key, string member) => CallAsync("ZSCORE".InputKey(key, member), rt => rt.ThrowOrValue<decimal?>());
public Task<long> ZUnionStoreAsync(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null) => ZStoreAsync(false, destination, keys, weights, aggregate);
Task<long> ZStoreAsync(bool inter, string destination, string[] keys, int[] weights, ZAggregate? aggregate) => CallAsync((inter ? "ZINTERSTORE" : "ZUNIONSTORE")
.InputKey(destination, keys?.Length ?? 0)
.InputKey(keys)
.InputIf(weights?.Any() == true, weights)
.InputIf(aggregate != null, "AGGREGATE", aggregate ?? ZAggregate.max), rt => rt
.ThrowOrValue<long>());
#endregion
#endif
public ZMember BZPopMin(string key, int timeoutSeconds) => BZPop(false, new[] { key }, timeoutSeconds)?.value;
public KeyValue<ZMember> BZPopMin(string[] keys, int timeoutSeconds) => BZPop(false, keys, timeoutSeconds);
public ZMember BZPopMax(string key, int timeoutSeconds) => BZPop(true, new[] { key }, timeoutSeconds)?.value;
public KeyValue<ZMember> BZPopMax(string[] keys, int timeoutSeconds) => BZPop(true, keys, timeoutSeconds);
KeyValue<ZMember> BZPop(bool ismax, string[] keys, int timeoutSeconds) => Call((ismax ? "BZPOPMAX" : "BZPOPMIN")
.InputKey(keys, timeoutSeconds), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? null : new KeyValue<ZMember>(a[0].ConvertTo<string>(), new ZMember(a[1].ConvertTo<string>(), a[2].ConvertTo<decimal>().ConvertTo<decimal>()))));
public long ZAdd(string key, decimal score, string member, params object[] scoreMembers) => ZAdd<long>(key, false, false, null, false, false, score, member, scoreMembers);
public long ZAdd(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false) => ZAdd<long>(key, false, false, than, ch, false, scoreMembers);
public long ZAddNx(string key, decimal score, string member, params object[] scoreMembers) => ZAdd<long>(key, true, false, null, false, false, score, member, scoreMembers);
public long ZAddNx(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false) => ZAdd<long>(key, true, false, than, ch, false, scoreMembers);
public long ZAddXx(string key, decimal score, string member, params object[] scoreMembers) => ZAdd<long>(key, false, true, null, false, false, score, member, scoreMembers);
public long ZAddXx(string key, ZMember[] scoreMembers, ZAddThan? than = null, bool ch = false) => ZAdd<long>(key, false, true, than, ch, false, scoreMembers);
T ZAdd<T>(string key, bool nx, bool xx, ZAddThan? than, bool ch, bool incr, decimal score, string member, params object[] scoreMembers)
{
if (scoreMembers?.Length > 0)
{
var members = scoreMembers.MapToList((sco, mem) => new ZMember(mem.ConvertTo<string>(), sco.ConvertTo<decimal>()));
members.Insert(0, new ZMember(member, score));
return ZAdd<T>(key, nx, xx, than, ch, incr, members);
}
return ZAdd<T>(key, nx, xx, than, ch, incr, new[] { new ZMember(member, score) });
}
TReturn ZAdd<TReturn>(string key, bool nx, bool xx, ZAddThan? than, bool ch, bool incr, IEnumerable<ZMember> scoreMembers)
{
var cmd = "ZADD"
.InputKey(key)
.InputIf(nx, "NX")
.InputIf(xx, "XX")
.InputIf(than != null, than)
.InputIf(ch, "CH")
.InputIf(incr, "INCR");
foreach (var sm in scoreMembers) cmd.InputRaw(sm.score).InputRaw(sm.member);
return Call(cmd, rt => rt.ThrowOrValue<TReturn>());
}
public long ZCard(string key) => Call("ZCARD".InputKey(key), rt => rt.ThrowOrValue<long>());
public long ZCount(string key, decimal min, decimal max) => Call("ZCOUNT".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public long ZCount(string key, string min, string max) => Call("ZCOUNT".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public decimal ZIncrBy(string key, decimal increment, string member) => Call("ZINCRBY".InputKey(key, increment, member), rt => rt.ThrowOrValue<decimal>());
public long ZInterStore(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null) => ZStore(true, destination, keys, weights, aggregate);
public long ZLexCount(string key, string min, string max) => Call("ZLEXCOUNT".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public ZMember ZPopMin(string key) => ZPop(false, key);
public ZMember[] ZPopMin(string key, int count) => ZPop(false, key, count);
public ZMember ZPopMax(string key) => ZPop(true, key);
public ZMember[] ZPopMax(string key, int count) => ZPop(true, key, count);
ZMember ZPop(bool ismax, string key) => Call((ismax ? "ZPOPMAX" : "ZPOPMIN").InputKey(key), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? null : new ZMember(a[0].ConvertTo<string>(), a[1].ConvertTo<decimal>())));
ZMember[] ZPop(bool ismax, string key, int count) => Call((ismax ? "ZPOPMAX" : "ZPOPMIN").InputKey(key, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public string[] ZRange(string key, decimal start, decimal stop) => Call("ZRANGE".InputKey(key, start, stop), rt => rt.ThrowOrValue<string[]>());
public ZMember[] ZRangeWithScores(string key, decimal start, decimal stop) => Call("ZRANGE"
.InputKey(key, start, stop)
.Input("WITHSCORES"), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public string[] ZRangeByLex(string key, string min, string max, int offset = 0, int count = 0) => Call("ZRANGEBYLEX"
.InputKey(key, min, max)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public string[] ZRangeByScore(string key, decimal min, decimal max, int offset = 0, int count = 0) => Call("ZRANGEBYSCORE"
.InputKey(key, min, max)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public string[] ZRangeByScore(string key, string min, string max, int offset = 0, int count = 0) => Call("ZRANGEBYSCORE"
.InputKey(key, min, max)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public ZMember[] ZRangeByScoreWithScores(string key, decimal min, decimal max, int offset = 0, int count = 0) => Call("ZRANGEBYSCORE"
.InputKey(key, min, max)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public ZMember[] ZRangeByScoreWithScores(string key, string min, string max, int offset = 0, int count = 0) => Call("ZRANGEBYSCORE"
.InputKey(key, min, max)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public long? ZRank(string key, string member) => Call("ZRANK".InputKey(key, member), rt => rt.ThrowOrValue<long?>());
public long ZRem(string key, params string[] members) => Call("ZREM".InputKey(key, members), rt => rt.ThrowOrValue<long>());
public long ZRemRangeByLex(string key, string min, string max) => Call("ZREMRANGEBYLEX".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public long ZRemRangeByRank(string key, long start, long stop) => Call("ZREMRANGEBYRANK".InputKey(key, start, stop), rt => rt.ThrowOrValue<long>());
public long ZRemRangeByScore(string key, decimal min, decimal max) => Call("ZREMRANGEBYSCORE".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public long ZRemRangeByScore(string key, string min, string max) => Call("ZREMRANGEBYSCORE".InputKey(key, min, max), rt => rt.ThrowOrValue<long>());
public string[] ZRevRange(string key, decimal start, decimal stop) => Call("ZREVRANGE".InputKey(key, start, stop), rt => rt.ThrowOrValue<string[]>());
public ZMember[] ZRevRangeWithScores(string key, decimal start, decimal stop) => Call("ZREVRANGE"
.InputKey(key, start, stop)
.Input("WITHSCORES"), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public string[] ZRevRangeByLex(string key, decimal max, decimal min, int offset = 0, int count = 0) => Call("ZREVRANGEBYLEX"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public string[] ZRevRangeByLex(string key, string max, string min, int offset = 0, int count = 0) => Call("ZREVRANGEBYLEX"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public string[] ZRevRangeByScore(string key, decimal max, decimal min, int offset = 0, int count = 0) => Call("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public string[] ZRevRangeByScore(string key, string max, string min, int offset = 0, int count = 0) => Call("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt.ThrowOrValue<string[]>());
public ZMember[] ZRevRangeByScoreWithScores(string key, decimal max, decimal min, int offset = 0, int count = 0) => Call("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public ZMember[] ZRevRangeByScoreWithScores(string key, string max, string min, int offset = 0, int count = 0) => Call("ZREVRANGEBYSCORE"
.InputKey(key, max, min)
.Input("WITHSCORES")
.InputIf(offset > 0 || count > 0, "LIMIT", offset, count), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
public long ZRevRank(string key, string member) => Call("ZREVRANK".InputKey(key, member), rt => rt.ThrowOrValue<long>());
//ZSCAN key cursor [MATCH pattern] [COUNT count]
public decimal? ZScore(string key, string member) => Call("ZSCORE".InputKey(key, member), rt => rt.ThrowOrValue<decimal?>());
public long ZUnionStore(string destination, string[] keys, int[] weights = null, ZAggregate? aggregate = null) => ZStore(false, destination, keys, weights, aggregate);
long ZStore(bool inter, string destination, string[] keys, int[] weights, ZAggregate? aggregate) => Call((inter ? "ZINTERSTORE" : "ZUNIONSTORE")
.InputKey(destination, keys?.Length ?? 0)
.InputKey(keys)
.InputIf(weights?.Any() == true, weights)
.InputIf(aggregate != null, "AGGREGATE", aggregate ?? ZAggregate.max), rt => rt
.ThrowOrValue<long>());
/// <summary>
/// 随机返回N个元素
/// <para>Redis 6.2.0+以上才支持该命令</para>
/// </summary>
/// <param name="key">Key</param>
/// <param name="count">返回的个数</param>
/// <param name="repetition">是否允许有重复元素返回</param>
/// <returns></returns>
public string[] ZRandMember(string key, int count, bool repetition) => Call("ZRANDMEMBER".InputKey(key, repetition ? -count : count), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// 随机返回N个元素, 包含分数
/// <para>Redis 6.2.0+以上才支持该命令</para>
/// </summary>
/// <param name="key">Key</param>
/// <param name="count">返回的个数</param>
/// <param name="repetition">是否允许有重复元素返回</param>
/// <returns></returns>
public ZMember[] ZRandMemberWithScores(string key, int count, bool repetition) => Call("ZRANDMEMBER"
.InputKey(key, repetition ? -count : count)
.Input("WITHSCORES"), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new ZMember[0] : a.MapToHash<decimal>(rt.Encoding).Select(b => new ZMember(b.Key, b.Value)).ToArray()));
/// <summary>
/// ZSCAN key cursor [MATCH pattern] [COUNT count]
/// </summary>
/// <param name="key"></param>
/// <param name="cursor"></param>
/// <param name="pattern"></param>
/// <param name="count"></param>
/// <returns></returns>
public ScanResult<ZMember> ZScan(string key, long cursor, string pattern, long count = 0) => Call("ZSCAN"
.InputKey(key, cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<ZMember>(a[0].ConvertTo<long>(),
a[1] == null ? new ZMember[0] :
((object[])a[1]).MapToList((k, v) => new ZMember(k.ConvertTo<string>(), v.ConvertTo<decimal>())).ToArray())));
public IEnumerable<ZMember[]> ZScan(string key, string pattern, long count) => new ScanCollection<ZMember>(this, "zscan", (cli, cursor) => cli.ZScan(key, cursor, pattern, count));
}
public class ZMember
{
public readonly string member;
public readonly decimal score;
public ZMember(string member, decimal score) { this.member = member; this.score = score; }
}
public enum ZAggregate { sum, min, max }
}
|
2881099/FreeRedis | 2,692 | src/FreeRedis/RedisClient/Scripting.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<object> EvalAsync(string script, string[] keys = null, params object[] arguments) => CallAsync("EVAL"
.Input(script, keys?.Length ?? 0)
.InputKeyIf(keys?.Any() == true, keys)
.Input(arguments), rt => rt.ThrowOrValue());
public Task<object> EvalShaAsync(string sha1, string[] keys = null, params object[] arguments) => CallAsync("EVALSHA"
.Input(sha1, keys?.Length ?? 0)
.InputKeyIf(keys?.Any() == true, keys)
.Input(arguments), rt => rt.ThrowOrValue());
public Task<bool> ScriptExistsAsync(string sha1) => CallAsync("SCRIPT".SubCommand("EXISTS").InputRaw(sha1), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo<bool>()));
public Task<bool[]> ScriptExistsAsync(string[] sha1) => CallAsync("SCRIPT".SubCommand("EXISTS").Input(sha1), rt => rt.ThrowOrValue<bool[]>());
public Task ScriptFlushAsync() => CallAsync("SCRIPT".SubCommand("FLUSH"), rt => rt.ThrowOrNothing());
public Task ScriptKillAsync() => CallAsync("SCRIPT".SubCommand("KILL"), rt => rt.ThrowOrNothing());
public Task<string> ScriptLoadAsync(string script) => CallAsync("SCRIPT".SubCommand("LOAD").InputRaw(script), rt => rt.ThrowOrValue<string>());
#endregion
#endif
public object Eval(string script, string[] keys = null, params object[] arguments) => Call("EVAL"
.Input(script, keys?.Length ?? 0)
.InputKeyIf(keys?.Any() == true, keys)
.Input(arguments), rt => rt.ThrowOrValue());
public object EvalSha(string sha1, string[] keys = null, params object[] arguments) => Call("EVALSHA"
.Input(sha1, keys?.Length ?? 0)
.InputKeyIf(keys?.Any() == true, keys)
.Input(arguments), rt => rt.ThrowOrValue());
public bool ScriptExists(string sha1) => Call("SCRIPT".SubCommand("EXISTS").InputRaw(sha1), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo<bool>()));
public bool[] ScriptExists(string[] sha1) => Call("SCRIPT".SubCommand("EXISTS").Input(sha1), rt => rt.ThrowOrValue<bool[]>());
public void ScriptFlush() => Call("SCRIPT".SubCommand("FLUSH"), rt => rt.ThrowOrNothing());
public void ScriptKill() => Call("SCRIPT".SubCommand("KILL"), rt => rt.ThrowOrNothing());
public string ScriptLoad(string script) => Call("SCRIPT".SubCommand("LOAD").InputRaw(script), rt => rt.ThrowOrValue<string>());
}
}
|
2881099/FreeRedis | 1,240 | src/FreeRedis/RedisClient/HyperLogLog.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<bool> PfAddAsync(string key, params object[] elements) => CallAsync("PFADD".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<bool>());
public Task<long> PfCountAsync(params string[] keys) => CallAsync("PFCOUNT".InputKey(keys), rt => rt.ThrowOrValue<long>());
public Task PfMergeAsync(string destkey, params string[] sourcekeys) => CallAsync("PFMERGE".InputKey(destkey).InputKey(sourcekeys), rt => rt.ThrowOrValue<string>());
#endregion
#endif
public bool PfAdd(string key, params object[] elements) => Call("PFADD".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<bool>());
public long PfCount(params string[] keys) => Call("PFCOUNT".InputKey(keys), rt => rt.ThrowOrValue<long>());
public void PfMerge(string destkey, params string[] sourcekeys) => Call("PFMERGE".InputKey(destkey).InputKey(sourcekeys), rt => rt.ThrowOrValue<string>());
}
}
|
2881099/FreeRedis | 11,159 | src/FreeRedis/RedisClient/Hashes.cs | using FreeRedis.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<long> HDelAsync(string key, params string[] fields) => CallAsync("HDEL".InputKey(key, fields), rt => rt.ThrowOrValue<long>());
public Task<bool> HExistsAsync(string key, string field) => CallAsync("HEXISTS".InputKey(key, field), rt => rt.ThrowOrValue<bool>());
public Task<string> HGetAsync(string key, string field) => CallAsync("HGET".InputKey(key, field), rt => rt.ThrowOrValue<string>());
public Task<T> HGetAsync<T>(string key, string field) => CallAsync("HGET".InputKey(key, field).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<Dictionary<string, string>> HGetAllAsync(string key) => CallAsync("HGETALL".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
public Task<Dictionary<string, T>> HGetAllAsync<T>(string key) => CallAsync("HGETALL".InputKey(key).FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) =>
{
for (var x = 0; x < a.Length; x += 2)
{
a[x] = rt.Encoding.GetString(a[x].ConvertTo<byte[]>());
a[x + 1] = DeserializeRedisValue<T>(a[x + 1].ConvertTo<byte[]>(), rt.Encoding);
}
return a.MapToHash<T>(rt.Encoding);
}));
public Task<long> HIncrByAsync(string key, string field, long increment) => CallAsync("HINCRBY".InputKey(key, field, increment), rt => rt.ThrowOrValue<long>());
public Task<decimal> HIncrByFloatAsync(string key, string field, decimal increment) => CallAsync("HINCRBYFLOAT".InputKey(key, field, increment), rt => rt.ThrowOrValue<decimal>());
public Task<string[]> HKeysAsync(string key) => CallAsync("HKEYS".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public Task<long> HLenAsync(string key) => CallAsync("HLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public Task<string[]> HMGetAsync(string key, params string[] fields) => CallAsync("HMGET".InputKey(key, fields), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> HMGetAsync<T>(string key, params string[] fields) => HReadArrayAsync<T>("HMGET".InputKey(key, fields));
public Task HMSetAsync<T>(string key, string field, T value, params object[] fieldValues) => HSetAsync(true, key, field, value, fieldValues);
public Task HMSetAsync<T>(string key, Dictionary<string, T> keyValues) => CallAsync("HMSET".InputKey(key).InputKv(keyValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
public Task<ScanResult<KeyValuePair<string, string>>> HScanAsync(string key, long cursor, string pattern, long count) => CallAsync("HSCAN"
.InputKey(key, cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<KeyValuePair<string, string>>(a[0].ConvertTo<long>(),
a[1].ConvertTo<string[]>().MapToList((k, v) => new KeyValuePair<string, string>(k.ConvertTo<string>(), v.ConvertTo<string>())).ToArray())));
public Task<ScanResult<KeyValuePair<string, T>>> HScanAsync<T>(string key, long cursor, string pattern, long count) => CallAsync("HSCAN"
.InputKey(key, cursor)
.FlagReadbytes(true)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<KeyValuePair<string, T>>(a[0].ConvertTo<long>(),
a[1].ConvertTo<byte[][]>().MapToList((k, v) => new KeyValuePair<string, T>(k.ConvertTo<string>(), DeserializeRedisValue<T>(v.ConvertTo<byte[]>(), rt.Encoding))).ToArray())));
public Task<long> HSetAsync<T>(string key, string field, T value, params object[] fieldValues) => HSetAsync(false, key, field, value, fieldValues);
public Task<long> HSetAsync<T>(string key, Dictionary<string, T> keyValues) => CallAsync("HSET".InputKey(key).InputKv(keyValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<long>());
Task<long> HSetAsync<T>(bool hmset, string key, string field, T value, params object[] fieldValues)
{
if (fieldValues?.Any() == true)
return CallAsync((hmset ? "HMSET" : "HSET").InputKey(key, field).InputRaw(SerializeRedisValue(value))
.InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<long>());
return CallAsync((hmset ? "HMSET" : "HSET").InputKey(key, field).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
}
public Task<bool> HSetNxAsync<T>(string key, string field, T value) => CallAsync("HSETNX".InputKey(key, field).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<bool>());
public Task<long> HStrLenAsync(string key, string field) => CallAsync("HSTRLEN".InputKey(key, field), rt => rt.ThrowOrValue<long>());
public Task<string[]> HValsAsync(string key) => CallAsync("HVALS".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> HValsAsync<T>(string key) => HReadArrayAsync<T>("HVALS".InputKey(key));
Task<T[]> HReadArrayAsync<T>(CommandPacket cb) => CallAsync(cb.FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
#endregion
#endif
public long HDel(string key, params string[] fields) => Call("HDEL".InputKey(key, fields), rt => rt.ThrowOrValue<long>());
public bool HExists(string key, string field) => Call("HEXISTS".InputKey(key, field), rt => rt.ThrowOrValue<bool>());
public string HGet(string key, string field) => Call("HGET".InputKey(key, field), rt => rt.ThrowOrValue<string>());
public T HGet<T>(string key, string field) => Call("HGET".InputKey(key, field).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Dictionary<string, string> HGetAll(string key) => Call("HGETALL".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
public Dictionary<string, T> HGetAll<T>(string key) => Call("HGETALL".InputKey(key).FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) =>
{
for (var x = 0; x < a.Length; x += 2)
{
a[x] = rt.Encoding.GetString(a[x].ConvertTo<byte[]>());
a[x + 1] = DeserializeRedisValue<T>(a[x + 1].ConvertTo<byte[]>(), rt.Encoding);
}
return a.MapToHash<T>(rt.Encoding);
}));
public long HIncrBy(string key, string field, long increment) => Call("HINCRBY".InputKey(key, field, increment), rt => rt.ThrowOrValue<long>());
public decimal HIncrByFloat(string key, string field, decimal increment) => Call("HINCRBYFLOAT".InputKey(key, field, increment), rt => rt.ThrowOrValue<decimal>());
public string[] HKeys(string key) => Call("HKEYS".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public long HLen(string key) => Call("HLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public string[] HMGet(string key, params string[] fields) => Call("HMGET".InputKey(key, fields), rt => rt.ThrowOrValue<string[]>());
public T[] HMGet<T>(string key, params string[] fields) => HReadArray<T>("HMGET".InputKey(key, fields));
public void HMSet<T>(string key, string field, T value, params object[] fieldValues) => HSet(true, key, field, value, fieldValues);
public void HMSet<T>(string key, Dictionary<string, T> keyValues) => Call("HMSET".InputKey(key).InputKv(keyValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
public ScanResult<KeyValuePair<string, string>> HScan(string key, long cursor, string pattern, long count) => Call("HSCAN"
.InputKey(key, cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<KeyValuePair<string, string>>(a[0].ConvertTo<long>(),
a[1].ConvertTo<string[]>().MapToList((k, v) => new KeyValuePair<string, string>(k.ConvertTo<string>(), v.ConvertTo<string>())).ToArray())));
public ScanResult<KeyValuePair<string, T>> HScan<T>(string key, long cursor, string pattern, long count) => Call("HSCAN"
.InputKey(key, cursor)
.FlagReadbytes(true)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<KeyValuePair<string, T>>(a[0].ConvertTo<long>(),
a[1].ConvertTo<byte[][]>().MapToList((k, v) => new KeyValuePair<string, T>(k.ConvertTo<string>(), DeserializeRedisValue<T>(v.ConvertTo<byte[]>(), rt.Encoding))).ToArray())));
public IEnumerable<KeyValuePair<string, string>[]> HScan(string key, string pattern, long count) => new ScanCollection<KeyValuePair<string, string>>(this, "hscan", (cli, cursor) => cli.HScan(key, cursor, pattern, count));
public IEnumerable<KeyValuePair<string, T>[]> HScan<T>(string key, string pattern, long count) => new ScanCollection<KeyValuePair<string, T>>(this, "hscan", (cli, cursor) => cli.HScan<T>(key, cursor, pattern, count));
public long HSet<T>(string key, string field, T value, params object[] fieldValues) => HSet(false, key, field, value, fieldValues);
public long HSet<T>(string key, Dictionary<string, T> keyValues) => Call("HSET".InputKey(key).InputKv(keyValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<long>());
long HSet<T>(bool hmset, string key, string field, T value, params object[] fieldValues)
{
if (fieldValues?.Any() == true)
return Call((hmset ? "HMSET" : "HSET").InputKey(key, field).InputRaw(SerializeRedisValue(value))
.InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<long>());
return Call((hmset ? "HMSET" : "HSET").InputKey(key, field).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
}
public bool HSetNx<T>(string key, string field, T value) => Call("HSETNX".InputKey(key, field).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<bool>());
public long HStrLen(string key, string field) => Call("HSTRLEN".InputKey(key, field), rt => rt.ThrowOrValue<long>());
public string[] HVals(string key) => Call("HVALS".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public T[] HVals<T>(string key) => HReadArray<T>("HVALS".InputKey(key));
T[] HReadArray<T>(CommandPacket cb) => Call(cb.FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
}
}
|
2881099/FreeRedis | 13,051 | src/FreeRedis/RedisClient/Lists.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string> BLPopAsync(string key, int timeoutSeconds) => CallAsync("BLPOP".InputKey(key, timeoutSeconds), rt => rt.ThrowOrValue((a, _) => a.LastOrDefault().ConvertTo<string>()));
async public Task<T> BLPopAsync<T>(string key, int timeoutSeconds)
{
var kv = await BLRPopAsync<T>("BLPOP", new[] { key }, timeoutSeconds);
if (kv == null) return default(T);
return kv.value;
}
public Task<KeyValue<string>> BLPopAsync(string[] keys, int timeoutSeconds) => BLRPopAsync<string>("BLPOP", keys, timeoutSeconds);
public Task<KeyValue<T>> BLPopAsync<T>(string[] keys, int timeoutSeconds) => BLRPopAsync<T>("BLPOP", keys, timeoutSeconds);
public Task<string> BRPopAsync(string key, int timeoutSeconds) => CallAsync("BRPOP".InputKey(key, timeoutSeconds), rt => rt.ThrowOrValue((a, _) => a.LastOrDefault().ConvertTo<string>()));
async public Task<T> BRPopAsync<T>(string key, int timeoutSeconds)
{
var kv = await BLRPopAsync<T>("BRPOP", new[] { key }, timeoutSeconds);
if (kv == null) return default(T);
return kv.value;
}
public Task<KeyValue<string>> BRPopAsync(string[] keys, int timeoutSeconds) => BLRPopAsync<string>("BRPOP", keys, timeoutSeconds);
public Task<KeyValue<T>> BRPopAsync<T>(string[] keys, int timeoutSeconds) => BLRPopAsync<T>("BRPOP", keys, timeoutSeconds);
Task<KeyValue<T>> BLRPopAsync<T>(string cmd, string[] keys, int timeoutSeconds) => CallAsync(cmd.InputKey(keys, timeoutSeconds).FlagReadbytes(true), rt => rt.ThrowOrValue((a, _) =>
a?.Length != 2 ? null : new KeyValue<T>(rt.Encoding.GetString(a.FirstOrDefault().ConvertTo<byte[]>()), DeserializeRedisValue<T>(a.LastOrDefault().ConvertTo<byte[]>(), rt.Encoding))));
public Task<string> BRPopLPushAsync(string source, string destination, int timeoutSeconds) => CallAsync("BRPOPLPUSH"
.InputKey(source).InputKey(destination)
.InputRaw(timeoutSeconds), rt => rt.ThrowOrValue<string>());
public Task<T> BRPopLPushAsync<T>(string source, string destination, int timeoutSeconds) => CallAsync("BRPOPLPUSH"
.InputKey(source).InputKey(destination)
.InputRaw(timeoutSeconds)
.FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<string> LIndexAsync(string key, long index) => CallAsync("LINDEX".InputKey(key, index), rt => rt.ThrowOrValue<string>());
public Task<T> LIndexAsync<T>(string key, long index) => CallAsync("LINDEX".InputKey(key, index).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<long> LInsertAsync(string key, InsertDirection direction, object pivot, object element) => CallAsync("LINSERT"
.InputKey(key)
.InputRaw(direction)
.InputRaw(SerializeRedisValue(pivot))
.InputRaw(SerializeRedisValue(element)), rt => rt.ThrowOrValue<long>());
public Task<long> LLenAsync(string key) => CallAsync("LLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public Task<string> LPopAsync(string key) => CallAsync("LPOP".InputKey(key), rt => rt.ThrowOrValue<string>());
public Task<T> LPopAsync<T>(string key) => CallAsync("LPOP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<long> LPosAsync<T>(string key, T element, int rank = 0) => CallAsync("LPOS"
.InputKey(key)
.InputRaw(SerializeRedisValue(element))
.InputIf(rank != 0, "RANK", rank), rt => rt.ThrowOrValue<long>());
public Task<long[]> LPosAsync<T>(string key, T element, int rank, int count, int maxLen) => CallAsync("LPOS"
.InputKey(key)
.InputRaw(SerializeRedisValue(element))
.InputIf(rank != 0, "RANK", rank)
.Input("COUNT", count)
.InputIf(maxLen != 0, "MAXLEN ", maxLen), rt => rt.ThrowOrValue<long[]>());
public Task<long> LPushAsync(string key, params object[] elements) => CallAsync("LPUSH".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<long> LPushXAsync(string key, params object[] elements) => CallAsync("LPUSHX".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<string[]> LRangeAsync(string key, long start, long stop) => CallAsync("LRANGE".InputKey(key, start, stop), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> LRangeAsync<T>(string key, long start, long stop) => CallAsync("LRANGE".InputKey(key, start, stop).FlagReadbytes(true), rt => rt.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
public Task<long> LRemAsync<T>(string key, long count, T element) => CallAsync("LREM".InputKey(key, count).InputRaw(SerializeRedisValue(element)), rt => rt.ThrowOrValue<long>());
public Task LSetAsync<T>(string key, long index, T element) => CallAsync("LSET".InputKey(key, index).InputRaw(SerializeRedisValue(element)), rt => rt.ThrowOrValue<string>());
public Task LTrimAsync(string key, long start, long stop) => CallAsync("LTRIM".InputKey(key, start, stop), rt => rt.ThrowOrValue<string>());
public Task<string> RPopAsync(string key) => CallAsync("RPOP".InputKey(key), rt => rt.ThrowOrValue<string>());
public Task<T> RPopAsync<T>(string key) => CallAsync("RPOP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<string> RPopLPushAsync(string source, string destination) => CallAsync("RPOPLPUSH".InputKey(source).InputKey(destination), rt => rt.ThrowOrValue<string>());
public Task<T> RPopLPushAsync<T>(string source, string destination) => CallAsync("RPOPLPUSH".InputKey(source).InputKey(destination).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<long> RPushAsync(string key, params object[] elements) => CallAsync("RPUSH".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<long> RPushXAsync(string key, params object[] elements) => CallAsync("RPUSHX".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
#endregion
#endif
public string BLPop(string key, int timeoutSeconds) => Call("BLPOP".InputKey(key, timeoutSeconds), rt => rt.ThrowOrValue((a, _) => a.LastOrDefault().ConvertTo<string>()));
public T BLPop<T>(string key, int timeoutSeconds)
{
var kv = BLRPop<T>("BLPOP", new[] { key }, timeoutSeconds);
if (kv == null) return default(T);
return kv.value;
}
public KeyValue<string> BLPop(string[] keys, int timeoutSeconds) => BLRPop<string>("BLPOP", keys, timeoutSeconds);
public KeyValue<T> BLPop<T>(string[] keys, int timeoutSeconds) => BLRPop<T>("BLPOP", keys, timeoutSeconds);
public string BRPop(string key, int timeoutSeconds) => Call("BRPOP".InputKey(key, timeoutSeconds), rt => rt.ThrowOrValue((a, _) => a.LastOrDefault().ConvertTo<string>()));
public T BRPop<T>(string key, int timeoutSeconds)
{
var kv = BLRPop<T>("BRPOP", new[] { key }, timeoutSeconds);
if (kv == null) return default(T);
return kv.value;
}
public KeyValue<string> BRPop(string[] keys, int timeoutSeconds) => BLRPop<string>("BRPOP", keys, timeoutSeconds);
public KeyValue<T> BRPop<T>(string[] keys, int timeoutSeconds) => BLRPop<T>("BRPOP", keys, timeoutSeconds);
KeyValue<T> BLRPop<T>(string cmd, string[] keys, int timeoutSeconds) => Call(cmd.InputKey(keys, timeoutSeconds).FlagReadbytes(true), rt => rt.ThrowOrValue((a, _) =>
a?.Length != 2 ? null : new KeyValue<T>(rt.Encoding.GetString(a.FirstOrDefault().ConvertTo<byte[]>()), DeserializeRedisValue<T>(a.LastOrDefault().ConvertTo<byte[]>(), rt.Encoding))));
public string BRPopLPush(string source, string destination, int timeoutSeconds) => Call("BRPOPLPUSH"
.InputKey(source).InputKey(destination)
.InputRaw(timeoutSeconds), rt => rt.ThrowOrValue<string>());
public T BRPopLPush<T>(string source, string destination, int timeoutSeconds) => Call("BRPOPLPUSH"
.InputKey(source).InputKey(destination)
.InputRaw(timeoutSeconds)
.FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public string LIndex(string key, long index) => Call("LINDEX".InputKey(key, index), rt => rt.ThrowOrValue<string>());
public T LIndex<T>(string key, long index) => Call("LINDEX".InputKey(key, index).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public long LInsert(string key, InsertDirection direction, object pivot, object element) => Call("LINSERT"
.InputKey(key)
.InputRaw(direction)
.InputRaw(SerializeRedisValue(pivot))
.InputRaw(SerializeRedisValue(element)), rt => rt.ThrowOrValue<long>());
public long LLen(string key) => Call("LLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public string LPop(string key) => Call("LPOP".InputKey(key), rt => rt.ThrowOrValue<string>());
public T LPop<T>(string key) => Call("LPOP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public long LPos<T>(string key, T element, int rank = 0) => Call("LPOS"
.InputKey(key)
.InputRaw(SerializeRedisValue(element))
.InputIf(rank != 0, "RANK", rank), rt => rt.ThrowOrValue<long>());
public long[] LPos<T>(string key, T element, int rank, int count, int maxLen) => Call("LPOS"
.InputKey(key)
.InputRaw(SerializeRedisValue(element))
.InputIf(rank != 0, "RANK", rank)
.Input("COUNT", count)
.InputIf(maxLen != 0, "MAXLEN ", maxLen), rt => rt.ThrowOrValue<long[]>());
public long LPush(string key, params object[] elements) => Call("LPUSH".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public long LPushX(string key, params object[] elements) => Call("LPUSHX".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public string[] LRange(string key, long start, long stop) => Call("LRANGE".InputKey(key, start, stop), rt => rt.ThrowOrValue<string[]>());
public T[] LRange<T>(string key, long start, long stop) => Call("LRANGE".InputKey(key, start, stop).FlagReadbytes(true), rt => rt.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
public long LRem<T>(string key, long count, T element) => Call("LREM".InputKey(key, count).InputRaw(SerializeRedisValue(element)), rt => rt.ThrowOrValue<long>());
public void LSet<T>(string key, long index, T element) => Call("LSET".InputKey(key, index).InputRaw(SerializeRedisValue(element)), rt => rt.ThrowOrValue<string>());
public void LTrim(string key, long start, long stop) => Call("LTRIM".InputKey(key, start, stop), rt => rt.ThrowOrValue<string>());
public string RPop(string key) => Call("RPOP".InputKey(key), rt => rt.ThrowOrValue<string>());
public T RPop<T>(string key) => Call("RPOP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public string RPopLPush(string source, string destination) => Call("RPOPLPUSH".InputKey(source).InputKey(destination), rt => rt.ThrowOrValue<string>());
public T RPopLPush<T>(string source, string destination) => Call("RPOPLPUSH".InputKey(source).InputKey(destination).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public long RPush(string key, params object[] elements) => Call("RPUSH".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public long RPushX(string key, params object[] elements) => Call("RPUSHX".InputKey(key).Input(elements.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
}
}
|
2881099/FreeRedis | 3,593 | src/FreeRedis/RedisClient/Cluster.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace FreeRedis
{
partial class RedisClient
{
//wait testing
//public string ClusterAddSlots(params int[] slot) => Call("CLUSTER".SubCommand("ADDSLOTS").Input(slot), rt => rt.ThrowOrValue<string>());
//public string ClusterBumpEpoch() => Call("CLUSTER".SubCommand("BUMPEPOCH"), rt => rt.ThrowOrValue<string>());
//public long ClusterCountFailureReports(string nodeid) => Call("CLUSTER".SubCommand("COUNT-FAILURE-REPORTS").InputRaw(nodeid), rt => rt.ThrowOrValue<long>());
//public long ClusterCountKeysInSlot(int slot) => Call("CLUSTER".SubCommand("COUNTKEYSINSLOT").InputRaw(slot), rt => rt.ThrowOrValue<long>());
//public string ClusterDelSlots(params int[] slot) => Call("CLUSTER".SubCommand("DELSLOTS").Input(slot), rt => rt.ThrowOrValue<string>());
//public string ClusterFailOver(ClusterFailOverType type) => Call("CLUSTER".SubCommand("FAILOVER").InputRaw(type), rt => rt.ThrowOrValue<string>());
//public string ClusterFlushSlots() => Call("CLUSTER".SubCommand("FLUSHSLOTS"), rt => rt.ThrowOrValue<string>());
//public long ClusterForget(string nodeid) => Call("CLUSTER".SubCommand("FORGET").InputRaw(nodeid), rt => rt.ThrowOrValue<long>());
//public string[] ClusterGetKeysInSlot(int slot) => Call("CLUSTER".SubCommand("GETKEYSINSLOT").InputRaw(slot), rt => rt.ThrowOrValue<string[]>());
//public Dictionary<string, string> ClusterInfo() => Call("CLUSTER".SubCommand("INFO"), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
//public int ClusterKeySlot(string key) => Call("CLUSTER".SubCommand("KEYSLOT").InputRaw(key), rt => rt.ThrowOrValue<int>());
//public string ClusterMeet(string ip, int port) => Call("CLUSTER".SubCommand("MEET").Input(ip, port), rt => rt.ThrowOrValue<string>());
//public string ClusterMyId() => Call("CLUSTER".SubCommand("MYID"), rt => rt.ThrowOrValue<string>());
//public string ClusterNodes() => Call("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>());
//public string ClusterReplicas(string nodeid) => Call("CLUSTER".SubCommand("REPLICAS").InputRaw(nodeid), rt => rt.ThrowOrValue<string>());
//public string ClusterReplicate(string nodeid) => Call("CLUSTER".SubCommand("REPLICATE").InputRaw(nodeid), rt => rt.ThrowOrValue<string>());
//public string ClusterReset(ClusterResetType type) => Call("CLUSTER".SubCommand("RESET").InputRaw(type), rt => rt.ThrowOrValue<string>());
//public string ClusterSaveConfig() => Call("CLUSTER".SubCommand("SAVECONFIG"), rt => rt.ThrowOrValue<string>());
//public string ClusterSetConfigEpoch(string epoch) => Call("CLUSTER".SubCommand("SET-CONFIG-EPOCH").InputRaw(epoch), rt => rt.ThrowOrValue<string>());
//public string[] ClusterSetSlot(int slot, ClusterSetSlotType type, string nodeid = null) => Call("CLUSTER".SubCommand("SETSLOT")
// .Input(slot, type)
// .InputIf(!string.IsNullOrWhiteSpace(nodeid), nodeid), rt => rt.ThrowOrValue<string[]>());
//public string ClusterSlaves(string nodeid) => Call("CLUSTER".SubCommand("SLAVES").InputRaw(nodeid), rt => rt.ThrowOrValue<string>());
//public object ClusterSlots() => Call("CLUSTER".SubCommand("SLOTS"), rt => rt.ThrowOrValue<object>());
//public string ReadOnly() => Call("READONLY", rt => rt.ThrowOrValue<string>());
//public string ReadWrite() => Call("READWRITE", rt => rt.ThrowOrValue<string>());
}
}
|
2881099/FreeRedis | 31,933 | src/FreeRedis/RedisClient/Streams.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<long> XAckAsync(string key, string group, params string[] id) => CallAsync("XACK".InputKey(key, group).Input(id), rt => rt.ThrowOrValue<long>());
public Task<string> XAddAsync<T>(string key, string field, T value, params object[] fieldValues) => XAddAsync(key, 0, "*", field, value, fieldValues);
public Task<string> XAddAsync<T>(string key, long maxlen, string id, string field, T value, params object[] fieldValues) => CallAsync("XADD"
.InputKey(key)
.InputIf(maxlen > 0, "MAXLEN", maxlen)
.InputIf(maxlen < 0, "MAXLEN", "~", Math.Abs(maxlen))
.Input(string.IsNullOrEmpty(id) ? "*" : id)
.InputRaw(field).InputRaw(SerializeRedisValue(value))
.InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
public Task<string> XAddAsync<T>(string key, Dictionary<string, T> fieldValues) => XAddAsync(key, 0, "*", fieldValues);
public Task<string> XAddAsync<T>(string key, long maxlen, string id, Dictionary<string, T> fieldValues) => CallAsync("XADD"
.InputKey(key)
.InputIf(maxlen > 0, "MAXLEN", maxlen)
.InputIf(maxlen < 0, "MAXLEN", "~", Math.Abs(maxlen))
.Input(string.IsNullOrEmpty(id) ? "*" : id)
.InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
public Task<StreamsXAutoClaimResult> XAutoClaimAsync(string key, string group, string consumer, long minIdleTime, string start, long count = 0) => CallAsync("XAUTOCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, start)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValueToXAutoClaim());
public Task<StreamsEntry[]> XClaimAsync(string key, string group, string consumer, long minIdleTime, params string[] id) => CallAsync("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id), rt => rt.ThrowOrValueToStreamsEntryArray());
public Task<StreamsEntry[]> XClaimAsync(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force) => CallAsync("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id, "IDLE", idle, "RETRYCOUNT", retryCount)
.InputIf(force, "FORCE"), rt => rt.ThrowOrValueToStreamsEntryArray());
public Task<string[]> XClaimJustIdAsync(string key, string group, string consumer, long minIdleTime, params string[] id) => CallAsync("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id, "JUSTID"), rt => rt.ThrowOrValue<string[]>());
public Task<string[]> XClaimJustIdAsync(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force) => CallAsync("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id, "IDLE", idle, "RETRYCOUNT", retryCount)
.InputIf(force, "FORCE")
.Input("JUSTID"), rt => rt.ThrowOrValue<string[]>());
public Task<long> XDelAsync(string key, params string[] id) => CallAsync("XDEL".InputKey(key, id), rt => rt.ThrowOrValue<long>());
public Task XGroupCreateAsync(string key, string group, string id = "$", bool MkStream = false) => CallAsync("XGROUP"
.SubCommand("CREATE")
.InputKey(key)
.Input(group, id)
.InputIf(MkStream, "MKSTREAM"), rt => rt.ThrowOrNothing());
public Task XGroupSetIdAsync(string key, string group, string id = "$") => CallAsync("XGROUP".SubCommand("SETID").InputKey(key).Input(group, id), rt => rt.ThrowOrNothing());
public Task<bool> XGroupDestroyAsync(string key, string group) => CallAsync("XGROUP".SubCommand("DESTROY").InputKey(key).InputRaw(group), rt => rt.ThrowOrValue<bool>());
public Task XGroupCreateConsumerAsync(string key, string group, string consumer) => CallAsync("XGROUP".SubCommand("CREATECONSUMER").InputKey(key).Input(group, consumer), rt => rt.ThrowOrNothing());
public Task<long> XGroupDelConsumerAsync(string key, string group, string consumer) => CallAsync("XGROUP".SubCommand("DELCONSUMER").InputKey(key).Input(group, consumer), rt => rt.ThrowOrValue<long>());
public Task<StreamsXInfoStreamResult> XInfoStreamAsync(string key) => CallAsync("XINFO".SubCommand("STREAM").InputKey(key), rt => rt.ThrowOrValueToXInfoStream());
public Task<StreamsXInfoStreamFullResult> XInfoStreamFullAsync(string key, long count = 10) => CallAsync("XINFO"
.SubCommand("STREAM")
.InputKey(key)
.Input("FULL")
.InputIf(count != 10, "COUNT", count), rt => rt.ThrowOrValueToXInfoStreamFullResult());
public Task<StreamsXInfoGroupsResult[]> XInfoGroupsAsync(string key) => CallAsync("XINFO".SubCommand("GROUPS").InputKey(key), rt => rt.ThrowOrValue((a, _) => a.Select(x => (x as object[]).MapToClass<StreamsXInfoGroupsResult>(rt.Encoding)).ToArray()));
public Task<StreamsXInfoConsumersResult[]> XInfoConsumersAsync(string key, string group) => CallAsync("XINFO".SubCommand("CONSUMERS").InputKey(key).InputRaw(group), rt => rt.ThrowOrValue((a, _) => a.Select(x => (x as object[]).MapToClass<StreamsXInfoConsumersResult>(rt.Encoding)).ToArray()));
public Task<long> XLenAsync(string key) => CallAsync("XLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public Task<StreamsXPendingResult> XPendingAsync(string key, string group) => CallAsync("XPENDING".InputKey(key, group), rt => rt.ThrowOrValueToXPending());
public Task<StreamsXPendingConsumerResult[]> XPendingAsync(string key, string group, string start, string end, long count, string consumer = null) => CallAsync("XPENDING"
.InputKey(key, group)
.Input(start, end, count)
.InputIf(!string.IsNullOrWhiteSpace(consumer), consumer), rt => rt.ThrowOrValueToXPendingConsumer());
public Task<StreamsEntry[]> XRangeAsync(string key, string start, string end, long count = -1) => CallAsync("XRANGE"
.InputKey(key, string.IsNullOrEmpty(start) ? "-" : start, string.IsNullOrEmpty(end) ? "+" : end)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValueToStreamsEntryArray());
public Task<StreamsEntry[]> XRevRangeAsync(string key, string end, string start, long count = -1) => CallAsync("XREVRANGE"
.InputKey(key, string.IsNullOrEmpty(end) ? "+" : end, string.IsNullOrEmpty(start) ? "-" : start)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValueToStreamsEntryArray());
async public Task<StreamsEntry> XReadAsync(long block, string key, string id) => (await XReadAsync(1, block, key, id))?.FirstOrDefault()?.entries?.FirstOrDefault();
public Task<StreamsEntryResult[]> XReadAsync(long count, long block, string key, string id, params string[] keyIds)
{
var kis = keyIds.MapToHash<string>(Encoding.UTF8);
var kikeys = kis.Keys.ToArray();
return CallAsync("XREAD".SubCommand(null)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputRaw("STREAMS")
.InputKey(key)
.InputKeyIf(kikeys.Any(), kikeys)
.Input(id)
.InputIf(kikeys.Any(), kis.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public Task<StreamsEntryResult[]> XReadAsync(long count, long block, Dictionary<string, string> keyIds)
{
var kikeys = keyIds.Keys.ToArray();
return CallAsync("XREAD".SubCommand(null)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputRaw("STREAMS")
.InputKey(kikeys)
.Input(keyIds.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
async public Task<StreamsEntry> XReadGroupAsync(string group, string consumer, long block, string key, string id) => (await XReadGroupAsync(group, consumer, 1, block, false, key, id))?.FirstOrDefault()?.entries?.First();
public Task<StreamsEntryResult[]> XReadGroupAsync(string group, string consumer, long count, long block, bool noack, string key, string id, params string[] keyIds)
{
var kis = keyIds.MapToHash<string>(Encoding.UTF8);
var kikeys = kis.Keys.ToArray();
return CallAsync("XREADGROUP"
.Input("GROUP", group, consumer)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputIf(noack, "NOACK")
.InputRaw("STREAMS")
.InputKey(key)
.InputKeyIf(kikeys.Any(), kikeys)
.Input(id)
.InputIf(kikeys.Any(), kis.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public Task<StreamsEntryResult[]> XReadGroupAsync(string group, string consumer, long count, long block, bool noack, Dictionary<string, string> keyIds)
{
var kikeys = keyIds.Keys.ToArray();
return CallAsync("XREADGROUP"
.Input("GROUP", group, consumer)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputIf(noack, "NOACK")
.InputRaw("STREAMS")
.InputKey(kikeys)
.Input(keyIds.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public Task<long> XTrimAsync(string key, long count) => CallAsync("XTRIM"
.InputKey(key)
.InputIf(count > 0, "MAXLEN", count)
.InputIf(count < 0, "MAXLEN", "~", Math.Abs(count)), rt => rt.ThrowOrValue<long>());
#endregion
#endif
public long XAck(string key, string group, params string[] id) => Call("XACK".InputKey(key, group).Input(id), rt => rt.ThrowOrValue<long>());
public string XAdd<T>(string key, string field, T value, params object[] fieldValues) => XAdd(key, 0, "*", field, value, fieldValues);
public string XAdd<T>(string key, long maxlen, string id, string field, T value, params object[] fieldValues) => Call("XADD"
.InputKey(key)
.InputIf(maxlen > 0, "MAXLEN", maxlen)
.InputIf(maxlen < 0, "MAXLEN", "~", Math.Abs(maxlen))
.Input(string.IsNullOrEmpty(id) ? "*" : id)
.InputRaw(field).InputRaw(SerializeRedisValue(value))
.InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
public string XAdd<T>(string key, Dictionary<string, T> fieldValues) => XAdd(key, 0, "*", fieldValues);
public string XAdd<T>(string key, long maxlen, string id, Dictionary<string, T> fieldValues) => Call("XADD"
.InputKey(key)
.InputIf(maxlen > 0, "MAXLEN", maxlen)
.InputIf(maxlen < 0, "MAXLEN", "~", Math.Abs(maxlen))
.Input(string.IsNullOrEmpty(id) ? "*" : id)
.InputKv(fieldValues, false, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
public StreamsXAutoClaimResult XAutoClaim(string key, string group, string consumer, long minIdleTime, string start, long count = 0) => Call("XAUTOCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, start)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValueToXAutoClaim());
public StreamsEntry[] XClaim(string key, string group, string consumer, long minIdleTime, params string[] id) => Call("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id), rt => rt.ThrowOrValueToStreamsEntryArray());
public StreamsEntry[] XClaim(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force) => Call("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id, "IDLE", idle, "RETRYCOUNT", retryCount)
.InputIf(force, "FORCE"), rt => rt.ThrowOrValueToStreamsEntryArray());
public string[] XClaimJustId(string key, string group, string consumer, long minIdleTime, params string[] id) => Call("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id, "JUSTID"), rt => rt.ThrowOrValue<string[]>());
public string[] XClaimJustId(string key, string group, string consumer, long minIdleTime, string[] id, long idle, long retryCount, bool force) => Call("XCLAIM"
.InputKey(key, group, consumer)
.Input(minIdleTime, id, "IDLE", idle, "RETRYCOUNT", retryCount)
.InputIf(force, "FORCE")
.Input("JUSTID"), rt => rt.ThrowOrValue<string[]>());
public long XDel(string key, params string[] id) => Call("XDEL".InputKey(key, id), rt => rt.ThrowOrValue<long>());
public void XGroupCreate(string key, string group, string id = "$", bool MkStream = false) => Call("XGROUP"
.SubCommand("CREATE")
.InputKey(key)
.Input(group, id)
.InputIf(MkStream, "MKSTREAM"), rt => rt.ThrowOrNothing());
public void XGroupSetId(string key, string group, string id = "$") => Call("XGROUP".SubCommand("SETID").InputKey(key).Input(group, id), rt => rt.ThrowOrNothing());
public bool XGroupDestroy(string key, string group) => Call("XGROUP".SubCommand("DESTROY").InputKey(key).InputRaw(group), rt => rt.ThrowOrValue<bool>());
public void XGroupCreateConsumer(string key, string group, string consumer) => Call("XGROUP".SubCommand("CREATECONSUMER").InputKey(key).Input(group, consumer), rt => rt.ThrowOrNothing());
public long XGroupDelConsumer(string key, string group, string consumer) => Call("XGROUP".SubCommand("DELCONSUMER").InputKey(key).Input(group, consumer), rt => rt.ThrowOrValue<long>());
public StreamsXInfoStreamResult XInfoStream(string key) => Call("XINFO".SubCommand("STREAM").InputKey(key), rt => rt.ThrowOrValueToXInfoStream());
public StreamsXInfoStreamFullResult XInfoStreamFull(string key, long count = 10) => Call("XINFO"
.SubCommand("STREAM")
.InputKey(key)
.Input("FULL")
.InputIf(count != 10, "COUNT", count), rt => rt.ThrowOrValueToXInfoStreamFullResult());
public StreamsXInfoGroupsResult[] XInfoGroups(string key) => Call("XINFO".SubCommand("GROUPS").InputKey(key), rt => rt.ThrowOrValue((a, _) => a.Select(x => (x as object[]).MapToClass<StreamsXInfoGroupsResult>(rt.Encoding)).ToArray()));
public StreamsXInfoConsumersResult[] XInfoConsumers(string key, string group) => Call("XINFO".SubCommand("CONSUMERS").InputKey(key).InputRaw(group), rt => rt.ThrowOrValue((a, _) => a.Select(x => (x as object[]).MapToClass<StreamsXInfoConsumersResult>(rt.Encoding)).ToArray()));
public long XLen(string key) => Call("XLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public StreamsXPendingResult XPending(string key, string group) => Call("XPENDING".InputKey(key, group), rt => rt.ThrowOrValueToXPending());
public StreamsXPendingConsumerResult[] XPending(string key, string group, string start, string end, long count, string consumer = null) => Call("XPENDING"
.InputKey(key, group)
.Input(start, end, count)
.InputIf(!string.IsNullOrWhiteSpace(consumer), consumer), rt => rt.ThrowOrValueToXPendingConsumer());
public StreamsEntry[] XRange(string key, string start, string end, long count = -1) => Call("XRANGE"
.InputKey(key, string.IsNullOrEmpty(start) ? "-" : start, string.IsNullOrEmpty(end) ? "+" : end)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValueToStreamsEntryArray());
public StreamsEntry[] XRevRange(string key, string end, string start, long count = -1) => Call("XREVRANGE"
.InputKey(key, string.IsNullOrEmpty(end) ? "+" : end, string.IsNullOrEmpty(start) ? "-" : start)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValueToStreamsEntryArray());
public StreamsEntry XRead(long block, string key, string id) => XRead(1, block, key, id)?.FirstOrDefault()?.entries?.FirstOrDefault();
public StreamsEntryResult[] XRead(long count, long block, string key, string id, params string[] keyIds)
{
var kis = keyIds.MapToHash<string>(Encoding.UTF8);
var kikeys = kis.Keys.ToArray();
return Call("XREAD".SubCommand(null)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputRaw("STREAMS")
.InputKey(key)
.InputKeyIf(kikeys.Any(), kikeys)
.Input(id)
.InputIf(kikeys.Any(), kis.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public StreamsEntryResult[] XRead(long count, long block, Dictionary<string, string> keyIds)
{
var kikeys = keyIds.Keys.ToArray();
return Call("XREAD".SubCommand(null)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputRaw("STREAMS")
.InputKey(kikeys)
.Input(keyIds.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public StreamsEntry XReadGroup(string group, string consumer, long block, string key, string id) => XReadGroup(group, consumer, 1, block, false, key, id)?.FirstOrDefault()?.entries?.FirstOrDefault();
public StreamsEntryResult[] XReadGroup(string group, string consumer, long count, long block, bool noack, string key, string id, params string[] keyIds) {
var kis = keyIds.MapToHash<string>(Encoding.UTF8);
var kikeys = kis.Keys.ToArray();
return Call("XREADGROUP"
.Input("GROUP", group, consumer)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputIf(noack, "NOACK")
.InputRaw("STREAMS")
.InputKey(key)
.InputKeyIf(kikeys.Any(), kikeys)
.Input(id)
.InputIf(kikeys.Any(), kis.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public StreamsEntryResult[] XReadGroup(string group, string consumer, long count, long block, bool noack, Dictionary<string, string> keyIds)
{
var kikeys = keyIds.Keys.ToArray();
return Call("XREADGROUP"
.Input("GROUP", group, consumer)
.InputIf(count != 0, "COUNT", count)
.InputIf(block > 0, "BLOCK", block)
.InputIf(noack, "NOACK")
.InputRaw("STREAMS")
.InputKey(kikeys)
.Input(keyIds.Values.ToArray()), rt => rt.ThrowOrValueToXRead());
}
public long XTrim(string key, long count) => Call("XTRIM"
.InputKey(key)
.InputIf(count > 0, "MAXLEN", count)
.InputIf(count < 0, "MAXLEN", "~", Math.Abs(count)), rt => rt.ThrowOrValue<long>());
}
#region Model
static partial class RedisResultThrowOrValueExtensions
{
public static StreamsXAutoClaimResult ThrowOrValueToXAutoClaim(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a == null) return null;
var a1 = a[1] as object[];
var entries = new StreamsEntry[a.Length];
for (var z = 0; z < a1.Length; z++)
{
var objs1 = a1[z] as object[];
if (objs1 == null) continue;
entries[z] = new StreamsEntry { id = objs1[0].ConvertTo<string>(), fieldValues = objs1[1] as object[] };
}
return new StreamsXAutoClaimResult { start = a[0].ConvertTo<string>(), entries = entries, delIds = (a[2] as object[])?.Select(z => z.ConvertTo<string>()).ToArray() };
});
public static StreamsEntry[] ThrowOrValueToStreamsEntryArray(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a == null) return new StreamsEntry[0];
var entries = new StreamsEntry[a.Length];
for (var z = 0; z < a.Length; z++)
{
var objs1 = a[z] as object[];
if (objs1 == null) continue;
entries[z] = new StreamsEntry { id = objs1[0].ConvertTo<string>(), fieldValues = objs1[1] as object[] };
}
return entries;
});
public static StreamsXPendingResult ThrowOrValueToXPending(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a?.Any() != true) return null;
var ret = new StreamsXPendingResult { count = a[0].ConvertTo<long>(), minId = a[1].ConvertTo<string>(), maxId = a[2].ConvertTo<string>() };
var objs1 = a[3] as object[];
if (objs1 == null) objs1 = new object[0];
ret.consumers = new StreamsXPendingResult.Consumer[objs1.Length];
for (var z = 0; z < objs1.Length; z++)
{
var objs2 = objs1[z] as object[];
ret.consumers[z] = new StreamsXPendingResult.Consumer { consumer = objs2[0].ConvertTo<string>(), count = objs2[1].ConvertTo<long>() };
}
return ret;
});
public static StreamsXPendingConsumerResult[] ThrowOrValueToXPendingConsumer(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a == null) return new StreamsXPendingConsumerResult[0];
var ret = new StreamsXPendingConsumerResult[a.Length];
for (var z = 0; z < a.Length; z++)
{
var objs1 = a[z] as object[];
ret[z] = new StreamsXPendingConsumerResult { id = objs1[0].ConvertTo<string>(), consumer = objs1[1].ConvertTo<string>(), idle = objs1[2].ConvertTo<long>(), deliveredTimes = objs1[3].ConvertTo<long>() };
}
return ret;
});
public static StreamsXInfoStreamResult ThrowOrValueToXInfoStream(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a == null) return null;
a.MapSetListValue(new Dictionary<string, Func<object[], object>>
{
["first-entry"] = ThrowOrValueToXInfoStreamMapSet,
["last-entry"] = ThrowOrValueToXInfoStreamMapSet
});
return a.MapToClass<StreamsXInfoStreamResult>(rt.Encoding);
});
static object ThrowOrValueToXInfoStreamMapSet(object[] value)
{
var objs1 = value as object[];
return objs1 == null ? null : new StreamsEntry { id = objs1[0].ConvertTo<string>(), fieldValues = objs1[1] as object[] };
}
public static StreamsXInfoStreamFullResult ThrowOrValueToXInfoStreamFullResult(this RedisResult rt) =>
rt.ThrowOrValue((objs_full, _) =>
{
if (objs_full == null) return null;
objs_full.MapSetListValue(new Dictionary<string, Func<object[], object>>
{
["entries"] = value => value.Select(z =>
{
var objs_entry = z as object[];
return objs_entry == null ? null : new StreamsEntry { id = objs_entry[0].ConvertTo<string>(), fieldValues = objs_entry[1] as object[] };
}).ToArray(),
["groups"] = value => value.Select(z =>
{
var objs_group = z as object[];
if (objs_group == null) return null;
objs_group.MapSetListValue(new Dictionary<string, Func<object[], object>>
{
["pending"] = value1 => value1.Select(y =>
{
var objs_pending = y as object[];
if (objs_pending == null) return null;
return new StreamsXInfoStreamFullResult.Group.Pending
{
id = objs_pending[0].ConvertTo<string>(),
consumer = objs_pending[1].ConvertTo<string>(),
seen_time = objs_pending[2].ConvertTo<long>(),
pel_count = objs_pending[3].ConvertTo<long>()
};
}).ToArray(),
["consumers"] = value1 => value1.Select(y =>
{
var objs_consumer = y as object[];
if (objs_consumer == null) return null;
objs_consumer.MapSetListValue(new Dictionary<string, Func<object[], object>>
{
["pending"] = value2 => value2.Select(x =>
{
var objs_consumer_pending = x as object[];
if (objs_consumer_pending == null) return null;
return new StreamsXInfoStreamFullResult.Group.Pending
{
id = objs_consumer_pending[0].ConvertTo<string>(),
consumer = objs_consumer[1].ConvertTo<string>(),
seen_time = objs_consumer_pending[1].ConvertTo<long>(),
pel_count = objs_consumer_pending[2].ConvertTo<long>()
};
}).ToArray()
});
return objs_consumer.MapToClass<StreamsXInfoStreamFullResult.Group.Consumer>(rt.Encoding);
}).ToArray()
});
return objs_group.MapToClass<StreamsXInfoStreamFullResult.Group>(rt.Encoding);
}).ToArray()
});
return objs_full.MapToClass<StreamsXInfoStreamFullResult>(rt.Encoding);
});
public static StreamsEntryResult[] ThrowOrValueToXRead(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
if (a == null) return new StreamsEntryResult[0];
var ret = new StreamsEntryResult[a.Length];
for (var z = 0; z < a.Length; z++)
{
var objs1 = a[z] as object[];
var objs2 = objs1[1] as object[];
var entries = new StreamsEntry[objs2.Length];
ret[z] = new StreamsEntryResult { key = objs1[0].ConvertTo<string>(), entries = entries };
for (var y = 0; y < objs2.Length; y++)
{
var objs3 = objs2[y] as object[];
entries[y] = new StreamsEntry { id = objs3[0].ConvertTo<string>(), fieldValues = objs3[1] as object[] };
}
}
return ret;
});
}
public class StreamsXAutoClaimResult
{
public string start;
public StreamsEntry[] entries;
public string[] delIds;
public override string ToString() => $"{start}, [{string.Join("], [", entries.Select(a => a?.ToString()))}], [{string.Join(", ", delIds)}]";
}
public class StreamsXPendingResult
{
public long count;
public string minId;
public string maxId;
public Consumer[] consumers;
public override string ToString() => $"{count}, {minId}, {maxId}, {string.Join(", ", consumers?.Select(a => a.ToString()))}";
public class Consumer
{
public string consumer;
public long count;
public override string ToString() => $"{consumer}({count})";
}
}
public class StreamsXPendingConsumerResult
{
public string id;
public string consumer;
public long idle;
public long deliveredTimes;
public override string ToString() => $"{id}, {consumer}, {idle}, {deliveredTimes}";
}
public class StreamsXInfoStreamResult
{
public long length;
public long radix_tree_keys;
public long radix_tree_nodes;
public long groups;
public string last_generated_id;
public StreamsEntry first_entry;
public StreamsEntry last_entry;
public override string ToString() => $"{length}, {radix_tree_keys}, {radix_tree_nodes}, {groups}, {last_generated_id}, {(first_entry?.ToString() ?? "NULL")}, {(last_entry?.ToString() ?? "NULL")}";
}
public class StreamsXInfoGroupsResult
{
public string name;
public long consumers;
public long pending;
public string last_delivered_id;
public override string ToString() => $"{name}, {consumers}, {pending}, {last_delivered_id}";
}
public class StreamsXInfoConsumersResult
{
public string name;
public long pending;
public long idle;
public override string ToString() => $"{name}, {pending}, {idle}";
}
public class StreamsXInfoStreamFullResult
{
public long length;
public long radix_tree_keys;
public long radix_tree_nodes;
public string last_generated_id;
public StreamsEntry[] entries;
public Group[] groups;
public override string ToString() => $"{length}, {radix_tree_keys}, {radix_tree_nodes}, {last_generated_id}, [{string.Join("], [", entries?.Select(a => a?.ToString()))}], [{string.Join(", ", groups?.Select(a => a?.ToString()))}]";
public class Group
{
public string name;
public string last_delivered_id;
public long pel_count;
public Pending[] pending;
public Consumer[] consumers;
public override string ToString() => $"{name}, {last_delivered_id}, {pel_count}, [{string.Join("], [", pending?.Select(a => a?.ToString()))}], [{string.Join("], [", consumers?.Select(a => a?.ToString()))}]";
public class Pending
{
public string id;
public string consumer;
public long seen_time;
public long pel_count;
public override string ToString() => $"{id}, {consumer}, {seen_time}, {pel_count}";
}
public class Consumer
{
public string name;
public long seen_time;
public long pel_count;
public Pending[] pending;
public override string ToString() => $"{name}, {seen_time}, {pel_count}, [{string.Join("], [", pending?.Select(a => a?.ToString()))}]";
}
}
}
public class StreamsEntryResult
{
public string key;
public StreamsEntry[] entries;
public override string ToString() => $"{key}, [{string.Join("], [", entries.Select(a => a?.ToString()))}]";
}
public class StreamsEntry
{
public string id;
public object[] fieldValues;
public override string ToString() => $"{id}, {string.Join(", ", fieldValues)}";
}
#endregion
}
|
2881099/FreeRedis | 5,887 | src/FreeRedis/RedisClient/Connection.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace FreeRedis
{
partial class RedisClient
{
public void Auth(string password) => Call("AUTH".Input(password), rt => rt.ThrowOrValue());
public void Auth(string username, string password) => Call("AUTH".SubCommand(null)
.InputIf(!string.IsNullOrWhiteSpace(username), username)
.InputRaw(password), rt => rt.ThrowOrValue());
public void ClientCaching(Confirm confirm) => Call("CLIENT".SubCommand("CACHING").InputRaw(confirm), rt => rt.ThrowOrValue());
public string ClientGetName() => Call("CLIENT".SubCommand("GETNAME"), rt => rt.ThrowOrValue<string>());
public long ClientGetRedir() => Call("CLIENT".SubCommand("GETREDIR"), rt => rt.ThrowOrValue<long>());
public long ClientId() => Call("CLIENT".SubCommand("ID"), rt => rt.ThrowOrValue<long>());
public void ClientKill(string ipport) => Call("CLIENT"
.SubCommand("KILL")
.InputIf(!string.IsNullOrWhiteSpace(ipport), ipport), rt => rt.ThrowOrValue<long>());
public long ClientKill(string ipport, long? clientid, ClientType? type, string username, string addr, Confirm? skipme) => Call("CLIENT"
.SubCommand("KILL")
.InputIf(!string.IsNullOrWhiteSpace(ipport), ipport)
.InputIf(clientid != null, "ID", clientid)
.InputIf(type != null, "TYPE", type)
.InputIf(!string.IsNullOrWhiteSpace(username), "USER", username)
.InputIf(!string.IsNullOrWhiteSpace(addr), "ADDR", addr)
.InputIf(skipme != null, "SKIPME", skipme), rt => rt.ThrowOrValue<long>());
public string ClientList(ClientType? type = null) => Call("CLIENT".SubCommand("LIST")
.InputIf(type != null, "TYPE", type), rt => rt.ThrowOrValue<string>());
public void ClientPause(long timeoutMilliseconds) => Call("CLIENT".SubCommand("PAUSE").InputRaw(timeoutMilliseconds), rt => rt.ThrowOrValue());
public void ClientReply(ClientReplyType type)
{
var cmd = "CLIENT".SubCommand("REPLY").InputRaw(type);
Adapter.TopOwner.LogCall(cmd, () =>
{
using (var rds = Adapter.GetRedisSocket(null))
{
rds.Write(cmd);
switch (type)
{
case ClientReplyType.off:
break;
case ClientReplyType.on:
rds.Read(cmd).ThrowOrNothing();
break;
case ClientReplyType.skip:
break;
}
}
return default(string);
});
}
public void ClientSetName(string connectionName) => Call("CLIENT".SubCommand("SETNAME").InputRaw(connectionName), rt => rt.ThrowOrNothing());
public void ClientTracking(bool on_off, long? redirect, string[] prefix, bool bcast, bool optin, bool optout, bool noloop) => Call("CLIENT"
.SubCommand("TRACKING")
.InputIf(on_off, "ON")
.InputIf(!on_off, "OFF")
.InputIf(redirect != null, "REDIRECT", redirect)
.InputIf(prefix?.Any() == true, prefix?.Select(a => new[] { "PREFIX", a }).SelectMany(a => a).ToArray())
.InputIf(bcast, "BCAST")
.InputIf(optin, "OPTIN")
.InputIf(optout, "OPTOUT")
.InputIf(noloop, "NOLOOP"), rt => rt.ThrowOrNothing());
public bool ClientUnBlock(long clientid, ClientUnBlockType? type = null) => Call("CLIENT"
.SubCommand("UNBLOCK")
.InputRaw(clientid)
.InputIf(type != null, type), rt => rt.ThrowOrValue<bool>());
public string Echo(string message) => Call("ECHO".SubCommand(null)
.InputIf(!string.IsNullOrEmpty(message), message), rt => rt.ThrowOrValue<string>());
public Dictionary<string, object> Hello(string protover, string username = null, string password = null, string clientname = null) => Call("HELLO"
.Input(protover)
.InputIf(!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password), "AUTH", username, password)
.InputIf(!string.IsNullOrWhiteSpace(clientname), "SETNAME", clientname), rt => rt
.ThrowOrValue((a, _) => a.MapToHash<object>(rt.Encoding)));
public string Ping(string message = null)
{
if (Adapter.UseType == UseType.SingleInside &&
_pubsubPriv?.IsSubscribed == true &&
this == Adapter.TopOwner)
{
_pubsub.Call("PING");
return message ?? "PONG";
}
return Call("PING".SubCommand(null)
.InputIf(!string.IsNullOrEmpty(message), message), rt => rt.ThrowOrValue(a =>
{
if (a is string str) return str;
if (a is object[] objs)
{
//If the client is subscribed to a channel or a pattern,
//it will instead return a multi-bulk with a "pong" in the first position and an empty bulk in the second position,
//unless an argument is provided in which case it returns a copy of the argument.
var str2 = objs[1].ConvertTo<string>();
if (!string.IsNullOrEmpty(str2)) return str2;
return objs[0].ConvertTo<string>();
}
return a.ConvertTo<string>();
}));
}
public void Quit() => Call("QUIT", rt => rt.ThrowOrValue());
public void Select(int index) => Call("SELECT".Input(index), rt => rt.ThrowOrValue());
}
}
|
2881099/FreeRedis | 10,103 | src/FreeRedis/RedisClient/Sets.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<long> SAddAsync(string key, params object[] members) => CallAsync("SADD".InputKey(key).Input(members.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<long> SCardAsync(string key) => CallAsync("SCARD".InputKey(key), rt => rt.ThrowOrValue<long>());
public Task<string[]> SDiffAsync(params string[] keys) => CallAsync("SDIFF".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> SDiffAsync<T>(params string[] keys) => SReadArrayAsync<T>("SDIFF".InputKey(keys));
public Task<long> SDiffStoreAsync(string destination, params string[] keys) => CallAsync("SDIFFSTORE".InputKey(destination).InputKey(keys), rt => rt.ThrowOrValue<long>());
public Task<string[]> SInterAsync(params string[] keys) => CallAsync("SINTER".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> SInterAsync<T>(params string[] keys) => SReadArrayAsync<T>("SINTER".InputKey(keys));
public Task<long> SInterStoreAsync(string destination, params string[] keys) => CallAsync("SINTERSTORE".InputKey(destination).InputKey(keys), rt => rt.ThrowOrValue<long>());
public Task<bool> SIsMemberAsync<T>(string key, T member) => CallAsync("SISMEMBER".InputKey(key).InputRaw(SerializeRedisValue(member)), rt => rt.ThrowOrValue<bool>());
public Task<string[]> SMembersAsync(string key) => CallAsync("SMEMBERS".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> SMembersAsync<T>(string key) => SReadArrayAsync<T>("SMEMBERS".InputKey(key));
public Task<bool[]> SMIsMemberAsync(string key, params object[] members) => CallAsync("SMISMEMBER".InputKey(key).Input(members.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<bool[]>());
public Task<bool> SMoveAsync<T>(string source, string destination, T member) => CallAsync("SMOVE"
.InputKey(source)
.InputKey(destination)
.InputRaw(SerializeRedisValue(member)), rt => rt.ThrowOrValue<bool>());
public Task<string> SPopAsync(string key) => CallAsync("SPOP".InputKey(key), rt => rt.ThrowOrValue<string>());
public Task<T> SPopAsync<T>(string key) => CallAsync("SPOP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<string[]> SPopAsync(string key, int count) => CallAsync("SPOP".InputKey(key, count), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> SPopAsync<T>(string key, int count) => SReadArrayAsync<T>("SPOP".InputKey(key, count));
public Task<string> SRandMemberAsync(string key) => CallAsync("SRANDMEMBER".InputKey(key), rt => rt.ThrowOrValue<string>());
public Task<T> SRandMemberAsync<T>(string key) => CallAsync("SRANDMEMBER".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<string[]> SRandMemberAsync(string key, int count) => CallAsync("SRANDMEMBER".InputKey(key, count), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> SRandMemberAsync<T>(string key, int count) => SReadArrayAsync<T>("SRANDMEMBER".InputKey(key, count));
public Task<long> SRemAsync(string key, params object[] members) => CallAsync("SREM".InputKey(key).Input(members.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<ScanResult<string>> SScanAsync(string key, long cursor, string pattern, long count) => CallAsync("SSCAN"
.InputKey(key, cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<string>(a[0].ConvertTo<long>(), a[1].ConvertTo<string[]>())));
public Task<ScanResult<T>> SScanAsync<T>(string key, long cursor, string pattern, long count) => CallAsync("SSCAN"
.InputKey(key, cursor)
.FlagReadbytes(true)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<T>(a[0].ConvertTo<long>(), a[1].ConvertTo<byte[][]>().Select(b => DeserializeRedisValue<T>(b, rt.Encoding)).ToArray())));
public Task<string[]> SUnionAsync(params string[] keys) => CallAsync("SUNION".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
public Task<T[]> SUnionAsync<T>(params string[] keys) => SReadArrayAsync<T>("SUNION".InputKey(keys));
public Task<long> SUnionStoreAsync(string destination, params string[] keys) => CallAsync("SUNIONSTORE".InputKey(destination).InputKey(keys), rt => rt.ThrowOrValue<long>());
Task<T[]> SReadArrayAsync<T>(CommandPacket cb) => CallAsync(cb.FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new T[0] : a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
#endregion
#endif
public long SAdd(string key, params object[] members) => Call("SADD".InputKey(key).Input(members.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public long SCard(string key) => Call("SCARD".InputKey(key), rt => rt.ThrowOrValue<long>());
public string[] SDiff(params string[] keys) => Call("SDIFF".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
public T[] SDiff<T>(params string[] keys) => SReadArray<T>("SDIFF".InputKey(keys));
public long SDiffStore(string destination, params string[] keys) => Call("SDIFFSTORE".InputKey(destination).InputKey(keys), rt => rt.ThrowOrValue<long>());
public string[] SInter(params string[] keys) => Call("SINTER".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
public T[] SInter<T>(params string[] keys) => SReadArray<T>("SINTER".InputKey(keys));
public long SInterStore(string destination, params string[] keys) => Call("SINTERSTORE".InputKey(destination).InputKey(keys), rt => rt.ThrowOrValue<long>());
public bool SIsMember<T>(string key, T member) => Call("SISMEMBER".InputKey(key).InputRaw(SerializeRedisValue(member)), rt => rt.ThrowOrValue<bool>());
public string[] SMembers(string key) => Call("SMEMBERS".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public T[] SMembers<T>(string key) => SReadArray<T>("SMEMBERS".InputKey(key));
public bool[] SMIsMember(string key, params object[] members) => Call("SMISMEMBER".InputKey(key).Input(members.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<bool[]>());
public bool SMove<T>(string source, string destination, T member) => Call("SMOVE"
.InputKey(source)
.InputKey(destination)
.InputRaw(SerializeRedisValue(member)), rt => rt.ThrowOrValue<bool>());
public string SPop(string key) => Call("SPOP".InputKey(key), rt => rt.ThrowOrValue<string>());
public T SPop<T>(string key) => Call("SPOP".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public string[] SPop(string key, int count) => Call("SPOP".InputKey(key, count), rt => rt.ThrowOrValue<string[]>());
public T[] SPop<T>(string key, int count) => SReadArray<T>("SPOP".InputKey(key, count));
public string SRandMember(string key) => Call("SRANDMEMBER".InputKey(key), rt => rt.ThrowOrValue<string>());
public T SRandMember<T>(string key) => Call("SRANDMEMBER".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public string[] SRandMember(string key, int count) => Call("SRANDMEMBER".InputKey(key, count), rt => rt.ThrowOrValue<string[]>());
public T[] SRandMember<T>(string key, int count) => SReadArray<T>("SRANDMEMBER".InputKey(key, count));
public long SRem(string key, params object[] members) => Call("SREM".InputKey(key).Input(members.Select(a => SerializeRedisValue(a)).ToArray()), rt => rt.ThrowOrValue<long>());
public ScanResult<string> SScan(string key, long cursor, string pattern, long count) => Call("SSCAN"
.InputKey(key, cursor)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<string>(a[0].ConvertTo<long>(), a[1].ConvertTo<string[]>())));
public ScanResult<T> SScan<T>(string key, long cursor, string pattern, long count) => Call("SSCAN"
.InputKey(key, cursor)
.FlagReadbytes(true)
.InputIf(!string.IsNullOrWhiteSpace(pattern), "MATCH", pattern)
.InputIf(count != 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new ScanResult<T>(a[0].ConvertTo<long>(), a[1].ConvertTo<byte[][]>().Select(b => DeserializeRedisValue<T>(b, rt.Encoding)).ToArray())));
public IEnumerable<string[]> SScan(string key, string pattern, long count) => new ScanCollection<string>(this, "sscan", (cli, cursor) => cli.SScan(key, cursor, pattern, count));
public IEnumerable<T[]> SScan<T>(string key, string pattern, long count) => new ScanCollection<T>(this, "sscan", (cli, cursor) => cli.SScan<T>(key, cursor, pattern, count));
public string[] SUnion(params string[] keys) => Call("SUNION".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
public T[] SUnion<T>(params string[] keys) => SReadArray<T>("SUNION".InputKey(keys));
public long SUnionStore(string destination, params string[] keys) => Call("SUNIONSTORE".InputKey(destination).InputKey(keys), rt => rt.ThrowOrValue<long>());
T[] SReadArray<T>(CommandPacket cb) => Call(cb.FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a == null || a.Length == 0 ? new T[0] : a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
}
}
|
2881099/FreeRedis | 13,001 | src/FreeRedis/RedisClient/Geo.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<long> GeoAddAsync(string key, params GeoMember[] members)
{
var cmd = "GEOADD".InputKey(key);
foreach (var mem in members) cmd.InputRaw(mem.longitude).InputRaw(mem.latitude).InputRaw(mem.member);
return CallAsync(cmd, rt => rt.ThrowOrValue<long>());
}
public Task<decimal?> GeoDistAsync(string key, string member1, string member2, GeoUnit unit = GeoUnit.m) => CallAsync("GEODIST"
.InputKey(key)
.Input(member1, member2)
.InputIf(unit != GeoUnit.m, unit), rt => rt.ThrowOrValue<decimal?>());
public Task<string> GeoHashAsync(string key, string member) => CallAsync("GEOHASH".InputKey(key, member), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo<string>()));
public Task<string[]> GeoHashAsync(string key, string[] members) => CallAsync("GEOHASH".InputKey(key, members), rt => rt.ThrowOrValue<string[]>());
public Task<GeoMember> GeoPosAsync(string key, string member) => GeoPosAsync(key, new[] { member }, rt => rt.FirstOrDefault());
public Task<GeoMember[]> GeoPosAsync(string key, string[] members) => GeoPosAsync(key, members, rt => rt);
Task<T> GeoPosAsync<T>(string key, string[] members, Func<GeoMember[], T> parse) => CallAsync("GEOPOS".InputKey(key, members), rt => rt
.ThrowOrValue((a, _) => parse(a.Select((z, y) =>
{
if (z == null) return null;
var zarr = z as object[];
return new GeoMember(zarr[0].ConvertTo<decimal>(), zarr[1].ConvertTo<decimal>(), members[y]);
}).ToArray())
));
public Task<GeoRadiusResult[]> GeoRadiusAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m,
bool withdoord = false, bool withdist = false, bool withhash = false,
long? count = null, Collation? collation = null) => GeoRadiusAsync("GEORADIUS", key, null, longitude, latitude, radius, unit,
withdoord, withdist, withhash, count, collation);
public Task<long> GeoRadiusStoreAsync(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m,
long? count = null, Collation? collation = null,
string storekey = null, string storedistkey = null)
{
if (string.IsNullOrWhiteSpace(storekey) && string.IsNullOrWhiteSpace(storedistkey)) throw new ArgumentNullException(nameof(storekey));
return CallAsync("GEORADIUS"
.InputKey(key)
.Input(longitude, latitude, radius, unit)
.InputIf(count != null, "COUNT", count)
.InputIf(collation != null, collation)
.InputIf(!string.IsNullOrWhiteSpace(storekey), "STORE", storekey)
.InputIf(!string.IsNullOrWhiteSpace(storedistkey), "STOREDIST", storedistkey), rt => rt.ThrowOrValue<long>());
}
Task<GeoRadiusResult[]> GeoRadiusAsync(string cmd, string key, string member, decimal? longitude, decimal? latitude, decimal radius, GeoUnit unit = GeoUnit.m,
bool withdoord = false, bool withdist = false, bool withhash = false,
long? count = null, Collation? collation = null) => CallAsync(cmd
.InputKey(key)
.InputIf(!string.IsNullOrEmpty(member), member)
.InputIf(longitude != null && latitude != null, longitude, latitude)
.InputRaw(radius)
.InputRaw(unit)
.InputIf(withdoord, "WITHCOORD")
.InputIf(withdist, "WITHDIST")
.InputIf(withhash, "WITHHASH")
.InputIf(count != null, "COUNT", count)
.InputIf(collation != null, collation), rt => rt.ThrowOrValue((a, _) =>
{
if (withdoord || withdist || withhash)
return a.Select(x =>
{
var objs2 = x as object[];
var grr = new GeoRadiusResult { member = objs2[0].ConvertTo<string>() };
var objs2idx = 0;
if (withdist) grr.dist = objs2[++objs2idx].ConvertTo<decimal>();
if (withhash) grr.hash = objs2[++objs2idx].ConvertTo<long>();
if (withdoord)
{
var objs3 = objs2[++objs2idx].ConvertTo<decimal[]>();
grr.longitude = objs3[0];
grr.latitude = objs3[1];
}
return grr;
}).ToArray();
return a.Select(x => new GeoRadiusResult { member = x.ConvertTo<string>() }).ToArray();
}));
public Task<GeoRadiusResult[]> GeoRadiusByMemberAsync(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m,
bool withdoord = false, bool withdist = false, bool withhash = false,
long? count = null, Collation? collation = null) => GeoRadiusAsync("GEORADIUSBYMEMBER", key, member, null, null, radius, unit,
withdoord, withdist, withhash, count, collation);
public Task<long> GeoRadiusByMemberStoreAsync(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m,
long? count = null, Collation? collation = null,
string storekey = null, string storedistkey = null)
{
if (string.IsNullOrWhiteSpace(storekey) && string.IsNullOrWhiteSpace(storedistkey)) throw new ArgumentNullException(nameof(storekey));
return CallAsync("GEORADIUSBYMEMBER"
.InputKey(key)
.Input(member, radius, unit)
.InputIf(count != null, "COUNT", count)
.InputIf(collation != null, collation)
.InputIf(!string.IsNullOrWhiteSpace(storekey), "STORE", storekey)
.InputIf(!string.IsNullOrWhiteSpace(storedistkey), "STOREDIST", storedistkey), rt => rt.ThrowOrValue<long>());
}
#endregion
#endif
public long GeoAdd(string key, params GeoMember[] members)
{
var cmd = "GEOADD".InputKey(key);
foreach (var mem in members) cmd.InputRaw(mem.longitude).InputRaw(mem.latitude).InputRaw(mem.member);
return Call(cmd, rt => rt.ThrowOrValue<long>());
}
public decimal? GeoDist(string key, string member1, string member2, GeoUnit unit = GeoUnit.m) => Call("GEODIST"
.InputKey(key)
.Input(member1, member2)
.InputIf(unit != GeoUnit.m, unit), rt => rt.ThrowOrValue<decimal?>());
public string GeoHash(string key, string member) => Call("GEOHASH".InputKey(key, member), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo<string>()));
public string[] GeoHash(string key, string[] members) => Call("GEOHASH".InputKey(key, members), rt => rt.ThrowOrValue<string[]>());
public GeoMember GeoPos(string key, string member) => GeoPos(key, new[] { member }, rt => rt.FirstOrDefault());
public GeoMember[] GeoPos(string key, string[] members) => GeoPos(key, members, rt => rt);
T GeoPos<T>(string key, string[] members, Func<GeoMember[], T> parse) => Call("GEOPOS".InputKey(key, members), rt => rt
.ThrowOrValue((a, _) => parse(a.Select((z, y) =>
{
if (z == null) return null;
var zarr = z as object[];
return new GeoMember(zarr[0].ConvertTo<decimal>(), zarr[1].ConvertTo<decimal>(), members[y]);
}).ToArray())
));
public GeoRadiusResult[] GeoRadius(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m,
bool withdoord = false, bool withdist = false, bool withhash = false,
long? count = null, Collation? collation = null) => GeoRadius("GEORADIUS", key, null, longitude, latitude, radius, unit,
withdoord, withdist, withhash, count, collation);
public long GeoRadiusStore(string key, decimal longitude, decimal latitude, decimal radius, GeoUnit unit = GeoUnit.m,
long? count = null, Collation? collation = null,
string storekey = null, string storedistkey = null)
{
if (string.IsNullOrWhiteSpace(storekey) && string.IsNullOrWhiteSpace(storedistkey)) throw new ArgumentNullException(nameof(storekey));
return Call("GEORADIUS"
.InputKey(key)
.Input(longitude, latitude, radius, unit)
.InputIf(count != null, "COUNT", count)
.InputIf(collation != null, collation)
.InputIf(!string.IsNullOrWhiteSpace(storekey), "STORE", storekey)
.InputIf(!string.IsNullOrWhiteSpace(storedistkey), "STOREDIST", storedistkey), rt => rt.ThrowOrValue<long>());
}
GeoRadiusResult[] GeoRadius(string cmd, string key, string member, decimal? longitude, decimal? latitude, decimal radius, GeoUnit unit = GeoUnit.m,
bool withdoord = false, bool withdist = false, bool withhash = false,
long? count = null, Collation? collation = null) => Call(cmd
.InputKey(key)
.InputIf(!string.IsNullOrEmpty(member), member)
.InputIf(longitude != null && latitude != null, longitude, latitude)
.InputRaw(radius)
.InputRaw(unit)
.InputIf(withdoord, "WITHCOORD")
.InputIf(withdist, "WITHDIST")
.InputIf(withhash, "WITHHASH")
.InputIf(count != null, "COUNT", count)
.InputIf(collation != null, collation), rt => rt.ThrowOrValue((a, _) =>
{
if (withdoord || withdist || withhash)
return a.Select(x =>
{
var objs2 = x as object[];
var grr = new GeoRadiusResult { member = objs2[0].ConvertTo<string>() };
var objs2idx = 0;
if (withdist) grr.dist = objs2[++objs2idx].ConvertTo<decimal>();
if (withhash) grr.hash = objs2[++objs2idx].ConvertTo<long>();
if (withdoord)
{
var objs3 = objs2[++objs2idx].ConvertTo<decimal[]>();
grr.longitude = objs3[0];
grr.latitude = objs3[1];
}
return grr;
}).ToArray();
return a.Select(x => new GeoRadiusResult { member = x.ConvertTo<string>() }).ToArray();
}));
public GeoRadiusResult[] GeoRadiusByMember(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m,
bool withdoord = false, bool withdist = false, bool withhash = false,
long? count = null, Collation? collation = null) => GeoRadius("GEORADIUSBYMEMBER", key, member, null, null, radius, unit,
withdoord, withdist, withhash, count, collation);
public long GeoRadiusByMemberStore(string key, string member, decimal radius, GeoUnit unit = GeoUnit.m,
long? count = null, Collation? collation = null,
string storekey = null, string storedistkey = null)
{
if (string.IsNullOrWhiteSpace(storekey) && string.IsNullOrWhiteSpace(storedistkey)) throw new ArgumentNullException(nameof(storekey));
return Call("GEORADIUSBYMEMBER"
.InputKey(key)
.Input(member, radius, unit)
.InputIf(count != null, "COUNT", count)
.InputIf(collation != null, collation)
.InputIf(!string.IsNullOrWhiteSpace(storekey), "STORE", storekey)
.InputIf(!string.IsNullOrWhiteSpace(storedistkey), "STOREDIST", storedistkey), rt => rt.ThrowOrValue<long>());
}
}
public class GeoMember
{
public readonly decimal longitude;
public readonly decimal latitude;
public readonly string member;
public GeoMember(decimal longitude, decimal latitude, string member) { this.longitude = longitude; this.latitude = latitude; this.member = member; }
}
//1) 1) "Palermo"
// 2) "190.4424"
// 3) (integer) 3479099956230698
// 4) 1) "13.361389338970184"
// 2) "38.115556395496299"
//2) 1) "Catania"
// 2) "56.4413"
// 3) (integer) 3479447370796909
// 4) 1) "15.087267458438873"
// 2) "37.50266842333162"
public class GeoRadiusResult
{
public string member;
public decimal? dist;
public decimal? hash;
public decimal? longitude;
public decimal? latitude;
}
}
|
2881099/FreeRedis | 16,270 | src/FreeRedis/RedisClient/PubSub.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace FreeRedis.Internal
{
public interface IPubSubSubscriber : IDisposable
{
RedisClient TopOwner { get; }
IRedisSocket RedisSocket { get; }
}
}
namespace FreeRedis
{
partial class RedisClient
{
PubSub _pubsubPriv;
object _pubsubPrivLock = new object();
PubSub _pubsub //Sharing top RedisClient PubSub, The cluster can forward and take effect
{
get
{
if (this != Adapter.TopOwner) return Adapter.TopOwner._pubsub;
if (_pubsubPriv == null)
lock (_pubsubPrivLock)
if (_pubsubPriv == null)
_pubsubPriv = new PubSub(this);
return _pubsubPriv;
}
}
#if isasync
#region async (copy from sync)
public Task<long> PublishAsync(string channel, string message) => CallAsync("PUBLISH".Input(channel, message), rt => rt.ThrowOrValue<long>());
public Task<long> PublishAsync(string channel, byte[] message) => CallAsync("PUBLISH".Input(channel).InputRaw(message), rt => rt.ThrowOrValue<long>());
public Task<string[]> PubSubChannelsAsync(string pattern = "*") => CallAsync("PUBSUB".SubCommand("CHANNELS").Input(pattern), rt => rt.ThrowOrValue<string[]>());
public Task<long> PubSubNumSubAsync(string channel) => CallAsync("PUBSUB".SubCommand("NUMSUB").Input(channel), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).FirstOrDefault()));
public Task<long[]> PubSubNumSubAsync(string[] channels) => CallAsync("PUBSUB".SubCommand("NUMSUB").Input(channels), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).ToArray()));
public Task<long> PubSubNumPatAsync() => CallAsync("PUBLISH".SubCommand("NUMPAT"), rt => rt.ThrowOrValue<long>());
#endregion
#endif
public IDisposable PSubscribe(string pattern, Action<string, object> handler)
{
if (string.IsNullOrEmpty(pattern)) throw new ArgumentNullException(nameof(pattern));
if (handler == null) throw new ArgumentNullException(nameof(handler));
return _pubsub.Subscribe(true, false, new[] { pattern }, (p, k, d) => handler(k, d));
}
public IDisposable PSubscribe(string[] pattern, Action<string, object> handler)
{
if (pattern?.Any() != true) throw new ArgumentNullException(nameof(pattern));
if (handler == null) throw new ArgumentNullException(nameof(handler));
return _pubsub.Subscribe(true, false, pattern, (p, k, d) => handler(k, d));
}
public long Publish(string channel, string message) => Call("PUBLISH".Input(channel, message), rt => rt.ThrowOrValue<long>());
public long Publish(string channel, byte[] message) => Call("PUBLISH".Input(channel).InputRaw(message), rt => rt.ThrowOrValue<long>());
public string[] PubSubChannels(string pattern = "*") => Call("PUBSUB".SubCommand("CHANNELS").Input(pattern), rt => rt.ThrowOrValue<string[]>());
public long PubSubNumSub(string channel) => Call("PUBSUB".SubCommand("NUMSUB").Input(channel), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).FirstOrDefault()));
public long[] PubSubNumSub(string[] channels) => Call("PUBSUB".SubCommand("NUMSUB").Input(channels), rt => rt.ThrowOrValue((a, _) => a.MapToList((x, y) => y.ConvertTo<long>()).ToArray()));
public long PubSubNumPat() => Call("PUBLISH".SubCommand("NUMPAT"), rt => rt.ThrowOrValue<long>());
public void PUnSubscribe(params string[] pattern) => _pubsub.UnSubscribe(true, false, pattern);
public IDisposable Subscribe(string[] channels, Action<string, object> handler)
{
if (channels?.Any() != true) throw new ArgumentNullException(nameof(channels));
if (handler == null) throw new ArgumentNullException(nameof(handler));
return _pubsub.Subscribe(false, false, channels, (p, k, d) => handler(k, d));
}
public IDisposable Subscribe(string channel, Action<string, object> handler)
{
if (string.IsNullOrEmpty(channel)) throw new ArgumentNullException(nameof(channel));
if (handler == null) throw new ArgumentNullException(nameof(handler));
return _pubsub.Subscribe(false, false, new[] { channel }, (p, k, d) => handler(k, d));
}
public void UnSubscribe(params string[] channels) => _pubsub.UnSubscribe(false, false, channels);
class PubSubSubscribeDisposable : IPubSubSubscriber
{
PubSub _pubsub;
public RedisClient TopOwner => _pubsub._topOwner;
public IRedisSocket RedisSocket => _pubsub._redisSocket;
Action _release;
public PubSubSubscribeDisposable(PubSub pubsub, Action release)
{
_pubsub = pubsub;
_release = release;
}
public void Dispose() => _release?.Invoke();
}
//ERR only (P)SUBSCRIBE / (P)UNSUBSCRIBE / PING / QUIT allowed in this context
class PubSub : IDisposable
{
bool _stoped = false;
object _lock = new object();
internal RedisClient _topOwner;
internal IRedisSocket _redisSocket;
TimeSpan _redisSocketReceiveTimeoutOld;
internal bool IsSubscribed { get; private set; }
ConcurrentDictionary<Guid, string[]> _cancels = new ConcurrentDictionary<Guid, string[]>();
ConcurrentDictionary<string, ConcurrentDictionary<Guid, RegisterInfo>> _registers = new ConcurrentDictionary<string, ConcurrentDictionary<Guid, RegisterInfo>>();
const string _psub_regkey_prefix = "PSubscribe__ |";
const string _ssub_regkey_prefix = "SSubscribe__ |";
internal class RegisterInfo
{
public Guid Id { get; }
public Action<string, string, object> Handler { get; }
public DateTime RegTime { get; }
public RegisterInfo(Guid id, Action<string, string, object> handler, DateTime time)
{
this.Id = id;
this.Handler = handler;
this.RegTime = time;
}
}
internal PubSub(RedisClient topOwner)
{
_topOwner = topOwner;
}
public void Dispose()
{
_stoped = true;
Cancel(_cancels.Keys.ToArray());
}
internal void Cancel(params Guid[] ids)
{
if (ids == null) return;
var readyUnsubInterKeys = new List<string>();
foreach (var id in ids)
{
if (_cancels.TryRemove(id, out var oldkeys))
foreach (var oldkey in oldkeys)
{
if (_registers.TryGetValue(oldkey, out var oldrecvs) &&
oldrecvs.TryRemove(id, out var oldrecv) &&
oldrecvs.Any() == false)
readyUnsubInterKeys.Add(oldkey);
}
}
var unsub = readyUnsubInterKeys.Where(a => !a.StartsWith(_psub_regkey_prefix) && !a.StartsWith(_ssub_regkey_prefix)).ToArray();
var punsub = readyUnsubInterKeys.Where(a => a.StartsWith(_psub_regkey_prefix)).Select(a => a.Replace(_psub_regkey_prefix, "")).ToArray();
var sunsub = readyUnsubInterKeys.Where(a => a.StartsWith(_ssub_regkey_prefix)).Select(a => a.Replace(_ssub_regkey_prefix, "")).ToArray();
if (unsub.Any()) Call("UNSUBSCRIBE".Input(unsub));
if (punsub.Any()) Call("PUNSUBSCRIBE".Input(punsub));
if (sunsub.Any()) Call("SUNSUBSCRIBE".Input(punsub));
if (!_cancels.Any())
lock (_lock)
if (!_cancels.Any())
_redisSocket?.ReleaseSocket();
}
internal void UnSubscribe(bool punsub, bool sunsub, string[] channels)
{
channels = channels?.Distinct().Select(a =>
{
if (punsub) return $"{_psub_regkey_prefix}{a}";
if (sunsub) return $"{_ssub_regkey_prefix}{a}";
return a;
}).ToArray();
if (channels.Any() != true) return;
var ids = channels.Select(a => _registers.TryGetValue(a, out var tryval) ? tryval : null).Where(a => a != null).SelectMany(a => a.Keys).Distinct().ToArray();
Cancel(ids);
}
internal IDisposable Subscribe(bool psub, bool ssub, string[] channels, Action<string, string, object> handler)
{
if (_stoped) return new PubSubSubscribeDisposable(this, null);
channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
if (channels?.Any() != true) return new PubSubSubscribeDisposable(this, null);
var id = Guid.NewGuid();
var time = DateTime.Now;
var regkeys = channels.Select(a =>
{
if (psub) return $"{_psub_regkey_prefix}{a}";
if (ssub) return $"{_ssub_regkey_prefix}{a}";
return a;
}).ToArray();
for (var a = 0; a < regkeys.Length; a++)
{
ConcurrentDictionary<Guid, RegisterInfo> dict = null;
lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary<Guid, RegisterInfo>());
dict.TryAdd(id, new RegisterInfo(id, handler, time));
}
lock (_lock)
_cancels.TryAdd(id, regkeys);
var isnew = false;
if (IsSubscribed == false)
{
lock (_lock)
{
if (IsSubscribed == false)
{
_redisSocket = _topOwner.Adapter.GetRedisSocket(null);
IsSubscribed = isnew = true;
}
}
}
if (isnew)
{
_redisSocket.Connected += (_, e) =>
{
if (object.Equals(_, (_topOwner._pubsub._redisSocket as DefaultRedisSocket.TempProxyRedisSocket)?._owner))
{
var chans = _cancels.SelectMany(a => a.Value).ToList();
var resub = chans.Where(a => !a.StartsWith(_psub_regkey_prefix) && !a.StartsWith(_ssub_regkey_prefix)).ToArray();
var repsub = chans.Where(a => a.StartsWith(_psub_regkey_prefix)).Select(a => a.Replace(_psub_regkey_prefix, "")).ToArray();
var ressub = chans.Where(a => a.StartsWith(_ssub_regkey_prefix)).Select(a => a.Replace(_ssub_regkey_prefix, "")).ToArray();
if (resub.Any()) Call("SUBSCRIBE".Input(resub));
if (repsub.Any()) Call("PSUBSCRIBE".Input(repsub));
if (ressub.Any()) Call("SSUBSCRIBE".Input(repsub));
}
};
new Thread(() =>
{
_redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
_redisSocket.ReceiveTimeout = TimeSpan.Zero;
var timer = new Timer(state =>
{
try
{
_topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
}
catch (Exception ex)
{
Trace.WriteLine($"防止 IdleBus 超时回收异常: {ex.Message}");
}
try { _redisSocket.Write("PING"); } catch { }
}, null, 10000, 10000);
var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(_topOwner.ConnectionString.SubscribeReadbytes);
while (_stoped == false)
{
RedisResult rt = null;
try
{
rt = _redisSocket.Read(readCmd);
}
catch
{
Thread.CurrentThread.Join(100);
if (_cancels.Any()) continue;
break;
}
var val = rt.Value as object[];
if (val == null) continue; //special case
var val1 = val[0].ConvertTo<string>();
switch (val1)
{
case "pong":
case "punsubscribe":
case "sunsubscribe":
case "unsubscribe":
continue;
case "pmessage":
OnData(val[1].ConvertTo<string>(), false, val[2].ConvertTo<string>(), val[3]);
continue;
case "message":
OnData(null, false, val[1].ConvertTo<string>(), val[2]);
continue;
case "smessage":
OnData(null, true, val[1].ConvertTo<string>(), val[2]);
continue;
}
}
timer.Dispose();
lock (_lock)
{
IsSubscribed = false;
_redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
_redisSocket.ReleaseSocket();
_redisSocket.Dispose();
_redisSocket = null;
}
}).Start();
}
if (ssub) Call("SSUBSCRIBE".Input(channels));
else if (psub) Call(("PSUBSCRIBE").Input(channels));
else Call("SUBSCRIBE".Input(channels));
return new PubSubSubscribeDisposable(this, () => Cancel(id));
}
void OnData(string pattern, bool ssub, string key, object data)
{
var regkey = key;
if (pattern != null) regkey = $"{_psub_regkey_prefix}{pattern}";
if (ssub) regkey = $"{_ssub_regkey_prefix}{ key}";
if (_registers.TryGetValue(regkey, out var tryval) == false) return;
var multirecvs = tryval.Values.OrderBy(a => a.RegTime).ToArray(); //Execute in order
foreach (var recv in multirecvs)
recv.Handler(pattern, key, data);
}
internal void Call(CommandPacket cmd)
{
_topOwner.LogCall<object>(cmd, () =>
{
if (IsSubscribed == false)
throw new RedisClientException($"Subscription not opened, unable to execute");
if (_stoped == false && _redisSocket?.IsConnected == true)
lock (_lock)
_redisSocket?.Write(cmd);
return null;
});
}
}
}
} |
2881099/FreeRedis | 84,279 | src/FreeRedis/RedisClient/Strings.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
/// <summary>
/// APPEND command (An Asynchronous Version)<br /><br />
/// <br />
/// If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. <br /><br />
/// <br />
/// 若键值已存在且为字符串,则此命令将值附加在字符串的末尾;<br />
/// 若键值不存在,则会先创建一个空字符串,并附加值(在此情况下,APPEND 类似 SET 命令)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/append <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after the append operation.</returns>
public Task<long> AppendAsync<T>(string key, T value) => CallAsync("APPEND".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITCOUNT command (An Asynchronous Version)<br /><br />
/// <br />
/// Count the number of set bits (population counting) in a string.<br /><br />
/// <br />
/// 统计字符串中的位数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitcount <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>The number of set bits in the string. Non-existent keys are treated as empty strings and will return zero.</returns>
public Task<long> BitCountAsync(string key, long start, long end) => CallAsync("BITCOUNT".InputKey(key, start, end), rt => rt.ThrowOrValue<long>());
public Task<long[]> BitFieldAsync(string key, params BitFieldAction[] actions)
{
if (actions?.Any() != true) return null;
return CallAsync(GetBitFieldCommandPacket(key, actions), rt => rt.ThrowOrValue<long[]>());
}
/// <summary>
/// BITOP command (An Asynchronous Version) <br /><br />
/// <br />
/// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.<br /><br />
/// <br />
/// 在(包括字符串值)的多键之间按位运算,并将结果保存在目标键中。<br />
/// 目前支持 AND、OR、XOR 与 NOT 四种运算方式。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitop <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="operation">Bit operation type: AND, OR, XOR or NOT</param>
/// <param name="destkey">Destination Key</param>
/// <param name="keys">Multiple keys (containing string values)</param>
/// <returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns>
public Task<long> BitOpAsync(BitOpOperation operation, string destkey, params string[] keys) => CallAsync("BITOP".InputRaw(operation).InputKey(destkey).InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITPOS command (An Asynchronous Version) <br /><br />
/// <br />
/// Return the position of the first bit set to 1 or 0 in a string.<br />
/// The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position 8, and so forth.<br /><br />
/// <br />
/// 返回字符串中第一个 1 或 0 的位置。<br />
/// 注意,本命令将字符串视作位数组,自左向右计算,第一个字节在位置 0,第二个字节在位置 8,以此类推。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitpos <br />
/// Available since 2.8.7.
/// </summary>
/// <param name="key">Key</param>
/// <param name="bit">Bit value, 1 is true, 0 is false.</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>Returns the position of the first bit set to 1 or 0 according to the request.</returns>
public Task<long> BitPosAsync(string key, bool bit, long? start = null, long? end = null) => CallAsync("BITPOS"
.InputKey(key, bit ? "1" : "0")
.InputIf(start != null, start)
.InputIf(end != null, start), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECR command (An Asynchronous Version) <br /><br />
/// <br />
/// Decrements the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>the value of key after the decrement.</returns>
public Task<long> DecrAsync(string key) => CallAsync("DECR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECRBY command (An Asynchronous Version) <br /><br />
/// <br />
/// Decrements the number stored at key by decrement. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="decrement">The given value to be decreased.</param>
/// <returns>the value of key after the decrement.</returns>
public Task<long> DecrByAsync(string key, long decrement) => CallAsync("DECRBY".InputKey(key, decrement), rt => rt.ThrowOrValue<long>());
/// <summary>
/// GET command (An Asynchronous Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key, or nil when key does not exist.</returns>
public Task<string> GetAsync(string key) => CallAsync("GET".InputKey(key), rt => rt.ThrowOrValue<string>());
public Task<string> GetDelAsync(string key) => CallAsync("GETDEL".InputKey(key), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GET command (An Asynchronous Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <typeparam name="T"></typeparam>
/// <returns>The value of key, or nil when key does not exist.</returns>
public Task<T> GetAsync<T>(string key) => CallAsync("GET".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public Task<T> GetDelAsync<T>(string key) => CallAsync("GETDEL".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key and write to the stream.. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值并写入流中。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="destination">Destination stream</param>
/// <param name="bufferSize">Size</param>
public Task GetAsync(string key, Stream destination, int bufferSize = 1024) =>
GetStreamInternalAsync("GET", key, destination, bufferSize);
public Task GetDelAsync(string key, Stream destination, int bufferSize = 1024) =>
GetStreamInternalAsync("GETDEL", key, destination, bufferSize);
async public Task GetStreamInternalAsync(string command, string key, Stream destination, int bufferSize)
{
var cmd = command.InputKey(key);
await Adapter.TopOwner.LogCallAsync(cmd, async () =>
{
using (var rds = Adapter.GetRedisSocket(cmd))
{
await rds.WriteAsync(cmd);
await rds.ReadChunkAsync(destination, bufferSize);
}
return default(string);
});
}
/// <summary>
/// GETBIT command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the bit value at offset in the string value stored at key.<br /><br />
/// <br />
/// 返回键所对应字符串值中偏移量的位值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset</param>
/// <returns>The bit value stored at offset.</returns>
public Task<bool> GetBitAsync(string key, long offset) => CallAsync("GETBIT".InputKey(key, offset), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// GETRANGE command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <returns>The substring of the string value</returns>
public Task<string> GetRangeAsync(string key, long start, long end) => CallAsync("GETRANGE".InputKey(key, start, end), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GETRANGE command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public Task<T> GetRangeAsync<T>(string key, long start, long end) => CallAsync("GETRANGE".InputKey(key, start, end).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GETSET command (An Asynchronous Version) <br /><br />
/// <br />
/// Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value.<br /><br />
/// <br />
/// 以原子的方式将新值取代给定键的旧值,并返回旧值。如果该键存在但不包含字符串值时,返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getset <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">New value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The old value stored at key, or nil when key did not exist.</returns>
public Task<string> GetSetAsync<T>(string key, T value) => CallAsync("GETSET".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<string>());
/// <summary>
/// INCR command (An Asynchronous Version) <br /><br />
/// <br />
/// Increments the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key after the increment</returns>
public Task<long> IncrAsync(string key) => CallAsync("INCR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBY command (An Asynchronous Version) <br /><br />
/// <br />
/// Decrements the number stored at key by increment. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment</returns>
public Task<long> IncrByAsync(string key, long increment) => CallAsync("INCRBY".InputKey(key, increment), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBYFLOAT command (An Asynchronous Version) <br /><br />
/// <br />
/// Increment the string representing a floating point number stored at key by the specified increment. <br />
/// By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:<br />
/// - The key contains a value of the wrong type (not a string).<br />
/// - The current key content or the specified increment are not parsable as a double precision floating point number.<br />
/// If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.<br /><br />
/// <br />
/// 对该键的值加上给定的值,可以通过给定负值来减小对应键的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果发生以下情况,则返回错误:<br />
/// - 键所对应的值是错误的类型(不是字符串);<br />
/// - 该键的内容不能被解析为双精度浮点数。<br />
/// 如果命令执行成功,则将新值替换旧值,并返回给调用方。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment.</returns>
public Task<decimal> IncrByFloatAsync(string key, decimal increment) => CallAsync("INCRBYFLOAT".InputKey(key, increment), rt => rt.ThrowOrValue<decimal>());
/// <summary>
/// MGET command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <returns>A list of values at the specified keys.</returns>
public Task<string[]> MGetAsync(params string[] keys) => CallAsync("MGET".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// MGET command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <typeparam name="T"></typeparam>
/// <returns>A list of values at the specified keys.</returns>
public Task<T[]> MGetAsync<T>(params string[] keys) => CallAsync("MGET".InputKey(keys).FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
/// <summary>
/// MSET command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
public Task MSetAsync(string key, object value, params object[] keyValues) => MSetAsync<bool>(false, key, value, keyValues);
/// <summary>
/// MSET command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
public Task MSetAsync<T>(Dictionary<string, T> keyValues) => CallAsync("MSET".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
/// <summary>
/// MSETNX command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public Task<bool> MSetNxAsync(string key, object value, params object[] keyValues) => MSetAsync<bool>(true, key, value, keyValues);
/// <summary>
/// MSETNX command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public Task<bool> MSetNxAsync<T>(Dictionary<string, T> keyValues) => CallAsync("MSETNX".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// MSET key value [key value ...] command (An Asynchronous Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。如果不想覆盖现有的值,可以使用 MSETNX 指令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="nx">Mark whether it is NX mode. If it is, use the MSETNX command; otherwise, use the MSET command.</param>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>Always OK since MSET can't fail.</returns>
Task<T> MSetAsync<T>(bool nx, string key, object value, params object[] keyValues)
{
if (keyValues?.Any() == true)
return CallAsync((nx ? "MSETNX" : "MSET")
.InputKey(key).InputRaw(SerializeRedisValue(value))
.InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<T>());
return CallAsync((nx ? "MSETNX" : "MSET").InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<T>());
}
/// <summary>
/// PSETEX command (An Asynchronous Version) <br /><br />
/// <br />
/// PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// PSETEX 的工作方式与 SETEX 完全相同,唯一的区别是到期时间的单位是毫秒(ms),而不是秒(s)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/psetex <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="milliseconds">Timeout milliseconds value</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public Task PSetExAsync<T>(string key, long milliseconds, T value) => CallAsync("PSETEX".InputKey(key, milliseconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SET key value EX seconds (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value.<br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
public Task SetAsync<T>(string key, T value, int timeoutSeconds = 0) => SetAsync(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, false, false);
/// <summary>
/// SET key value KEEPTTL command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Retain the time to live associated with the key. <br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
public Task SetAsync<T>(string key, T value, bool keepTtl) => SetAsync(key, value, TimeSpan.Zero, keepTtl, false, false, false);
/// <summary>
/// SET key value EX seconds NX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
async public Task<bool> SetNxAsync<T>(string key, T value, int timeoutSeconds) => (await SetAsync(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, true, false, false)) == "OK";
/// <summary>
/// SET key value EX seconds NX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public async Task<bool> SetNxAsync<T>(string key, T value, TimeSpan timeout) => await SetAsync(key, value, timeout, false, true, false, false) == "OK";
/// <summary>
/// SET key value EX seconds XX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
async public Task<bool> SetXxAsync<T>(string key, T value, int timeoutSeconds = 0) => (await SetAsync(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, true, false)) == "OK";
/// <summary>
/// SET key value EX seconds XX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public async Task<bool> SetXxAsync<T>(string key, T value, TimeSpan timeout) => await SetAsync(key, value, timeout, false, false, true, false) == "OK";
/// <summary>
/// SET key value KEEPTTL XX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
async public Task<bool> SetXxAsync<T>(string key, T value, bool keepTtl) => (await SetAsync(key, value, TimeSpan.Zero, keepTtl, false, true, false)) == "OK";
/// <summary>
/// SET command (An Asynchronous Version) <br /><br />
///<br />
/// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <br /><br />
/// <br />
/// 设置键和值。如果该键已存在,则覆盖之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <param name="nx">Only set the key if it does not already exist.</param>
/// <param name="xx">Only set the key if it already exist.</param>
/// <param name="get"></param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public Task<string> SetAsync<T>(string key, T value, TimeSpan timeout, bool keepTtl, bool nx, bool xx, bool get) => CallAsync("SET"
.InputKey(key)
.InputRaw(SerializeRedisValue(value))
.InputIf(timeout.TotalSeconds >= 1, "EX", (long) timeout.TotalSeconds)
.InputIf(timeout.TotalSeconds < 1 && timeout.TotalMilliseconds >= 1, "PX", (long) timeout.TotalMilliseconds)
.InputIf(keepTtl, "KEEPTTL")
.InputIf(nx, "NX")
.InputIf(xx, "XX").InputIf(get, "GET"), rt => rt.ThrowOrValue<string>());
/// <summary>
/// SET key value EX seconds (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value.<br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout</param>
/// <typeparam name="T"></typeparam>
public Task SetAsync<T>(string key, T value, TimeSpan timeout) => SetAsync(key, value, timeout, false, false, false, false);
/// <summary>
/// SETBIT command (An Asynchronous Version) <br /><br />
///<br />
/// Sets or clears the bit at offset in the string value stored at key.<br /><br />
/// <br />
/// 设置或清除键值字符串指定偏移量的位(bit)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">New value</param>
/// <returns>The original bit value stored at offset.</returns>
public Task<long> SetBitAsync(string key, long offset, bool value) => CallAsync("SETBIT".InputKey(key, offset, value ? "1" : "0"), rt => rt.ThrowOrValue<long>());
/// <summary>
/// SETEX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold the string value and set key to timeout after a given number of seconds.<br /><br />
/// <br />
/// 设置键值在给定的秒数后超时。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setex <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="seconds">Seconds</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public Task SetExAsync<T>(string key, int seconds, T value) => CallAsync("SETEX".InputKey(key, seconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SETNX command (An Asynchronous Version) <br /><br />
/// <br />
/// Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. <br />
/// SETNX is short for "SET if Not eXists".<br /><br />
/// <br />
/// 如果键值不存在,则设置该键值,在此情况下与 SET 指令相似。当键值已经存在时,不执行任何操作。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setnx <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>Set result, specifically: 1 is if the key was set; 0 is if the key was not set.</returns>
public Task<bool> SetNxAsync<T>(string key, T value) => CallAsync("SETNX".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// SETRANGE command (An Asynchronous Version) <br /><br />
/// <br />
/// Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.<br /><br />
/// <br />
/// 从给定的偏移量开始覆盖键所对应的字符串值。如果偏移量大于值的长度,则为该字符串填充零字节(zero-bytes)以满足偏移量的要求。若键值不存在则视作空字符串值。故本指令将确保有足够长度的字符串以适应偏移量的要求。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setrange <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">The value to be filled.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after it was modified by the command.</returns>
public Task<long> SetRangeAsync<T>(string key, long offset, T value) => CallAsync("SETRANGE".InputKey(key, offset).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
//STRALGO LCS algo-specific-argument [algo-specific-argument ...]
/// <summary>
/// STRLRN command (An Asynchronous Version) <br /><br />
/// <br />
/// Returns the length of the string value stored at key. An error is returned when key holds a non-string value.<br /><br />
/// <br />
/// 返回键对应值字符串的长度。当该键对应的值不是字符串,则返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/strlen <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The length of the string at key, or 0 when key does not exist.</returns>
public Task<long> StrLenAsync(string key) => CallAsync("STRLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
#endregion
#endif
/// <summary>
/// APPEND command (A Synchronized Version)<br /><br />
/// <br />
/// If key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so APPEND will be similar to SET in this special case. <br /><br />
/// <br />
/// 若键值已存在且为字符串,则此命令将值附加在字符串的末尾;<br />
/// 若键值不存在,则会先创建一个空字符串,并附加值(在此情况下,APPEND 类似 SET 命令)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/append <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after the append operation.</returns>
public long Append<T>(string key, T value) => Call("APPEND".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITCOUNT command (A Synchronized Version)<br /><br />
/// <br />
/// Count the number of set bits (population counting) in a string.<br /><br />
/// <br />
/// 统计字符串中的位数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitcount <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>The number of set bits in the string. Non-existent keys are treated as empty strings and will return zero.</returns>
public long BitCount(string key, long start, long end) => Call("BITCOUNT".InputKey(key, start, end), rt => rt.ThrowOrValue<long>());
public long[] BitField(string key, params BitFieldAction[] actions)
{
if (actions?.Any() != true) return null;
return Call(GetBitFieldCommandPacket(key, actions), rt => rt.ThrowOrValue<long[]>());
}
CommandPacket GetBitFieldCommandPacket(string key, BitFieldAction[] actions)
{
var cmd = "BITFIELD".InputKey(key);
foreach (var opt in actions)
{
switch (opt.operation)
{
case BitFieldOperation.get:
cmd.InputIf(opt.arguments?.Length == 2, "GET");
cmd.InputIf(opt.arguments?.Length == 2, opt.arguments);
break;
case BitFieldOperation.overflow_wrap:
cmd.Input("OVERFLOW").Input("WRAP");
break;
case BitFieldOperation.overflow_sat:
cmd.Input("OVERFLOW").Input("SAT");
break;
case BitFieldOperation.overflow_fail:
cmd.Input("OVERFLOW").Input("FAIL");
break;
case BitFieldOperation.set:
cmd.InputIf(opt.arguments?.Length == 3, "GET");
cmd.InputIf(opt.arguments?.Length == 3, opt.arguments);
break;
case BitFieldOperation.incrby:
cmd.InputIf(opt.arguments?.Length == 3, "INCRBY");
cmd.InputIf(opt.arguments?.Length == 3, opt.arguments);
break;
}
}
return cmd;
}
/// <summary>
/// BITOP command (A Synchronized Version) <br /><br />
/// <br />
/// Perform a bitwise operation between multiple keys (containing string values) and store the result in the destination key.<br /><br />
/// <br />
/// 在(包括字符串值)的多键之间按位运算,并将结果保存在目标键中。<br />
/// 目前支持 AND、OR、XOR 与 NOT 四种运算方式。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitop <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="operation">Bit operation type: AND, OR, XOR or NOT</param>
/// <param name="destkey">Destination Key</param>
/// <param name="keys">Multiple keys (containing string values)</param>
/// <returns>The size of the string stored in the destination key, that is equal to the size of the longest input string.</returns>
public long BitOp(BitOpOperation operation, string destkey, params string[] keys) => Call("BITOP".InputRaw(operation).InputKey(destkey).InputKey(keys), rt => rt.ThrowOrValue<long>());
/// <summary>
/// BITPOS command (A Synchronized Version) <br /><br />
/// <br />
/// Return the position of the first bit set to 1 or 0 in a string.<br />
/// The position is returned, thinking of the string as an array of bits from left to right, where the first byte's most significant bit is at position 0, the second byte's most significant bit is at position 8, and so forth.<br /><br />
/// <br />
/// 返回字符串中第一个 1 或 0 的位置。<br />
/// 注意,本命令将字符串视作位数组,自左向右计算,第一个字节在位置 0,第二个字节在位置 8,以此类推。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/bitpos <br />
/// Available since 2.8.7.
/// </summary>
/// <param name="key">Key</param>
/// <param name="bit">Bit value, 1 is true, 0 is false.</param>
/// <param name="start">Index of the start. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <param name="end">Index of the end. It can contain negative values in order to index bytes starting from the end of the string.</param>
/// <returns>Returns the position of the first bit set to 1 or 0 according to the request.</returns>
public long BitPos(string key, bool bit, long? start = null, long? end = null) => Call("BITPOS"
.InputKey(key, bit ? "1" : "0")
.InputIf(start != null, start)
.InputIf(end != null, start), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECR command (A Synchronized Version) <br /><br />
/// <br />
/// Decrements the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>the value of key after the decrement.</returns>
public long Decr(string key) => Call("DECR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// DECRBY command (A Synchronized Version) <br /><br />
/// <br />
/// Decrements the number stored at key by decrement. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值减去给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/decrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="decrement">The given value to be decreased.</param>
/// <returns>the value of key after the decrement.</returns>
public long DecrBy(string key, long decrement) => Call("DECRBY".InputKey(key, decrement), rt => rt.ThrowOrValue<long>());
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key, or nil when key does not exist.</returns>
public string Get(string key) => Call("GET".InputKey(key), rt => rt.ThrowOrValue<string>());
public string GetDel(string key) => Call("GETDEL".InputKey(key), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <typeparam name="T"></typeparam>
/// <returns>The value of key, or nil when key does not exist.</returns>
public T Get<T>(string key) => Call("GET".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
public T GetDel<T>(string key) => Call("GETDEL".InputKey(key).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GET command (A Synchronized Version) <br /><br />
/// <br />
/// Get the value of key and write to the stream.. If the key does not exist the special value nil is returned. An error is returned if the value stored at key is not a string, because GET only handles string values.<br /><br />
/// <br />
/// 获得给定键的值并写入流中。若键不存在,则返回特殊的 nil 值。如果给定键的值不是字符串,则返回错误,因为 GET 指令只能处理字符串。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/get <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="destination">Destination stream</param>
/// <param name="bufferSize">Size</param>
public void Get(string key, Stream destination, int bufferSize = 1024) => GetStreamInternal("GET", key, destination, bufferSize);
public void GetDel(string key, Stream destination, int bufferSize = 1024) => GetStreamInternal("GETDEL", key, destination, bufferSize);
void GetStreamInternal(string command, string key, Stream destination, int bufferSize)
{
var cmd = command.InputKey(key);
Adapter.TopOwner.LogCall(cmd, () =>
{
using (var rds = Adapter.GetRedisSocket(cmd))
{
rds.Write(cmd);
rds.ReadChunk(destination, bufferSize);
}
return default(string);
});
}
/// <summary>
/// GETBIT command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the bit value at offset in the string value stored at key.<br /><br />
/// <br />
/// 返回键所对应字符串值中偏移量的位值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset</param>
/// <returns>The bit value stored at offset.</returns>
public bool GetBit(string key, long offset) => Call("GETBIT".InputKey(key, offset), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// GETRANGE command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <returns>The substring of the string value</returns>
public string GetRange(string key, long start, long end) => Call("GETRANGE".InputKey(key, start, end), rt => rt.ThrowOrValue<string>());
/// <summary>
/// GETRANGE command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive).<br /><br />
/// <br />
/// 返回键值的子字符串该字符串由偏移量 start 和 end 来确定(两端均闭包)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getrange <br />
/// Available since 2.0.0. It is called SUBSTR in Redis versions <= 2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="start">Start</param>
/// <param name="end">End</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetRange<T>(string key, long start, long end) => Call("GETRANGE".InputKey(key, start, end).FlagReadbytes(true), rt => rt.ThrowOrValue(a => DeserializeRedisValue<T>(a.ConvertTo<byte[]>(), rt.Encoding)));
/// <summary>
/// GETSET command (A Synchronized Version) <br /><br />
/// <br />
/// Atomically sets key to value and returns the old value stored at key. Returns an error when key exists but does not hold a string value.<br /><br />
/// <br />
/// 以原子的方式将新值取代给定键的旧值,并返回旧值。如果该键存在但不包含字符串值时,返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/getset <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">New value</param>
/// <typeparam name="T"></typeparam>
/// <returns>The old value stored at key, or nil when key did not exist.</returns>
public string GetSet<T>(string key, T value) => Call("GETSET".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<string>());
/// <summary>
/// INCR command (A Synchronized Version) <br /><br />
/// <br />
/// Increments the number stored at key by one. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上 1。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incr <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The value of key after the increment</returns>
public long Incr(string key) => Call("INCR".InputKey(key), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBY command (A Synchronized Version) <br /><br />
/// <br />
/// Decrements the number stored at key by increment. <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if the key contains a value of the wrong type or contains a string that can not be represented as integer. <br />
/// This operation is limited to 64 bit signed integers.<br /><br />
/// <br />
/// 对该键的值加上给定的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果键对应的值是个错误类型或不能表达为整数的字符串,则返回错误。此操作仅限于 64 位有符号整数。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment</returns>
public long IncrBy(string key, long increment) => Call("INCRBY".InputKey(key, increment), rt => rt.ThrowOrValue<long>());
/// <summary>
/// INCRBYFLOAT command (A Synchronized Version) <br /><br />
/// <br />
/// Increment the string representing a floating point number stored at key by the specified increment. <br />
/// By using a negative increment value, the result is that the value stored at the key is decremented (by the obvious properties of addition). <br />
/// If the key does not exist, it is set to 0 before performing the operation. An error is returned if one of the following conditions occur:<br />
/// - The key contains a value of the wrong type (not a string).<br />
/// - The current key content or the specified increment are not parsable as a double precision floating point number.<br />
/// If the command is successful the new incremented value is stored as the new value of the key (replacing the old one), and returned to the caller as a string.<br /><br />
/// <br />
/// 对该键的值加上给定的值,可以通过给定负值来减小对应键的值。<br />
/// 如果键值不存在,则在操作前先设置为 0。如果发生以下情况,则返回错误:<br />
/// - 键所对应的值是错误的类型(不是字符串);<br />
/// - 该键的内容不能被解析为双精度浮点数。<br />
/// 如果命令执行成功,则将新值替换旧值,并返回给调用方。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/incrby <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="increment">The given value to be increased.</param>
/// <returns>The value of key after the increment.</returns>
public decimal IncrByFloat(string key, decimal increment) => Call("INCRBYFLOAT".InputKey(key, increment), rt => rt.ThrowOrValue<decimal>());
/// <summary>
/// MGET command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <returns>A list of values at the specified keys.</returns>
public string[] MGet(params string[] keys) => Call("MGET".InputKey(keys), rt => rt.ThrowOrValue<string[]>());
/// <summary>
/// MGET command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the values of all specified keys. For every key that does not hold a string value or does not exist, the special value nil is returned. Because of this, the operation never fails.<br /><br />
/// <br />
/// 返回所有给定键的值,对于其中个别键不存在,或其值不为字符串的,反悔特殊的 nil 值,因此 MGET 指令永远不会执行失败。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mget <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="keys">Key list</param>
/// <typeparam name="T"></typeparam>
/// <returns>A list of values at the specified keys.</returns>
public T[] MGet<T>(params string[] keys) => Call("MGET".InputKey(keys).FlagReadbytes(true), rt => rt
.ThrowOrValue((a, _) => a.Select(b => DeserializeRedisValue<T>(b.ConvertTo<byte[]>(), rt.Encoding)).ToArray()));
/// <summary>
/// MSET command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
public void MSet(string key, object value, params object[] keyValues) => MSet<bool>(false, key, value, keyValues);
/// <summary>
/// MSET command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. <br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
public void MSet<T>(Dictionary<string, T> keyValues) => Call("MSET".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<string>());
/// <summary>
/// MSETNX command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public bool MSetNx(string key, object value, params object[] keyValues) => MSet<bool>(true, key, value, keyValues);
/// <summary>
/// MSETNX command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSETNX will not perform any operation at all even if just a single key already exists.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。只要有一个键已经存在,则整组键值都将不会被设置。 <br /><br />
/// <br />
/// Document link: https://redis.io/commands/msetnx <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="keyValues">Key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>True if the all the keys were set. False if no key was set (at least one key already existed).</returns>
public bool MSetNx<T>(Dictionary<string, T> keyValues) => Call("MSETNX".SubCommand(null).InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// MSET key value [key value ...] command (A Synchronized Version) <br /><br />
/// <br />
/// Sets the given keys to their respective values. MSET replaces existing values with new values, just as regular SET. See MSETNX if you don't want to overwrite existing values.<br /><br />
/// <br />
/// 将给定键的值设置为对应的新值。如果不想覆盖现有的值,可以使用 MSETNX 指令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/mset <br />
/// Available since 1.0.1.
/// </summary>
/// <param name="nx">Mark whether it is NX mode. If it is, use the MSETNX command; otherwise, use the MSET command.</param>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keyValues">Other key-value sets</param>
/// <typeparam name="T"></typeparam>
/// <returns>Always OK since MSET can't fail.</returns>
T MSet<T>(bool nx, string key, object value, params object[] keyValues)
{
if (keyValues?.Any() == true)
return Call((nx ? "MSETNX" : "MSET")
.InputKey(key).InputRaw(SerializeRedisValue(value))
.InputKv(keyValues, true, SerializeRedisValue), rt => rt.ThrowOrValue<T>());
return Call((nx ? "MSETNX" : "MSET").InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<T>());
}
/// <summary>
/// PSETEX command (A Synchronized Version) <br /><br />
/// <br />
/// PSETEX works exactly like SETEX with the sole difference that the expire time is specified in milliseconds instead of seconds.<br /><br />
/// <br />
/// PSETEX 的工作方式与 SETEX 完全相同,唯一的区别是到期时间的单位是毫秒(ms),而不是秒(s)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/psetex <br />
/// Available since 2.6.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="milliseconds">Timeout milliseconds value</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public void PSetEx<T>(string key, long milliseconds, T value) => Call("PSETEX".InputKey(key, milliseconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SET key value EX seconds (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value.<br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
public void Set<T>(string key, T value, int timeoutSeconds = 0) => Set(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, false, false);
/// <summary>
/// SET key value EX seconds (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value.<br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout</param>
/// <typeparam name="T"></typeparam>
public void Set<T>(string key, T value, TimeSpan timeout) => Set(key, value, timeout, false, false, false, false);
/// <summary>
/// SET key value KEEPTTL command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Retain the time to live associated with the key. <br /><br />
/// <br />
/// 设置键和值。<br /><br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
public void Set<T>(string key, T value, bool keepTtl) => Set(key, value, TimeSpan.Zero, keepTtl, false, false, false);
/// <summary>
/// SET key value EX seconds NX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetNx<T>(string key, T value, int timeoutSeconds) => Set(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, true, false, false) == "OK";
/// <summary>
/// SET key value EX seconds NX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it does not already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值不存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetNx<T>(string key, T value, TimeSpan timeout) => Set(key, value, timeout, false, true, false, false) == "OK";
/// <summary>
/// SET key value EX seconds XX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeoutSeconds">Timeout seconds</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetXx<T>(string key, T value, int timeoutSeconds = 0) => Set(key, value, TimeSpan.FromSeconds(timeoutSeconds), false, false, true, false) == "OK";
/// <summary>
/// SET key value EX seconds XX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 2.6.12.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetXx<T>(string key, T value, TimeSpan timeout) => Set(key, value, timeout, false, false, true, false) == "OK";
/// <summary>
/// SET key value KEEPTTL XX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. Only set the key if it already exist.<br /><br />
/// <br />
/// 设置键和值。当且仅当键值已存在时才执行命令。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public bool SetXx<T>(string key, T value, bool keepTtl) => Set(key, value, TimeSpan.Zero, keepTtl, false, true, false) == "OK";
/// <summary>
/// SET command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. <br /><br />
/// <br />
/// 设置键和值。如果该键已存在,则覆盖之。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/set <br />
/// Available since 6.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <param name="timeout">Timeout value</param>
/// <param name="keepTtl">Retain the time to live associated with the key</param>
/// <param name="nx">Only set the key if it does not already exist.</param>
/// <param name="xx">Only set the key if it already exist.</param>
/// <param name="get">Return the old value stored at key, or nil when key did not exist.</param>
/// <typeparam name="T"></typeparam>
/// <returns>
/// Simple string reply: OK if SET was executed correctly.<br />
/// Bulk string reply: when GET option is set, the old value stored at key, or nil when key did not exist.<br />
/// Null reply: a Null Bulk Reply is returned if the SET operation was not performed because the user specified the NX or XX option but the condition was not met or if user specified the NX and GET options that do not met.
/// </returns>
public string Set<T>(string key, T value, TimeSpan timeout, bool keepTtl, bool nx, bool xx, bool get) => Call("SET"
.InputKey(key)
.InputRaw(SerializeRedisValue(value))
.InputIf(timeout.TotalSeconds >= 1, "EX", (long) timeout.TotalSeconds)
.InputIf(timeout.TotalSeconds < 1 && timeout.TotalMilliseconds >= 1, "PX", (long) timeout.TotalMilliseconds)
.InputIf(keepTtl, "KEEPTTL")
.InputIf(nx, "NX")
.InputIf(xx, "XX")
.InputIf(get, "GET"), rt => rt.ThrowOrValue<string>());
/// <summary>
/// SETBIT command (A Synchronized Version) <br /><br />
/// <br />
/// Sets or clears the bit at offset in the string value stored at key.<br /><br />
/// <br />
/// 设置或清除键值字符串指定偏移量的位(bit)。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setbit <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">New value</param>
/// <returns>The original bit value stored at offset.</returns>
public long SetBit(string key, long offset, bool value) => Call("SETBIT".InputKey(key, offset, value ? "1" : "0"), rt => rt.ThrowOrValue<long>());
/// <summary>
/// SETEX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold the string value and set key to timeout after a given number of seconds.<br /><br />
/// <br />
/// 设置键值在给定的秒数后超时。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setex <br />
/// Available since 2.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="seconds">Seconds</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
public void SetEx<T>(string key, int seconds, T value) => Call("SETEX".InputKey(key, seconds).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrNothing());
/// <summary>
/// SETNX command (A Synchronized Version) <br /><br />
/// <br />
/// Set key to hold string value if key does not exist. In that case, it is equal to SET. When key already holds a value, no operation is performed. <br />
/// SETNX is short for "SET if Not eXists".<br /><br />
/// <br />
/// 如果键值不存在,则设置该键值,在此情况下与 SET 指令相似。当键值已经存在时,不执行任何操作。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setnx <br />
/// Available since 1.0.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="value">Value</param>
/// <typeparam name="T"></typeparam>
/// <returns>Set result, specifically: 1 is if the key was set; 0 is if the key was not set.</returns>
public bool SetNx<T>(string key, T value) => Call("SETNX".InputKey(key).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<bool>());
/// <summary>
/// SETRANGE command (A Synchronized Version) <br /><br />
/// <br />
/// Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. If the offset is larger than the current length of the string at key, the string is padded with zero-bytes to make offset fit. Non-existing keys are considered as empty strings, so this command will make sure it holds a string large enough to be able to set value at offset.<br /><br />
/// <br />
/// 从给定的偏移量开始覆盖键所对应的字符串值。如果偏移量大于值的长度,则为该字符串填充零字节(zero-bytes)以满足偏移量的要求。若键值不存在则视作空字符串值。故本指令将确保有足够长度的字符串以适应偏移量的要求。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/setrange <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <param name="offset">Offset value</param>
/// <param name="value">The value to be filled.</param>
/// <typeparam name="T"></typeparam>
/// <returns>The length of the string after it was modified by the command.</returns>
public long SetRange<T>(string key, long offset, T value) => Call("SETRANGE".InputKey(key, offset).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long>());
//STRALGO LCS algo-specific-argument [algo-specific-argument ...]
/// <summary>
/// STRLRN command (A Synchronized Version) <br /><br />
/// <br />
/// Returns the length of the string value stored at key. An error is returned when key holds a non-string value.<br /><br />
/// <br />
/// 返回键对应值字符串的长度。当该键对应的值不是字符串,则返回错误。<br /><br />
/// <br />
/// Document link: https://redis.io/commands/strlen <br />
/// Available since 2.2.0.
/// </summary>
/// <param name="key">Key</param>
/// <returns>The length of the string at key, or 0 when key does not exist.</returns>
public long StrLen(string key) => Call("STRLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
}
} |
2881099/FreeRedis | 4,611 | src/FreeRedis/Internal/IdleBus/IdleBus`1.ThreadScan.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace FreeRedis.Internal
{
partial class IdleBus<TKey, TValue>
{
bool _threadStarted = false;
object _threadStartedLock = new object();
void ThreadScanWatch(ItemInfo item)
{
var startThread = false;
if (_threadStarted == false)
lock (_threadStartedLock)
if (_threadStarted == false)
startThread = _threadStarted = true;
if (startThread)
new Thread(() =>
{
this.ThreadScanWatchHandler();
lock (_threadStartedLock)
_threadStarted = false;
}).Start();
}
public class TimeoutScanOptions
{
/// <summary>
/// 扫描线程间隔(默认值:2秒)
/// </summary>
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(2);
/// <summary>
/// 扫描线程空闲多少秒退出(默认值:10秒)
/// </summary>
public int QuitWaitSeconds { get; set; } = 10;
/// <summary>
/// 扫描的每批数量(默认值:512)<para></para>
/// 可防止注册数量太多时导致 CPU 占用过高
/// </summary>
public int BatchQuantity { get; set; } = 512;
/// <summary>
/// 达到扫描的每批数量时,线程等待(默认值:1秒)
/// </summary>
public TimeSpan BatchQuantityWait { get; set; } = TimeSpan.FromSeconds(1);
}
/// <summary>
/// 扫描过期对象的设置<para></para>
/// 机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。<para></para>
/// 连续多少秒都没存活的对象时,才退出扫描。
/// </summary>
public TimeoutScanOptions ScanOptions { get; } = new TimeoutScanOptions();
void ThreadScanWatchHandler()
{
var couter = 0;
while (IsDisposed == false)
{
if (ThreadJoin(ScanOptions.Interval) == false) return;
this.InternalRemoveDelayHandler();
if (_usageQuantity == 0)
{
couter = couter + (int)ScanOptions.Interval.TotalSeconds;
if (couter < ScanOptions.QuitWaitSeconds) continue;
break;
}
couter = 0;
var keys = _dic.Keys.ToArray();
long keysIndex = 0;
foreach (var key in keys)
{
if (IsDisposed) return;
++keysIndex;
if (ScanOptions.BatchQuantity > 0 && keysIndex % ScanOptions.BatchQuantity == 0)
{
if (ThreadJoin(ScanOptions.BatchQuantityWait) == false) return;
}
if (_dic.TryGetValue(key, out var item) == false) continue;
if (item.value == null) continue;
if (DateTime.Now.Subtract(item.lastActiveTime) <= item.idle) continue;
try
{
var now = DateTime.Now;
if (item.Release(() => DateTime.Now.Subtract(item.lastActiveTime) > item.idle && item.lastActiveTime >= item.createTime))
//防止并发有其他线程创建,最后活动时间 > 创建时间
this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, null, $"{key} ---自动释放成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{_usageQuantity}/{Quantity}"));
}
catch (Exception ex)
{
this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, ex, $"{key} ---自动释放执行出错:{ex.Message}"));
}
}
}
}
bool ThreadJoin(TimeSpan interval)
{
if (interval <= TimeSpan.Zero) return true;
var milliseconds = interval.TotalMilliseconds;
var seconds = Math.Floor(milliseconds / 1000);
milliseconds = milliseconds - seconds * 1000;
for (var a = 0; a < seconds; a++)
{
Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
if (IsDisposed) return false;
}
for (var a = 0; a < milliseconds; a += 200)
{
Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200));
if (IsDisposed) return false;
}
return true;
}
}
} |
2881099/FreeRedis | 9,281 | src/FreeRedis/Internal/IdleBus/IdleBus`1.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
namespace FreeRedis.Internal
{
/// <summary>
/// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
/// </summary>
public partial class IdleBus<TKey, TValue> : IDisposable where TValue : class, IDisposable
{
ConcurrentDictionary<TKey, ItemInfo> _dic;
ConcurrentDictionary<string, ItemInfo> _removePending;
object _usageLock = new object();
int _usageQuantity;
TimeSpan _defaultIdle;
/// <summary>
/// 按空闲时间1分钟,创建空闲容器
/// </summary>
public IdleBus() : this(TimeSpan.FromMinutes(1)) { }
/// <summary>
/// 指定空闲时间、创建空闲容器
/// </summary>
/// <param name="idle">空闲时间</param>
public IdleBus(TimeSpan idle)
{
_dic = new ConcurrentDictionary<TKey, ItemInfo>();
_removePending = new ConcurrentDictionary<string, ItemInfo>();
_usageQuantity = 0;
_defaultIdle = idle;
}
/// <summary>
/// 根据 key 获得或创建【实例】(线程安全)<para></para>
/// key 未注册时,抛出异常
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public TValue Get(TKey key)
{
if (IsDisposed) throw new Exception($"{key} 实例获取失败,{nameof(IdleBus<TValue>)} 对象已释放");
if (_dic.TryGetValue(key, out var item) == false)
{
var error = new Exception($"{key} 实例获取失败,因为没有注册");
this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, error, error.Message));
throw error;
}
var now = DateTime.Now;
var ret = item.GetOrCreate();
if (item.IsRegisterError)
{
this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, null, $"{key} 实例获取失败:检测到注册实例的参数 create 返回了相同的实例,应该每次返回新实例,正确:() => new Xxx(),错误:() => 变量"));
throw new ArgumentException($"{key} 实例获取失败:检测到注册实例的参数 create 返回了相同的实例,应该每次返回新实例,正确:() => new Xxx(),错误:() => 变量");
}
var tsms = DateTime.Now.Subtract(now).TotalMilliseconds;
this.OnNotice(new NoticeEventArgs(NoticeType.Get, key, null, $"{key} 实例获取成功 {item.activeCounter}次{(tsms > 5 ? $",耗时 {tsms}ms" : "")}"));
//this.ThreadLiveWatch(item); //这种模式采用 Sorted 性能会比较慢
this.ThreadScanWatch(item); //这种在后台扫描 _dic,定时要求可能没那么及时
return ret;
}
/// <summary>
/// 获得或创建所有【实例】(线程安全)
/// </summary>
/// <returns></returns>
public List<TValue> GetAll() => _dic.Keys.ToArray().Select(a => Get(a)).ToList();
/// <summary>
/// 获得所有已注册的 key(线程安全)
/// </summary>
/// <returns></returns>
public TKey[] GetKeys(Func<TValue, bool> filter = null)
{
if (filter == null) return _dic.Keys.ToArray();
return _dic.Keys.ToArray().Where(key => _dic.TryGetValue(key, out var item) && filter(item.value)).ToArray();
}
/// <summary>
/// 判断 key 是否注册
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Exists(TKey key)
{
if (key == null) return false;
return _dic.ContainsKey(key);
}
/// <summary>
/// 注册【实例】
/// </summary>
/// <param name="key"></param>
/// <param name="create">实例创建方法</param>
/// <returns></returns>
public IdleBus<TKey, TValue> Register(TKey key, Func<TValue> create)
{
InternalRegister(key, create, null, true);
return this;
}
public IdleBus<TKey, TValue> Register(TKey key, Func<TValue> create, TimeSpan idle)
{
InternalRegister(key, create, idle, true);
return this;
}
public bool TryRegister(TKey key, Func<TValue> create) => InternalRegister(key, create, null, false);
public bool TryRegister(TKey key, Func<TValue> create, TimeSpan idle) => InternalRegister(key, create, idle, false);
public bool TryRemove(TKey key, bool now = false) => InternalRemove(key, now, false);
/// <summary>
/// 已创建【实例】数量
/// </summary>
public int UsageQuantity => _usageQuantity;
/// <summary>
/// 注册数量
/// </summary>
public int Quantity => _dic.Count;
/// <summary>
/// 通知事件
/// </summary>
public event EventHandler<NoticeEventArgs> Notice;
bool InternalRegister(TKey key, Func<TValue> create, TimeSpan? idle, bool isThrow)
{
if (IsDisposed)
{
if (isThrow) throw new Exception($"{key} 注册失败,{nameof(IdleBus<TValue>)} 对象已释放");
return false;
}
var error = new Exception($"{key} 注册失败,请勿重复注册");
if (_dic.ContainsKey(key))
{
this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, error, error.Message));
if (isThrow) throw error;
return false;
}
if (idle == null) idle = _defaultIdle;
//if (idle < TimeSpan.FromSeconds(5))
//{
// var limitError = new Exception($"{key} 注册失败,{nameof(idle)} 参数必须 >= 5秒");
// this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, limitError, limitError.Message));
// if (isThrow) throw error;
// return this;
//}
var added = _dic.TryAdd(key, new ItemInfo
{
ib = this,
key = key,
create = create,
idle = idle.Value,
});
if (added == false)
{
this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, error, error.Message));
if (isThrow) throw error;
return false;
}
this.OnNotice(new NoticeEventArgs(NoticeType.Register, key, null, $"{key} 注册成功,{_usageQuantity}/{Quantity}"));
return true;
}
bool InternalRemove(TKey key, bool isNow, bool isThrow)
{
if (IsDisposed)
{
if (isThrow) throw new Exception($"{key} 删除失败 ,{nameof(IdleBus<TValue>)} 对象已释放");
return false;
}
if (_dic.TryRemove(key, out var item) == false)
{
var error = new Exception($"{key} 删除失败 ,因为没有注册");
this.OnNotice(new NoticeEventArgs(NoticeType.Remove, key, error, error.Message));
if (isThrow) throw error;
return false;
}
Interlocked.Exchange(ref item.releaseErrorCounter, 0);
if (isNow)
{
item.Release(() => true);
this.OnNotice(new NoticeEventArgs(NoticeType.Remove, item.key, null, $"{key} 删除成功,{_usageQuantity}/{Quantity}"));
return true;
}
item.lastActiveTime = DateTime.Now;
if (item.value == null) item.lastActiveTime = DateTime.Now.Subtract(item.idle).AddSeconds(-60); //延时删除
_removePending.TryAdd(Guid.NewGuid().ToString(), item);
this.OnNotice(new NoticeEventArgs(NoticeType.Remove, item.key, null, $"{key} 删除成功,并且已标记为延时释放,{_usageQuantity}/{Quantity}"));
return true;
}
void InternalRemoveDelayHandler()
{
//处理延时删除
var removeKeys = _removePending.Keys;
foreach (var removeKey in removeKeys)
{
if (_removePending.TryGetValue(removeKey, out var removeItem) == false) continue;
if (DateTime.Now.Subtract(removeItem.lastActiveTime) <= removeItem.idle) continue;
try
{
removeItem.Release(() => true);
}
catch (Exception ex)
{
var tmp1 = Interlocked.Increment(ref removeItem.releaseErrorCounter);
this.OnNotice(new NoticeEventArgs(NoticeType.Remove, removeItem.key, ex, $"{removeKey} ---延时释放执行出错({tmp1}次):{ex.Message}"));
if (tmp1 < 3)
continue;
}
removeItem.Dispose();
_removePending.TryRemove(removeKey, out var oldItem);
}
}
void OnNotice(NoticeEventArgs e)
{
this.Notice?.Invoke(this, e);
}
#region Dispose
~IdleBus() => Dispose();
public bool IsDisposed { get; private set; }
object isdisposedLock = new object();
public void Dispose()
{
if (IsDisposed) return;
lock (isdisposedLock)
{
if (IsDisposed) return;
IsDisposed = true;
}
foreach (var item in _removePending.Values) item.Dispose();
foreach (var item in _dic.Values) item.Dispose();
_removePending.Clear();
_dic.Clear();
_usageQuantity = 0;
}
#endregion
}
} |
2881099/FreeRedis | 3,796 | src/FreeRedis/Internal/IdleBus/IdleBus`1.ItemInfo.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace FreeRedis.Internal
{
partial class IdleBus<TKey, TValue>
{
class ItemInfo : IDisposable
{
internal IdleBus<TKey, TValue> ib;
internal TKey key;
internal Func<TValue> create;
internal TimeSpan idle;
internal DateTime createTime;
internal DateTime lastActiveTime;
internal long activeCounter;
internal int releaseErrorCounter;
internal TValue value { get; private set; }
internal TValue firstValue { get; private set; }
internal bool IsRegisterError { get; private set; }
object valueLock = new object();
internal TValue GetOrCreate()
{
if (isdisposed == true) return null;
if (value == null)
{
var iscreate = false;
var now = DateTime.Now;
try
{
lock (valueLock)
{
if (isdisposed == true) return null;
if (value == null)
{
value = create();
createTime = DateTime.Now;
Interlocked.Increment(ref ib._usageQuantity);
iscreate = true;
}
else
{
return value;
}
}
if (iscreate)
{
if (value != null)
{
if (firstValue == null) firstValue = value; //记录首次值
else if (firstValue == value) IsRegisterError = true; //第二次与首次相等,注册姿势错误
}
ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, null, $"{key} 实例+++创建成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{ib._usageQuantity}/{ib.Quantity}"));
}
}
catch (Exception ex)
{
ib.OnNotice(new NoticeEventArgs(NoticeType.AutoCreate, key, ex, $"{key} 实例+++创建失败:{ex.Message}"));
throw;
}
}
lastActiveTime = DateTime.Now;
Interlocked.Increment(ref activeCounter);
return value;
}
internal bool Release(Func<bool> lockInIf)
{
lock (valueLock)
{
if (value != null && lockInIf())
{
value?.Dispose();
value = null;
Interlocked.Decrement(ref ib._usageQuantity);
Interlocked.Exchange(ref activeCounter, 0);
return true;
}
}
return false;
}
~ItemInfo() => Dispose();
bool isdisposed = false;
public void Dispose()
{
if (isdisposed) return;
lock (valueLock)
{
if (isdisposed) return;
isdisposed = true;
}
try
{
Release(() => true);
}
catch { }
}
}
}
} |
2881099/FreeRedis | 1,092 | src/FreeRedis/Internal/IdleBus/IdleBus.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace FreeRedis.Internal
{
/// <summary>
/// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
/// </summary>
public class IdleBus : IdleBus<string, IDisposable>
{
/// <summary>
/// 按空闲时间1分钟,创建空闲容器
/// </summary>
public IdleBus() : base() { }
/// <summary>
/// 指定空闲时间、创建空闲容器
/// </summary>
/// <param name="idle">空闲时间</param>
public IdleBus(TimeSpan idle) : base(idle) { }
}
/// <summary>
/// 空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
/// </summary>
public class IdleBus<TValue> : IdleBus<string, TValue> where TValue : class, IDisposable
{
/// <summary>
/// 按空闲时间1分钟,创建空闲容器
/// </summary>
public IdleBus() : base() { }
/// <summary>
/// 指定空闲时间、创建空闲容器
/// </summary>
/// <param name="idle">空闲时间</param>
public IdleBus(TimeSpan idle) : base(idle) { }
}
} |
2881099/FreeRedis | 1,106 | src/FreeRedis/Internal/IdleBus/IdleBus`1.Test.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace FreeRedis.Internal
{
partial class IdleBus<TKey, TValue>
{
public static void Test()
{
//超过1分钟没有使用,连续检测2次都这样,就销毁【实例】
var ib = new IdleBus<string, IDisposable>(TimeSpan.FromMinutes(1));
ib.Notice += (_, e) =>
{
var log = $"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e.Log}";
//Trace.WriteLine(log);
Console.WriteLine(log);
};
ib.Register("key1", () => new ManualResetEvent(false));
ib.Register("key2", () => new AutoResetEvent(false));
var item = ib.Get("key2") as AutoResetEvent;
//获得 key2 对象,创建
item = ib.Get("key2") as AutoResetEvent;
//获得 key2 对象,已创建
int num1 = ib.UsageQuantity;
//【实例】有效数量(即已经创建了的),后台定时清理不活跃的【实例】,此值就会减少
ib.Dispose();
}
}
} |
2881099/FreeRedis | 10,641 | src/FreeRedis/Internal/AsyncTestCode/AsyncRedisSocket.cs | //#if isasync
//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.IO;
//using System.Linq;
//using System.Net;
//using System.Net.Sockets;
//using System.Text;
//using System.Threading;
//using System.Threading.Tasks;
//namespace FreeRedis.Internal
//{
// class AsyncRedisSocket
// {
// internal class Manager
// {
// RedisClient.BaseAdapter _adapter;
// public Manager(RedisClient.BaseAdapter adapter)
// {
// _adapter = adapter;
// }
// List<AsyncRedisSocket> _asyncRedisSockets = new List<AsyncRedisSocket>();
// int _asyncRedisSocketsCount = 0;
// long _asyncRedisSocketsConcurrentCounter = 0;
// object _asyncRedisSocketsLock = new object();
// public AsyncRedisSocket GetAsyncRedisSocket(CommandPacket cmd)
// {
// AsyncRedisSocket asyncRds = null;
// Interlocked.Increment(ref _asyncRedisSocketsConcurrentCounter);
// for (var limit = 0; limit < 1000; limit += 1)
// {
// if (_asyncRedisSocketsCount > 0)
// {
// lock (_asyncRedisSocketsLock)
// {
// if (_asyncRedisSockets.Count > 0)
// {
// asyncRds = _asyncRedisSockets[RedisClient.BaseAdapter._rnd.Value.Next(_asyncRedisSockets.Count)];
// Interlocked.Increment(ref asyncRds._writeCounter);
// Interlocked.Decrement(ref _asyncRedisSocketsConcurrentCounter);
// return asyncRds;
// }
// }
// }
// if (limit > 50 && _asyncRedisSocketsConcurrentCounter < 2) break;
// if (_asyncRedisSocketsCount > 1) Thread.CurrentThread.Join(2);
// }
// NewAsyncRedisSocket();
// //AsyncRedisSocket.sb.AppendLine($"线程{Thread.CurrentThread.ManagedThreadId}:AsyncRedisSockets 数量 {_asyncRedisSocketsCount} {_asyncRedisSocketsConcurrentCounter}");
// Interlocked.Decrement(ref _asyncRedisSocketsConcurrentCounter);
// return asyncRds;
// void NewAsyncRedisSocket()
// {
// var rds = _adapter.GetRedisSocket(cmd);
// var key = Guid.NewGuid();
// asyncRds = new AsyncRedisSocket(rds, () =>
// {
// if (_asyncRedisSocketsConcurrentCounter > 0 || _asyncRedisSocketsCount > 1) Thread.CurrentThread.Join(8);
// Interlocked.Decrement(ref _asyncRedisSocketsCount);
// lock (_asyncRedisSocketsLock)
// _asyncRedisSockets.Remove(asyncRds);
// }, (innerRds, ioex) =>
// {
// if (ioex != null && ioex is ProtocolViolationException == false) (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool.SetUnavailable(ioex);
// innerRds.Dispose();
// }, () =>
// {
// lock (_asyncRedisSocketsLock)
// {
// if (asyncRds._writeCounter == 0) return true;
// }
// return false;
// });
// lock (_asyncRedisSocketsLock)
// {
// Interlocked.Increment(ref asyncRds._writeCounter);
// _asyncRedisSockets.Add(asyncRds);
// }
// Interlocked.Increment(ref _asyncRedisSocketsCount);
// }
// }
// }
// internal readonly IRedisSocket _rds;
// readonly Action _begin;
// readonly Action<IRedisSocket, Exception> _end;
// readonly Func<bool> _finish;
// internal long _writeCounter;
// public AsyncRedisSocket(IRedisSocket rds, Action begin, Action<IRedisSocket, Exception> end, Func<bool> finish)
// {
// _rds = rds;
// _begin = begin;
// _end = end;
// _finish = finish;
// _writeCounter = 0;
// }
// public Task<RedisResult> WriteAsync(CommandPacket cmd)
// {
// var iq = WriteInQueue(cmd);
// if (iq == null) return Task.FromResult(new RedisResult(null, true, RedisMessageType.SimpleString));
// return iq.TaskCompletionSource.Task;
// }
// class WriteAsyncInfo
// {
// public TaskCompletionSource<RedisResult> TaskCompletionSource;
// public CommandPacket Command;
// }
// ConcurrentQueue<WriteAsyncInfo> _writeQueue = new ConcurrentQueue<WriteAsyncInfo>();
// object _writeAsyncLock = new object();
// MemoryStream _bufferStream;
// bool _isfirst = false;
// WriteAsyncInfo WriteInQueue(CommandPacket cmd)
// {
// var ret = new WriteAsyncInfo { Command = cmd };
// if (_rds.ClientReply == ClientReplyType.on) ret.TaskCompletionSource = new TaskCompletionSource<RedisResult>();
// var isnew = false;
// lock (_writeAsyncLock)
// {
// _writeQueue.Enqueue(ret);
// if (_isfirst == false)
// isnew = _isfirst = true;
// if (_bufferStream == null) _bufferStream = new MemoryStream();
// new RespHelper.Resp3Writer(_bufferStream, _rds.Encoding, _rds.Protocol).WriteCommand(cmd);
// }
// if (isnew)
// {
// //Thread.CurrentThread.Join(TimeSpan.FromTicks(1000));
// try
// {
// if (_rds.IsConnected == false) _rds.Connect();
// }
// catch (Exception ioex)
// {
// lock (_writeAsyncLock)
// {
// while (_writeQueue.TryDequeue(out var wq)) wq.TaskCompletionSource?.TrySetException(ioex);
// _bufferStream.Close();
// _bufferStream.Dispose();
// _bufferStream = null;
// }
// _rds.ReleaseSocket();
// _end(_rds, ioex);
// throw;
// }
// for (var a = 0; a < 100; a++)
// {
// var cou = _writeQueue.Count;
// if (cou > 100) break;
// }
// var localQueue = new Queue<WriteAsyncInfo>();
// long localQueueThrowException(Exception exception)
// {
// long counter = 0;
// while (localQueue.Any())
// {
// var witem = localQueue.Dequeue();
// if (exception != null) witem.TaskCompletionSource?.TrySetException(exception);
// else witem.TaskCompletionSource?.TrySetCanceled();
// counter = Interlocked.Decrement(ref _writeCounter);
// }
// return counter;
// }
// var iswait = _writeCounter > 1;
// if (iswait) Thread.CurrentThread.Join(10);
// _begin();
// while (true)
// {
// if (_writeQueue.Any() == false)
// {
// Thread.CurrentThread.Join(10);
// continue;
// }
// lock (_writeAsyncLock)
// {
// while (_writeQueue.TryDequeue(out var wq))
// localQueue.Enqueue(wq);
// _bufferStream.Position = 0;
// try
// {
// _bufferStream.CopyTo(_rds.Stream);
// _bufferStream.Close();
// _bufferStream.Dispose();
// _bufferStream = null;
// }
// catch (Exception ioex)
// {
// localQueueThrowException(ioex);
// _bufferStream.Close();
// _bufferStream.Dispose();
// _bufferStream = null;
// _rds.ReleaseSocket();
// _end(_rds, ioex);
// throw;
// }
// }
// long counter = 0;
// RedisResult rt = null;
// //sb.AppendLine($"{name} 线程{Thread.CurrentThread.ManagedThreadId}:合并读取 {localQueue.Count} 个命令 total:{sw.ElapsedMilliseconds} ms");
// while (localQueue.Any())
// {
// var witem = localQueue.Dequeue();
// try
// {
// rt = _rds.Read(witem.Command);
// }
// catch (Exception ioex)
// {
// localQueueThrowException(ioex);
// _rds.ReleaseSocket();
// _end(_rds, ioex);
// throw;
// }
// witem.TaskCompletionSource.TrySetResult(rt);
// counter = Interlocked.Decrement(ref _writeCounter);
// }
// if (counter == 0 && _finish())
// break;
// Thread.CurrentThread.Join(1);
// //sb.AppendLine($"{name} 线程{Thread.CurrentThread.ManagedThreadId}:等待 1ms + {_writeQueue.Count} total:{sw.ElapsedMilliseconds} ms");
// }
// //sb.AppendLine($"{name} 线程{Thread.CurrentThread.ManagedThreadId}:退出 total:{sw.ElapsedMilliseconds} ms");
// _end(_rds, null);
// }
// return ret;
// }
// //public string name = Guid.NewGuid().ToString();
// //public static StringBuilder sb = new StringBuilder();
// //public static Stopwatch sw = new Stopwatch();
// }
//}
//#endif |
2881099/FreeRedis | 22,054 | src/FreeRedis/Internal/AsyncTestCode/AsyncPipelineRedisSocket.cs | //#if isasync
//using System;
//using System.Buffers;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Globalization;
//using System.IO;
//using System.IO.Pipelines;
//using System.Linq;
//using System.Net;
//using System.Net.Sockets;
//using System.Numerics;
//using System.Text;
//using System.Threading;
//using System.Threading.Tasks;
//namespace FreeRedis.Internal
//{
// class AsyncPipelineRedisSocket
// {
// readonly IRedisSocket _redisSocket;
// readonly TimeSpan _oldReceiveTimeout;
// Pipe _readPipe;
// Pipe _writePipe;
// bool _runing = true;
// Exception _exception;
// public AsyncPipelineRedisSocket(IRedisSocket redisSocket)
// {
// _redisSocket = redisSocket;
// _oldReceiveTimeout = _redisSocket.ReceiveTimeout;
// _redisSocket.ReceiveTimeout = TimeSpan.Zero;
// _readPipe = new Pipe();
// _writePipe = new Pipe();
// StartReadPipe(_readPipe);
// StartWritePipe(_writePipe);
// }
// public void Dispose()
// {
// _runing = false;
// try { _readPipe?.Reader?.CancelPendingRead(); } catch { }
// try { _readPipe?.Reader?.Complete(); } catch { }
// try { _readPipe?.Writer?.CancelPendingFlush(); } catch { }
// try { _readPipe?.Writer?.Complete(); } catch { }
// try { _writePipe?.Reader?.CancelPendingRead(); } catch { }
// try { _writePipe?.Reader?.Complete(); } catch { }
// try { _writePipe?.Writer?.CancelPendingFlush(); } catch { }
// try { _writePipe?.Writer?.Complete(); } catch { }
// _redisSocket.ReceiveTimeout = _oldReceiveTimeout;
// _redisSocket.ReleaseSocket();
// ClearAndTrySetExpcetion(null);
// }
// async public Task<RedisResult> WriteAsync(CommandPacket cmd)
// {
// var ex = _exception;
// if (ex != null) throw ex;
// var iq = WriteInQueue(cmd);
// if (iq == null) return new RedisResult(null, true, RedisMessageType.SimpleString);
// return await iq.TaskCompletionSource.Task;
// }
// void ClearAndTrySetExpcetion(Exception ioex)
// {
// lock (_writeQueueLock)
// {
// while (_writeQueue.TryDequeue(out var witem))
// {
// if (ioex != null) witem.TaskCompletionSource.TrySetException(ioex);
// else witem.TaskCompletionSource.TrySetCanceled();
// }
// }
// }
// class WriteAsyncInfo
// {
// public TaskCompletionSource<RedisResult> TaskCompletionSource = new TaskCompletionSource<RedisResult>();
// public CommandPacket Command;
// }
// ConcurrentQueue<WriteAsyncInfo> _writeQueue = new ConcurrentQueue<WriteAsyncInfo>();
// object _writeQueueLock = new object();
// WriteAsyncInfo WriteInQueue(CommandPacket cmd)
// {
// var ret = _redisSocket.ClientReply == ClientReplyType.on ? new WriteAsyncInfo { Command = cmd } : null;
// Span<byte> span = default;
// int spanlen = 0;
// using (var ms = new MemoryStream())
// {
// ms.Write(new byte[] { 32, 32, 32, 32 }, 0, 4);
// new RespHelper.Resp3Writer(ms, _redisSocket.Encoding, _redisSocket.Protocol).WriteCommand(cmd);
// var bytes = ms.ToArray();
// span = bytes.AsSpan();
// spanlen = bytes.Length;
// var size = (spanlen - 4).ToString("x");
// for (var a = 0; a < size.Length; a++) span[a] = (byte)size[a];
// ms.Close();
// }
// lock (_writeQueueLock)
// {
// if (ret != null) _writeQueue.Enqueue(ret);
// var wtspan = _writePipe.Writer.GetSpan(spanlen);
// for (var a = 0; a < spanlen; a++) wtspan[a] = span[a];
// try
// {
// _writePipe.Writer.Advance(spanlen);
// var flush = _writePipe.Writer.FlushAsync();
// if (!flush.IsCompletedSuccessfully)
// {
// flush.AsTask().Wait();
// }
// }
// catch (Exception ex)
// {
// Trace.WriteLine(ex.Message);
// throw ex;
// }
// }
// return ret;
// }
// void StartWritePipe(Pipe pipe)
// {
// new Thread(() =>
// {
// Task.Run(async () =>
// {
// while (_runing)
// {
// var readResult = await pipe.Reader.ReadAsync().ConfigureAwait(false);
// var buffer = readResult.Buffer;
// var bufferStart = buffer.Start;
// var bufferEnd = buffer.End;
// long offset = 0;
// try
// {
// if (TryReadSize(ref buffer, ref offset, 4, out var size))
// {
// if (!int.TryParse(Encoding.UTF8.GetString(size.ToArray()).TrimEnd(' '), NumberStyles.HexNumber, null, out var size_int))
// throw new ProtocolViolationException();
// if (TryReadSize(ref buffer, ref offset, size_int, out var body))
// {
// foreach (var it in body)
// {
// _redisSocket.Stream.Write(it.ToArray(), 0, it.Length);
// //Console.WriteLine(Encoding.UTF8.GetString(it.ToArray()));
// }
// while (TryReadSize(ref buffer, ref offset, 1, out var tmp))
// {
// }
// bufferStart = readResult.Buffer.GetPosition(offset);
// }
// }
// }
// finally
// {
// lock (_writeQueueLock)
// {
// pipe.Reader.AdvanceTo(bufferStart, bufferEnd);
// }
// }
// }
// }).Wait();
// }).Start();
// }
// void StartReadPipe(Pipe pipe)
// {
// var pipeLock = new object();
// new Thread(() =>
// {
// var buffer = new byte[1024];
// while (_runing)
// {
// var readsize = 0;
// try
// {
// readsize = _redisSocket.Stream.Read(buffer, 0, buffer.Length);
// }
// catch
// {
// Thread.CurrentThread.Join(100);
// }
// lock (pipeLock)
// {
// var span = pipe.Writer.GetSpan(readsize);
// for (var a = 0; a < readsize; a++) span[a] = buffer[a];
// pipe.Writer.Advance(readsize);
// }
// var flush = pipe.Writer.FlushAsync();
// if (!flush.IsCompletedSuccessfully) flush.AsTask().Wait();
// }
// }).Start();
// new Thread(() =>
// {
// Task.Run(async () =>
// {
// while (_runing)
// {
// var readResult = await pipe.Reader.ReadAsync().ConfigureAwait(false);
// var buffer = readResult.Buffer;
// var bufferStart = buffer.Start;
// var bufferEnd = buffer.End;
// long offset = 0;
// RedisResult redisResult = null;
// try
// {
// if (TryRead(ref buffer, ref offset, out redisResult))
// {
// bufferStart = buffer.Start;
// bufferEnd = buffer.End;
// }
// }
// finally
// {
// lock (pipeLock)
// {
// pipe.Reader.AdvanceTo(bufferStart, bufferEnd);
// }
// if (redisResult != null)
// {
// if (_writeQueue.TryDequeue(out var witem))
// witem.TaskCompletionSource.TrySetResult(redisResult);
// else
// ClearAndTrySetExpcetion(new RedisClientException($"AsyncRedisSocket: Message sequence error"));
// }
// }
// }
// }).Wait();
// }).Start();
// }
// #region Read
// static bool TryRead(ref ReadOnlySequence<byte> buffer, ref long offset, out RedisResult result)
// {
// if (!TryReadByte(ref buffer, ref offset, out var msgtype))
// {
// result = null;
// return false;
// }
// switch ((char)msgtype)
// {
// case '$': return (result = ReadBlobString(ref buffer, ref offset, RedisMessageType.BlobString)) != null;
// case '+': return (result = ReadLineString(ref buffer, ref offset, RedisMessageType.SimpleString)) != null;
// case '=': return (result = ReadBlobString(ref buffer, ref offset, RedisMessageType.VerbatimString)) != null;
// case '-': return (result = ReadLineString(ref buffer, ref offset, RedisMessageType.SimpleError)) != null;
// case '!': return (result = ReadBlobString(ref buffer, ref offset, RedisMessageType.BlobError)) != null;
// case ':': return (result = ReadNumber(ref buffer, ref offset, RedisMessageType.Number)) != null;
// case '(': return (result = ReadBigNumber(ref buffer, ref offset, RedisMessageType.BigNumber)) != null;
// case '_': return (result = ReadNull(ref buffer, ref offset, RedisMessageType.Null)) != null;
// case ',': return (result = ReadDouble(ref buffer, ref offset, RedisMessageType.Double)) != null;
// case '#': return (result = ReadBoolean(ref buffer, ref offset, RedisMessageType.Boolean)) != null;
// case '*': return (result = ReadArray(ref buffer, ref offset, RedisMessageType.Array)) != null;
// case '~': return (result = ReadArray(ref buffer, ref offset, RedisMessageType.Set)) != null;
// case '>': return (result = ReadArray(ref buffer, ref offset, RedisMessageType.Push)) != null;
// case '%': return (result = ReadMap(ref buffer, ref offset, RedisMessageType.Map)) != null;
// case '|': return (result = ReadMap(ref buffer, ref offset, RedisMessageType.Attribute)) != null;
// case '.': return (result = ReadEnd(ref buffer, ref offset, RedisMessageType.SimpleString)) != null;
// case ' ': result = null; return true;
// default: throw new ProtocolViolationException($"Expecting fail MessageType '{(char)msgtype}'");
// }
// }
// static bool TryReadSize(ref ReadOnlySequence<byte> buffer, ref long offset, long size, out ReadOnlySequence<byte> result)
// {
// long remaining = 0;
// foreach (var it in buffer)
// {
// remaining += it.Span.Length;
// if (remaining >= size)
// {
// offset += size;
// result = buffer.Slice(0, size);
// buffer = buffer.Slice(size);
// return true;
// }
// }
// result = default;
// return false;
// }
// static bool TryReadLine(ref ReadOnlySequence<byte> buffer, ref long offset, out string result)
// {
// var pos = buffer.PositionOf((byte)'\r');
// if (pos == null || buffer.Slice(pos.Value, 2).Slice(1).First.Span[0] != (byte)'\n')
// {
// result = null;
// return false;
// }
// var span = buffer.Slice(0, pos.Value);
// var spanlen = span.Length;
// offset += spanlen + 2;
// result = Encoding.UTF8.GetString(span.ToArray());
// buffer = buffer.Slice(spanlen + 2);
// return true;
// }
// static bool TryReadSizeText(ref ReadOnlySequence<byte> buffer, ref long offset, long size, out string result)
// {
// if (!TryReadSize(ref buffer, ref offset, size, out var readbuffer))
// {
// result = null;
// return false;
// }
// result = Encoding.UTF8.GetString(readbuffer.ToArray());
// return true;
// }
// static bool TryReadByte(ref ReadOnlySequence<byte> buffer, ref long offset, out byte result)
// {
// if (!TryReadSize(ref buffer, ref offset, 1, out var readbuffer))
// {
// result = 0;
// return false;
// }
// result = readbuffer.First.Span[0];
// return true;
// }
// static RedisResult ReadBlobString(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// if (long.TryParse(line, out var line_int))
// {
// if (!TryReadSizeText(ref buffer, ref offset, line_int, out var text)) return null;
// if (!TryReadLine(ref buffer, ref offset, out var emptyline)) return null;
// return new RedisResult(text, false, msgtype);
// }
// if (line == "?")
// {
// var lst = new List<ReadOnlySequence<byte>>();
// while (true)
// {
// if (!TryReadByte(ref buffer, ref offset, out var c)) return null;
// if ((char)c != ';') throw new ProtocolViolationException();
// if (!TryReadLine(ref buffer, ref offset, out line)) return null;
// if (!long.TryParse(line, out line_int)) throw new ProtocolViolationException();
// if (line_int > 0)
// {
// if (!TryReadSize(ref buffer, ref offset, line_int, out var blob2)) return null;
// lst.Add(blob2);
// continue;
// }
// using (var ms = new MemoryStream())
// {
// foreach (var ls in lst)
// foreach (var it in ls)
// ms.Write(it.Span.ToArray(), 0, it.Span.Length);
// var ret = new RedisResult(Encoding.UTF8.GetString(ms.ToArray()), false, msgtype);
// ms.Close();
// return ret;
// }
// }
// }
// throw new NotSupportedException();
// }
// static RedisResult ReadLineString(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var result)) return null;
// return new RedisResult(result, false, msgtype);
// }
// static RedisResult ReadNumber(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// if (!long.TryParse(line, out var num)) throw new ProtocolViolationException($"Expecting fail Number '{msgtype}0', got '{msgtype}{line}'");
// return new RedisResult(num, false, msgtype);
// }
// static RedisResult ReadBigNumber(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// if (!BigInteger.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out var num)) throw new ProtocolViolationException($"Expecting fail BigNumber '{msgtype}0', got '{msgtype}{line}'");
// return new RedisResult(num, false, msgtype);
// }
// static RedisResult ReadNull(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// return new RedisResult(null, false, msgtype);
// }
// static RedisResult ReadDouble(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// double num = 0;
// switch (line)
// {
// case "inf": num = double.PositiveInfinity; break;
// case "-inf": num = double.NegativeInfinity; break;
// default:
// if (!double.TryParse(line, NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat, out num)) throw new ProtocolViolationException($"Expecting fail Double '{msgtype}1.23', got '{msgtype}{line}'");
// break;
// }
// return new RedisResult(num, false, msgtype);
// }
// static RedisResult ReadBoolean(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// switch (line)
// {
// case "t": return new RedisResult(true, false, msgtype);
// case "f": return new RedisResult(false, false, msgtype);
// }
// throw new ProtocolViolationException($"Expecting fail Boolean '{msgtype}t', got '{msgtype}{line}'");
// }
// static RedisResult ReadArray(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// if (int.TryParse(line, out var len))
// {
// if (len < 0) return null;
// var arr = new object[len];
// for (var a = 0; a < len; a++)
// {
// if (!TryRead(ref buffer, ref offset, out var item)) return null;
// arr[a] = item.Value;
// }
// if (len == 1 && arr[0] == null) arr = new object[0];
// return new RedisResult(arr, false, msgtype);
// }
// if (line == "?")
// {
// var arr = new List<object>();
// while (true)
// {
// if (!TryRead(ref buffer, ref offset, out var item)) return null;
// if (item.IsEnd) break;
// arr.Add(item.Value);
// }
// return new RedisResult(arr.ToArray(), false, msgtype);
// }
// throw new ProtocolViolationException($"Expecting fail Array '{msgtype}3', got '{msgtype}{line}'");
// }
// static RedisResult ReadMap(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// if (int.TryParse(line, out var len))
// {
// if (len < 0) return null;
// var arr = new object[len * 2];
// for (var a = 0; a < len; a++)
// {
// if (!TryRead(ref buffer, ref offset, out var key)) return null;
// if (!TryRead(ref buffer, ref offset, out var value)) return null;
// arr[a * 2] = key.Value;
// arr[a * 2 + 1] = value.Value;
// }
// return new RedisResult(arr, false, msgtype);
// }
// if (line == "?")
// {
// var arr = new List<object>();
// while (true)
// {
// if (!TryRead(ref buffer, ref offset, out var key)) return null;
// if (key.IsEnd) break;
// if (!TryRead(ref buffer, ref offset, out var value)) return null;
// arr.Add(key.Value);
// arr.Add(value.Value);
// }
// return new RedisResult(arr.ToArray(), false, msgtype);
// }
// throw new ProtocolViolationException($"Expecting fail Map '{msgtype}3', got '{msgtype}{line}'");
// }
// static RedisResult ReadEnd(ref ReadOnlySequence<byte> buffer, ref long offset, RedisMessageType msgtype)
// {
// if (!TryReadLine(ref buffer, ref offset, out var line)) return null;
// return new RedisResult(null, true, msgtype);
// }
// #endregion
// }
//}
//#endif |
2881099/FreeRedis | 2,730 | src/FreeRedis/Internal/ObjectPool/IPolicy.cs | using System;
using System.Threading.Tasks;
namespace FreeRedis.Internal.ObjectPool
{
public interface IPolicy<T>
{
/// <summary>
/// 名称
/// </summary>
string Name { get; set; }
/// <summary>
/// 池容量
/// </summary>
int PoolSize { get; set; }
/// <summary>
/// 默认获取超时设置
/// </summary>
TimeSpan SyncGetTimeout { get; set; }
/// <summary>
/// 空闲时间,获取时若超出,则重新创建
/// </summary>
TimeSpan IdleTimeout { get; set; }
/// <summary>
/// 异步获取排队队列大小,小于等于0不生效
/// </summary>
int AsyncGetCapacity { get; set; }
/// <summary>
/// 获取超时后,是否抛出异常
/// </summary>
bool IsThrowGetTimeoutException { get; set; }
/// <summary>
/// 监听 AppDomain.CurrentDomain.ProcessExit/Console.CancelKeyPress 事件自动释放
/// </summary>
bool IsAutoDisposeWithSystem { get; set; }
/// <summary>
/// 后台定时检查可用性间隔
/// </summary>
TimeSpan AvailableCheckInterval { get; set; }
/// <summary>
/// 故障切换的容忍窗口期。
/// 当设置为大于 TimeSpan.Zero 的值时,首次失败会进入观察期,而不是立即熔断。
/// 在观察期内持续失败,才会最终熔断。设置为 Zero 表示关闭此功能。
/// </summary>
TimeSpan ToleranceWindow { get; set; }
/// <summary>
/// 在容忍窗口期(观察期)内,进行健康检查的间隔。
/// </summary>
TimeSpan ToleranceCheckInterval { get; set; }
/// <summary>
/// 对象池的对象被创建时
/// </summary>
/// <returns>返回被创建的对象</returns>
T OnCreate();
/// <summary>
/// 销毁对象
/// </summary>
/// <param name="obj">资源对象</param>
void OnDestroy(T obj);
/// <summary>
/// 从对象池获取对象超时的时候触发,通过该方法统计
/// </summary>
void OnGetTimeout();
/// <summary>
/// 从对象池获取对象成功的时候触发,通过该方法统计或初始化对象
/// </summary>
/// <param name="obj">资源对象</param>
void OnGet(Object<T> obj);
#if net40
#else
/// <summary>
/// 从对象池获取对象成功的时候触发,通过该方法统计或初始化对象
/// </summary>
/// <param name="obj">资源对象</param>
Task OnGetAsync(Object<T> obj);
#endif
/// <summary>
/// 归还对象给对象池的时候触发
/// </summary>
/// <param name="obj">资源对象</param>
void OnReturn(Object<T> obj);
/// <summary>
/// 检查可用性
/// </summary>
/// <param name="obj">资源对象</param>
/// <returns></returns>
bool OnCheckAvailable(Object<T> obj);
/// <summary>
/// 事件:可用时触发
/// </summary>
void OnAvailable();
/// <summary>
/// 事件:不可用时触发
/// </summary>
void OnUnavailable();
}
} |
2881099/FreeRedis | 2,651 | src/FreeRedis/Internal/ObjectPool/Object.cs | using System;
using System.Threading;
namespace FreeRedis.Internal.ObjectPool
{
public class Object<T> : IDisposable
{
public static Object<T> InitWith(IObjectPool<T> pool, int id, T value)
{
return new Object<T>
{
Pool = pool,
Id = id,
Value = value,
LastGetThreadId = Thread.CurrentThread.ManagedThreadId,
LastGetTime = DateTime.Now,
LastGetTimeCopy = DateTime.Now
};
}
/// <summary>
/// 所属对象池
/// </summary>
public IObjectPool<T> Pool { get; internal set; }
/// <summary>
/// 在对象池中的唯一标识
/// </summary>
public int Id { get; internal set; }
/// <summary>
/// 资源对象
/// </summary>
public T Value { get; internal set; }
internal long _getTimes;
/// <summary>
/// 被获取的总次数
/// </summary>
public long GetTimes => _getTimes;
/// 最后获取时的时间
public DateTime LastGetTime { get; internal set; }
public DateTime LastGetTimeCopy { get; internal set; }
/// <summary>
/// 最后归还时的时间
/// </summary>
public DateTime LastReturnTime { get; internal set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; internal set; } = DateTime.Now;
/// <summary>
/// 最后获取时的线程id
/// </summary>
public int LastGetThreadId { get; internal set; }
/// <summary>
/// 最后归还时的线程id
/// </summary>
public int LastReturnThreadId { get; internal set; }
public override string ToString()
{
return $"{this.Value}, Times: {this.GetTimes}, ThreadId(R/G): {this.LastReturnThreadId}/{this.LastGetThreadId}, Time(R/G): {this.LastReturnTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}/{this.LastGetTime.ToString("yyyy-MM-dd HH:mm:ss:ms")}";
}
/// <summary>
/// 重置 Value 值
/// </summary>
public void ResetValue()
{
if (this.Value != null)
{
try { this.Pool.Policy.OnDestroy(this.Value); } catch { }
try { (this.Value as IDisposable)?.Dispose(); } catch { }
}
T value = default(T);
try { value = this.Pool.Policy.OnCreate(); } catch { }
this.Value = value;
this.LastReturnTime = DateTime.Now;
}
internal bool _isReturned = false;
public void Dispose()
{
Pool?.Return(this);
}
}
} |
2881099/FreeRedis | 25,916 | src/FreeRedis/Internal/ObjectPool/ObjectPool.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FreeRedis.Internal.ObjectPool
{
internal class TestTrace
{
internal static void WriteLine(string text, ConsoleColor backgroundColor)
{
try
{
System.Diagnostics.Debug.WriteLine(text);
}
catch { }
return;
//try //#643
//{
// var bgcolor = Console.BackgroundColor;
// var forecolor = Console.ForegroundColor;
// Console.BackgroundColor = backgroundColor;
// switch (backgroundColor)
// {
// case ConsoleColor.Yellow:
// Console.ForegroundColor = ConsoleColor.White;
// break;
// case ConsoleColor.DarkGreen:
// Console.ForegroundColor = ConsoleColor.White;
// break;
// }
// Console.Write(text);
// Console.BackgroundColor = bgcolor;
// Console.ForegroundColor = forecolor;
// Console.WriteLine();
//}
//catch
//{
// try
// {
// System.Diagnostics.Debug.WriteLine(text);
// }
// catch { }
//}
}
}
/// <summary>
/// 对象池管理类
/// </summary>
/// <typeparam name="T">对象类型</typeparam>
public partial class ObjectPool<T> : IObjectPool<T>
{
private enum State { Healthy, Observing, Unavailable }
public IPolicy<T> Policy { get; protected set; }
private object _allObjectsLock = new object();
internal List<Object<T>> _allObjects = new List<Object<T>>();
internal ConcurrentStack<Object<T>> _freeObjects = new ConcurrentStack<Object<T>>();
private ConcurrentQueue<GetSyncQueueInfo> _getSyncQueue = new ConcurrentQueue<GetSyncQueueInfo>();
private ConcurrentQueue<TaskCompletionSource<Object<T>>> _getAsyncQueue = new ConcurrentQueue<TaskCompletionSource<Object<T>>>();
private ConcurrentQueue<bool> _getQueue = new ConcurrentQueue<bool>();
private volatile State _currentState = State.Healthy;
private Exception _firstFailureException;
private readonly object _stateTransitionLock = new object();
private bool _running = true;
private bool _isCheckerRunning = false;
public bool IsAvailable => this.UnavailableException == null;
public Exception UnavailableException { get; private set; }
public DateTime? UnavailableTime { get; private set; }
public DateTime? AvailableTime { get; private set; }
/// <summary>
/// 报告一次失败。这是新的故障处理入口。
/// 它会根据策略决定是进入“观察期”还是直接“熔断”。
/// </summary>
public bool SetUnavailable(Exception exception, DateTime lastGetTime)
{
// 如果策略未开启容忍窗口,则使用旧的直接熔断逻辑
if (Policy.ToleranceWindow <= TimeSpan.Zero)
{
lock (_stateTransitionLock)
{
_isCheckerRunning = false;
return TransitionToUnavailable(exception, lastGetTime, true);
}
}
// --- 使用容忍窗口的逻辑 ---
lock (_stateTransitionLock)
{
// 如果当前不处于健康状态,则什么都不做。
// 这意味着恢复检查器已经在工作了。
if (_currentState != State.Healthy)
{
return false;
}
// 状态从“健康”切换到“观察中”
_currentState = State.Observing;
_firstFailureException = exception;
TestTrace.WriteLine($"[{Policy.Name}] Service unstable: {exception.Message}. Entering a {Policy.ToleranceWindow.TotalSeconds} second observation period.", ConsoleColor.DarkYellow);
if (!_isCheckerRunning)
{
_isCheckerRunning = true;
// 在后台启动高频的恢复检查
new Thread(UnifiedCheckerLoop) { IsBackground = true }.Start();
}
return true; // 状态发生变化
}
}
/// <summary>
/// 一个统一的、能处理两种状态(Observing 和 Unavailable)的检查循环。
/// 这个线程一旦启动,就会一直运行,直到状态恢复为 Healthy 或池被 Dispose。
/// </summary>
private void UnifiedCheckerLoop()
{
try
{
// === 阶段一:观察期的高频检查 ===
if (_currentState == State.Observing)
{
TestTrace.WriteLine($"[{Policy.Name}] Observation period checker started.", ConsoleColor.DarkGray);
var observationEndTime = DateTime.Now.Add(Policy.ToleranceWindow);
while (DateTime.Now < observationEndTime)
{
if (_running == false || _currentState != State.Observing) return;
if (TryHealthCheck())
{
TestTrace.WriteLine($"[{Policy.Name}] Service recovery detected during the observation period.", ConsoleColor.DarkGreen);
RestoreToAvailable();
return; // 成功,退出线程
}
Thread.Sleep(Policy.ToleranceCheckInterval);
}
// 观察期结束仍未恢复,转换到熔断状态
lock (_stateTransitionLock)
{
if (_currentState == State.Observing)
{
TestTrace.WriteLine($"[{Policy.Name}] Observation period ended, service not recovered. Now breaking the circuit.", ConsoleColor.Red);
// 注意:这里不再启动新线程,而是让当前线程继续工作
TransitionToUnavailable(_firstFailureException, DateTime.Now, false);
}
}
}
// === 阶段二:熔断后的低频检查 ===
if (_currentState == State.Unavailable)
{
TestTrace.WriteLine($"[{Policy.Name}] Low-frequency recovery checker has taken over.", ConsoleColor.DarkGray);
while (_currentState == State.Unavailable)
{
if (_running == false) return;
// 使用低频间隔
Thread.Sleep(Policy.AvailableCheckInterval);
if (_running == false) return;
if (_currentState != State.Unavailable) return; // 可能在休眠期间状态已改变
if (TryHealthCheck())
{
RestoreToAvailable();
return; // 成功,退出线程
}
else
{
TestTrace.WriteLine($"[{Policy.Name}] Recovery check failed. Next check at: {DateTime.Now.Add(Policy.AvailableCheckInterval)}", ConsoleColor.DarkYellow);
}
}
}
}
finally
{
// --- 线程结束时,重置标志 ---
// 无论线程是正常退出(恢复成功)还是异常退出,
// 都必须确保重置标志,以便下次可以启动新的检查器。
lock (_stateTransitionLock)
{
_isCheckerRunning = false;
}
TestTrace.WriteLine($"[{Policy.Name}] Checker thread stopped.", ConsoleColor.DarkGray);
}
}
/// <summary>
/// 将连接池状态切换为“不可用”
/// </summary>
private bool TransitionToUnavailable(Exception exception, DateTime lastGetTime, bool isAvailableCheck)
{
if (_currentState == State.Unavailable) return false;
if (AvailableTime != null && lastGetTime < AvailableTime) return false;
UnavailableException = exception;
UnavailableTime = DateTime.Now;
AvailableTime = null;
_currentState = State.Unavailable;
Policy.OnUnavailable();
if (isAvailableCheck)
{
if (!_isCheckerRunning)
{
_isCheckerRunning = true;
CheckUntilAvailable(Policy.AvailableCheckInterval); // 启动“低频”的后台恢复检查
}
}
return true;
}
/// <summary>
/// 后台定时检查可用性(原 CheckAvailable 方法)
/// </summary>
private void CheckUntilAvailable(TimeSpan interval)
{
new Thread(() =>
{
if (_currentState == State.Unavailable)
TestTrace.WriteLine($"[{Policy.Name}] Service is circuit-broken. Next recovery check at: {DateTime.Now.Add(interval)}", ConsoleColor.DarkYellow);
while (_currentState == State.Unavailable)
{
if (_running == false) return;
Thread.Sleep(interval);
if (_running == false) return;
if (TryHealthCheck())
{
RestoreToAvailable();
break; // 恢复成功,退出循环
}
else
{
TestTrace.WriteLine($"[{Policy.Name}] Recovery check failed. Next check at: {DateTime.Now.Add(interval)}", ConsoleColor.DarkYellow);
}
}
})
{ IsBackground = true }.Start();
}
/// <summary>
/// 尝试进行一次健康检查的通用逻辑
/// </summary>
/// <returns>检查是否成功</returns>
private bool TryHealthCheck()
{
Object<T> conn = null;
try
{
conn = GetFree(false); // false 表示不检查池状态,强行获取一个对象
if (conn == null) throw new Exception($"[{Policy.Name}] Unable to get a resource for health check {this.Statistics}");
try
{
if (Policy.OnCheckAvailable(conn)) return true;
// 如果 OnCheckAvailable 返回 false,我们认为检查失败
throw new Exception($"[{Policy.Name}] OnCheckAvailable returned false.");
}
catch
{
// 如果检查失败,尝试重置对象,为下一次检查做准备
conn.ResetValue();
// 再次检查
return Policy.OnCheckAvailable(conn);
}
}
catch
{
// 任何异常都表示检查失败
return false;
}
finally
{
if (conn != null)
{
Return(conn);
}
}
}
/// <summary>
/// 将连接池恢复到可用状态
/// </summary>
private void RestoreToAvailable()
{
bool isRestored = false;
if (_currentState != State.Healthy)
{
lock (_stateTransitionLock)
{
if (_currentState != State.Healthy)
{
lock (_allObjectsLock)
_allObjects.ForEach(a => a.LastGetTime = a.LastReturnTime = new DateTime(2000, 1, 1));
UnavailableException = null;
UnavailableTime = null;
_firstFailureException = null; // 清理首次失败的异常
AvailableTime = DateTime.Now;
_currentState = State.Healthy; // 状态恢复为健康
isRestored = true;
}
}
}
if (isRestored)
{
Policy.OnAvailable();
TestTrace.WriteLine($"[{Policy.Name}] Service is now available.", ConsoleColor.DarkGreen);
}
}
protected bool LiveCheckAvailable()
{
try
{
var conn = GetFree(false);
if (conn == null) throw new Exception($"[{Policy.Name}] Failed to get resource {this.Statistics}");
try
{
if (Policy.OnCheckAvailable(conn) == false) throw new Exception($"[{Policy.Name}] An exception needs to be thrown");
}
finally
{
Return(conn);
}
}
catch
{
return false;
}
RestoreToAvailable();
return true;
}
public string Statistics => $"Pool: {_freeObjects.Count}/{_allObjects.Count}, Get wait: {_getSyncQueue.Count}, GetAsync wait: {_getAsyncQueue.Count}, State: {_currentState}";
public string StatisticsFullily
{
get
{
var sb = new StringBuilder();
sb.AppendLine(Statistics);
if (_currentState == State.Observing) sb.AppendLine($"Observing since: {_firstFailureException?.Message}");
if (_currentState == State.Unavailable) sb.AppendLine($"Unavailable since: {UnavailableException?.Message}");
sb.AppendLine("");
foreach (var obj in _allObjects)
{
sb.AppendLine($"{obj.Value}, Times: {obj.GetTimes}, ThreadId(R/G): {obj.LastReturnThreadId}/{obj.LastGetThreadId}, Time(R/G): {obj.LastReturnTime:yyyy-MM-dd HH:mm:ss:ms}/{obj.LastGetTime:yyyy-MM-dd HH:mm:ss:ms}, ");
}
return sb.ToString();
}
}
/// <summary>
/// 创建对象池
/// </summary>
/// <param name="poolsize">池大小</param>
/// <param name="createObject">池内对象的创建委托</param>
/// <param name="onGetObject">获取池内对象成功后,进行使用前操作</param>
public ObjectPool(int poolsize, Func<T> createObject, Action<Object<T>> onGetObject = null) : this(new DefaultPolicy<T> { PoolSize = poolsize, CreateObject = createObject, OnGetObject = onGetObject })
{
}
/// <summary>
/// 创建对象池
/// </summary>
/// <param name="policy">策略</param>
public ObjectPool(IPolicy<T> policy)
{
Policy = policy;
AppDomain.CurrentDomain.ProcessExit += (s1, e1) =>
{
if (Policy.IsAutoDisposeWithSystem)
_running = false;
};
try
{
Console.CancelKeyPress += (s1, e1) =>
{
if (e1.Cancel) return;
if (Policy.IsAutoDisposeWithSystem)
_running = false;
};
}
catch { }
}
public void AutoFree()
{
if (_running == false) return;
if (UnavailableException != null) return;
var list = new List<Object<T>>();
while (_freeObjects.TryPop(out var obj))
list.Add(obj);
foreach (var obj in list)
{
if (obj != null && obj.Value == null ||
obj != null && Policy.IdleTimeout > TimeSpan.Zero && DateTime.Now.Subtract(obj.LastReturnTime) > Policy.IdleTimeout)
{
if (obj.Value != null)
{
Return(obj, true);
continue;
}
}
Return(obj);
}
}
/// <summary>
/// 获取可用资源,或创建资源
/// </summary>
private Object<T> GetFree(bool checkAvailable)
{
if (_running == false)
throw new ObjectDisposedException($"[{Policy.Name}] The ObjectPool has been disposed, see: https://github.com/dotnetcore/FreeSql/discussions/1079");
if (checkAvailable)
{
var currentState = _currentState;
if (currentState == State.Unavailable)
throw new Exception($"[{Policy.Name}] The service is circuit-broken, waiting for recovery. Error: {UnavailableException?.Message}", UnavailableException);
//if (currentState == State.Observing)
// throw new Exception($"[{Policy.Name}] The service is unstable, checking for recovery. Original error: {_firstFailureException?.Message}", _firstFailureException);
}
if ((_freeObjects.TryPop(out var obj) == false || obj == null) && _allObjects.Count < Policy.PoolSize)
{
lock (_allObjectsLock)
if (_allObjects.Count < Policy.PoolSize)
_allObjects.Add(obj = new Object<T> { Pool = this, Id = _allObjects.Count + 1 });
}
if (obj != null)
obj._isReturned = false;
if (obj != null && obj.Value == null ||
obj != null && Policy.IdleTimeout > TimeSpan.Zero && DateTime.Now.Subtract(obj.LastReturnTime) > Policy.IdleTimeout)
{
try
{
obj.ResetValue();
}
catch
{
Return(obj);
throw;
}
}
return obj;
}
public Object<T> Get(TimeSpan? timeout = null)
{
var obj = GetFree(true);
if (obj == null)
{
var queueItem = new GetSyncQueueInfo();
_getSyncQueue.Enqueue(queueItem);
_getQueue.Enqueue(false);
if (timeout == null) timeout = Policy.SyncGetTimeout;
try
{
if (queueItem.Wait.Wait(timeout.Value))
obj = queueItem.ReturnValue;
}
catch { }
if (obj == null) obj = queueItem.ReturnValue;
if (obj == null) lock (queueItem.Lock) queueItem.IsTimeout = (obj = queueItem.ReturnValue) == null;
if (obj == null) obj = queueItem.ReturnValue;
if (queueItem.Exception != null) throw queueItem.Exception;
if (obj == null)
{
Policy.OnGetTimeout();
if (Policy.IsThrowGetTimeoutException)
throw new TimeoutException($"[{Policy.Name}] ObjectPool.Get() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081");
return null;
}
}
try
{
Policy.OnGet(obj);
}
catch
{
Return(obj, true);
throw;
}
obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastGetTime = DateTime.Now;
obj.LastGetTimeCopy = DateTime.Now;
Interlocked.Increment(ref obj._getTimes);
return obj;
}
#if net40
#else
async public Task<Object<T>> GetAsync()
{
var obj = GetFree(true);
if (obj == null)
{
if (Policy.AsyncGetCapacity > 0 && _getAsyncQueue.Count >= Policy.AsyncGetCapacity - 1)
throw new OutOfMemoryException($"[{Policy.Name}] ObjectPool.GetAsync() The queue is too long. Policy.AsyncGetCapacity = {Policy.AsyncGetCapacity}");
var tcs = new TaskCompletionSource<Object<T>>();
_getAsyncQueue.Enqueue(tcs);
_getQueue.Enqueue(true);
obj = await tcs.Task;
//if (timeout == null) timeout = Policy.SyncGetTimeout;
//if (tcs.Task.Wait(timeout.Value))
// obj = tcs.Task.Result;
//if (obj == null) {
// tcs.TrySetCanceled();
// Policy.GetTimeout();
// if (Policy.IsThrowGetTimeoutException)
// throw new TimeoutException($"[{Policy.Name}] ObjectPool.GetAsync() timeout {timeout.Value.TotalSeconds} seconds, see: https://github.com/dotnetcore/FreeSql/discussions/1081");
// return null;
//}
}
try
{
await Policy.OnGetAsync(obj);
}
catch
{
Return(obj, true);
throw;
}
obj.LastGetThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastGetTime = DateTime.Now;
obj.LastGetTimeCopy = DateTime.Now;
Interlocked.Increment(ref obj._getTimes);
return obj;
}
#endif
public void Return(Object<T> obj, bool isReset = false)
{
if (obj == null) return;
if (obj._isReturned) return;
if (_running == false)
{
Policy.OnDestroy(obj.Value);
try { (obj.Value as IDisposable)?.Dispose(); } catch { }
return;
}
if (isReset) obj.ResetValue();
bool isReturn = false;
while (isReturn == false && _getQueue.TryDequeue(out var isAsync))
{
if (isAsync == false)
{
if (_getSyncQueue.TryDequeue(out var queueItem) && queueItem != null)
{
lock (queueItem.Lock)
if (queueItem.IsTimeout == false)
queueItem.ReturnValue = obj;
if (queueItem.ReturnValue != null)
{
if (UnavailableException != null)
{
queueItem.Exception = new Exception($"[{Policy.Name}] Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException);
try
{
queueItem.Wait.Set();
}
catch { }
}
else
{
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastReturnTime = DateTime.Now;
try
{
queueItem.Wait.Set();
isReturn = true;
}
catch { }
}
}
try { queueItem.Dispose(); } catch { }
}
}
else
{
if (_getAsyncQueue.TryDequeue(out var tcs) && tcs != null && tcs.Task.IsCanceled == false)
{
if (UnavailableException != null)
{
try
{
tcs.TrySetException(new Exception($"[{Policy.Name}] Status unavailable, waiting for recovery. {UnavailableException?.Message}", UnavailableException));
}
catch { }
}
else
{
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastReturnTime = DateTime.Now;
try
{
isReturn = tcs.TrySetResult(obj);
}
catch { }
}
}
}
}
//无排队,直接归还
if (isReturn == false)
{
try
{
Policy.OnReturn(obj);
}
catch
{
throw;
}
finally
{
obj.LastReturnThreadId = Thread.CurrentThread.ManagedThreadId;
obj.LastReturnTime = DateTime.Now;
obj._isReturned = true;
_freeObjects.Push(obj);
}
}
}
public void Dispose()
{
_running = false;
while (_freeObjects.TryPop(out var fo)) ;
while (_getSyncQueue.TryDequeue(out var sync))
{
try { sync.Wait.Set(); } catch { }
}
while (_getAsyncQueue.TryDequeue(out var async))
async.TrySetCanceled();
while (_getQueue.TryDequeue(out var qs)) ;
for (var a = 0; a < _allObjects.Count; a++)
{
Policy.OnDestroy(_allObjects[a].Value);
try { (_allObjects[a].Value as IDisposable)?.Dispose(); } catch { }
}
_allObjects.Clear();
}
class GetSyncQueueInfo : IDisposable
{
internal ManualResetEventSlim Wait { get; set; } = new ManualResetEventSlim();
internal Object<T> ReturnValue { get; set; }
internal object Lock = new object();
internal bool IsTimeout { get; set; } = false;
internal Exception Exception { get; set; }
public void Dispose()
{
try
{
if (Wait != null)
Wait.Dispose();
}
catch
{
}
}
}
}
} |
2881099/FreeRedis | 1,608 | src/FreeRedis/Internal/ObjectPool/IObjectPool.cs | using System;
using System.Threading.Tasks;
namespace FreeRedis.Internal.ObjectPool
{
public interface IObjectPool<T> : IDisposable
{
IPolicy<T> Policy { get; }
/// <summary>
/// 是否可用
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// 不可用错误
/// </summary>
Exception UnavailableException { get; }
/// <summary>
/// 不可用时间
/// </summary>
DateTime? UnavailableTime { get; }
/// <summary>
/// 将对象池设置为不可用,后续 Get/GetAsync 均会报错,同时启动后台定时检查服务恢复可用
/// </summary>
/// <param name="exception"></param>
/// <param name="lastGetTime"></param>
/// <returns>由【可用】变成【不可用】时返回true,否则返回false</returns>
bool SetUnavailable(Exception exception, DateTime lastGetTime);
/// <summary>
/// 统计对象池中的对象
/// </summary>
string Statistics { get; }
/// <summary>
/// 统计对象池中的对象(完整)
/// </summary>
string StatisticsFullily { get; }
/// <summary>
/// 获取资源
/// </summary>
/// <param name="timeout">超时</param>
/// <returns></returns>
Object<T> Get(TimeSpan? timeout = null);
#if net40
#else
/// <summary>
/// 获取资源
/// </summary>
/// <returns></returns>
Task<Object<T>> GetAsync();
#endif
/// <summary>
/// 使用完毕后,归还资源
/// </summary>
/// <param name="obj">对象</param>
/// <param name="isReset">是否重新创建</param>
void Return(Object<T> obj, bool isReset = false);
}
}
|
2881099/FreeRedis | 1,729 | src/FreeRedis/Internal/ObjectPool/DefaultPolicy.cs | using System;
using System.Threading.Tasks;
namespace FreeRedis.Internal.ObjectPool
{
public class DefaultPolicy<T> : IPolicy<T>
{
public string Name { get; set; } = typeof(DefaultPolicy<T>).GetType().FullName;
public int PoolSize { get; set; } = 1000;
public TimeSpan SyncGetTimeout { get; set; } = TimeSpan.FromSeconds(10);
public TimeSpan IdleTimeout { get; set; } = TimeSpan.FromSeconds(50);
public int AsyncGetCapacity { get; set; } = 10000;
public bool IsThrowGetTimeoutException { get; set; } = true;
public bool IsAutoDisposeWithSystem { get; set; } = true;
public TimeSpan AvailableCheckInterval { get; set; } = TimeSpan.FromSeconds(3);
public TimeSpan ToleranceWindow { get; set; } = TimeSpan.FromSeconds(5);
public TimeSpan ToleranceCheckInterval { get; set; } = TimeSpan.FromSeconds(1);
public Func<T> CreateObject;
public Action<Object<T>> OnGetObject;
public T OnCreate()
{
return CreateObject();
}
public void OnDestroy(T obj)
{
}
public void OnGet(Object<T> obj)
{
OnGetObject?.Invoke(obj);
}
#if net40
#else
public Task OnGetAsync(Object<T> obj)
{
OnGetObject?.Invoke(obj);
return Task.FromResult(true);
}
#endif
public void OnGetTimeout()
{
}
public void OnReturn(Object<T> obj)
{
}
public bool OnCheckAvailable(Object<T> obj)
{
return true;
}
public void OnAvailable()
{
}
public void OnUnavailable()
{
}
}
} |
2881099/FreeRedis | 4,812 | src/FreeRedis/RedisClient/Adapter/SingleTempAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
// GetDatabase
public DatabaseHook GetDatabase(int? index = null)
{
CheckUseTypeOrThrow(UseType.Pooling, UseType.Sentinel);
var rds = Adapter.GetRedisSocket(null);
DatabaseHook hook = null;
try
{
hook = new DatabaseHook(new SingleTempAdapter(Adapter.TopOwner, rds, index));
}
catch
{
rds.Dispose();
throw;
}
return hook;
}
public class DatabaseHook : RedisClient
{
internal DatabaseHook(BaseAdapter adapter) : base(adapter) { }
}
class SingleTempAdapter : BaseAdapter
{
readonly IRedisSocket _redisSocket;
readonly int? _index;
readonly int _oldIndex;
public SingleTempAdapter(RedisClient topOwner, IRedisSocket redisSocket, int? index)
{
UseType = UseType.SingleInside;
TopOwner = topOwner;
_redisSocket = redisSocket;
_index = index;
_oldIndex = redisSocket.Database;
}
public override void Dispose()
{
}
public override void Refersh(IRedisSocket redisSocket)
{
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
return DefaultRedisSocket.CreateTempProxy(_redisSocket, null);
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (_index == null || cmd._command == "QUIT")
return TopOwner.LogCall(cmd, () =>
{
_redisSocket.Write(cmd);
var rt = _redisSocket.Read(cmd);
if (cmd._command == "QUIT") _redisSocket.ReleaseSocket();
return parse(rt);
});
var cmds = new[]
{
new PipelineCommand
{
Command = "SELECT".Input(_index.Value),
Parse = rt => rt.ThrowOrValue()
},
new PipelineCommand
{
Command = cmd,
Parse = rt => parse(rt)
},
new PipelineCommand
{
Command = "SELECT".Input(_oldIndex),
Parse = rt => rt.ThrowOrValue()
},
};
return TopOwner.LogCall(cmd, () =>
{
cmds[1].Command.WriteTarget = $"{_redisSocket.Host}/{_index}";
PipelineAdapter.EndPipe(_redisSocket, cmds);
return (TValue)cmds[1].Result;
});
}
#if isasync
public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (_index == null || cmd._command == "QUIT")
return TopOwner.LogCallAsync(cmd, async () =>
{
await _redisSocket.WriteAsync(cmd);
var rt = await _redisSocket.ReadAsync(cmd);
if (cmd._command == "QUIT") _redisSocket.ReleaseSocket();
return parse(rt);
});
var cmds = new[]
{
new PipelineCommand
{
Command = "SELECT".Input(_index.Value),
Parse = rt => rt.ThrowOrValue()
},
new PipelineCommand
{
Command = cmd,
Parse = rt => parse(rt)
},
new PipelineCommand
{
Command = "SELECT".Input(_oldIndex),
Parse = rt => rt.ThrowOrValue()
},
};
return TopOwner.LogCallAsync(cmd, async () =>
{
cmds[1].Command.WriteTarget = $"{_redisSocket.Host}/{_index}";
PipelineAdapter.EndPipe(_redisSocket, cmds);
await Task.Yield();
return (TValue)cmds[1].Result;
});
}
#endif
}
}
} |
2881099/FreeRedis | 2,681 | src/FreeRedis/RedisClient/Adapter/SingleInsideAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
internal class SingleInsideAdapter : BaseAdapter
{
readonly IRedisSocket _redisSocket;
public SingleInsideAdapter(RedisClient topOwner, RedisClient owner, string host,
bool ssl, RemoteCertificateValidationCallback certificateValidation, LocalCertificateSelectionCallback certificateSelection,
TimeSpan connectTimeout, TimeSpan receiveTimeout, TimeSpan sendTimeout,
Action<RedisClient> connected, Action<RedisClient> disconnected)
{
UseType = UseType.SingleInside;
TopOwner = topOwner;
_redisSocket = new DefaultRedisSocket(host, ssl, certificateValidation, certificateSelection);
_redisSocket.Connected += (s, e) => connected?.Invoke(owner);
_redisSocket.Disconnected += (s, e) => disconnected?.Invoke(owner);
_redisSocket.ConnectTimeout = connectTimeout;
_redisSocket.ReceiveTimeout = receiveTimeout;
_redisSocket.SendTimeout = sendTimeout;
}
public override void Dispose()
{
_redisSocket.Dispose();
}
public override void Refersh(IRedisSocket redisSocket)
{
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
return DefaultRedisSocket.CreateTempProxy(_redisSocket, null);
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
return TopOwner.LogCall(cmd, () =>
{
_redisSocket.Write(cmd);
var rt = _redisSocket.Read(cmd);
if (cmd._command == "QUIT") _redisSocket.ReleaseSocket();
return parse(rt);
});
}
#if isasync
public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
return TopOwner.LogCallAsync(cmd, async () =>
{
await _redisSocket.WriteAsync(cmd);
var rt = await _redisSocket.ReadAsync(cmd);
if (cmd._command == "QUIT") _redisSocket.ReleaseSocket();
return parse(rt);
});
}
#endif
}
}
} |
2881099/FreeRedis | 10,362 | src/FreeRedis/RedisClient/Adapter/NormanAdapter.cs | using FreeRedis;
using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
internal class NormanAdapter : BaseAdapter
{
internal readonly IdleBus<RedisClientPool> _ib;
readonly ConnectionStringBuilder[] _connectionStrings;
readonly Func<string, string> _redirectRule;
internal static Encoding _baseEncoding;
public NormanAdapter(RedisClient topOwner, ConnectionStringBuilder[] connectionStrings, Func<string, string> redirectRule)
{
UseType = UseType.Cluster;
TopOwner = topOwner;
if (connectionStrings.Any() != true)
throw new ArgumentNullException(nameof(connectionStrings));
_connectionStrings = connectionStrings.ToArray();
_baseEncoding = connectionStrings.FirstOrDefault()?.Encoding;
_ib = new IdleBus<RedisClientPool>(TimeSpan.FromMinutes(10));
foreach (var connectionString in _connectionStrings)
RegisterClusterNode(connectionString);
_redirectRule = redirectRule;
}
bool isdisposed = false;
public override void Dispose()
{
foreach (var key in _ib.GetKeys())
{
var pool = _ib.Get(key);
TopOwner.Unavailable?.Invoke(TopOwner, new UnavailableEventArgs(pool.Key, pool));
}
isdisposed = true;
_ib.Dispose();
}
public override void Refersh(IRedisSocket redisSocket)
{
if (isdisposed) return;
var tmprds = redisSocket as DefaultRedisSocket.TempProxyRedisSocket;
if (tmprds != null) _ib.Get(tmprds._poolkey);
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
string[] poolkeys = null;
if (_redirectRule == null)
{
//crc16
var slots = cmd?._keyIndexes.Select(a => ClusterAdapter.GetClusterSlot(cmd._input[a].ToInvariantCultureToString(), _baseEncoding)).Distinct().ToArray();
poolkeys = slots?.Select(a => _connectionStrings[a % _connectionStrings.Length]).Select(a => $"{a.Host}/{a.Database}").Distinct().ToArray();
}
else
{
poolkeys = cmd?._keyIndexes.Select(a => _redirectRule(cmd._input[a].ToInvariantCultureToString())).Distinct().ToArray();
}
if (poolkeys == null) poolkeys = new[] { $"{_connectionStrings[0].Host}/{_connectionStrings[0].Database}" };
if (poolkeys.Length > 1) throw new RedisClientException($"CROSSSLOT Keys in request don't hash to the same slot: {cmd}");
var poolkey = poolkeys?.FirstOrDefault() ?? $"{_connectionStrings[0].Host}/{_connectionStrings[0].Database}";
var pool = _ib.Get(poolkey);
var cli = pool.Get();
var rds = cli.Value.Adapter.GetRedisSocket(null);
var rdsproxy = DefaultRedisSocket.CreateTempProxy(rds, () => pool.Return(cli));
rdsproxy._poolkey = poolkey;
rdsproxy._pool = pool;
return rdsproxy;
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (cmd._keyIndexes.Count > 1) //Multiple key slot values not equal
{
cmd.Prefix(TopOwner.Prefix);
switch (cmd._command)
{
case "DEL":
case "UNLINK":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
case "MSET":
cmd._keyIndexes.ForEach(idx => AdapterCall(cmd.Reset().InputKey(cmd._input[idx].ToInvariantCultureToString()).InputRaw(cmd._input[idx + 1]), parse));
return default;
case "MGET":
return cmd._keyIndexes.Select((_, idx) =>
{
var rt = AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse);
return rt.ConvertTo<object[]>().FirstOrDefault();
}).ToArray().ConvertTo<TValue>();
case "PFCOUNT":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
}
}
return TopOwner.LogCall(cmd, () =>
{
RedisResult rt = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
try
{
rds.Write(cmd);
rt = rds.Read(cmd);
}
catch (ProtocolViolationException)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
{
}
throw;
}
}
if (protocolRetry) return AdapterCall(cmd, parse);
return parse(rt);
});
}
#if isasync
async public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (cmd._keyIndexes.Count > 1) //Multiple key slot values not equal
{
cmd.Prefix(TopOwner.Prefix);
switch (cmd._command)
{
case "DEL":
case "UNLINK":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
case "MSET":
cmd._keyIndexes.ForEach(idx => AdapterCall(cmd.Reset().InputKey(cmd._input[idx].ToInvariantCultureToString()).InputRaw(cmd._input[idx + 1]), parse));
return default;
case "MGET":
return cmd._keyIndexes.Select((_, idx) =>
{
var rt = AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse);
return rt.ConvertTo<object[]>().FirstOrDefault();
}).ToArray().ConvertTo<TValue>();
case "PFCOUNT":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
}
}
return await TopOwner.LogCallAsync(cmd, async () =>
{
RedisResult rt = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
try
{
await rds.WriteAsync(cmd);
rt = await rds.ReadAsync(cmd);
}
catch (ProtocolViolationException)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
{
}
throw;
}
}
if (protocolRetry) return await AdapterCallAsync(cmd, parse);
return parse(rt);
});
}
#endif
//closure connectionString
void RegisterClusterNode(ConnectionStringBuilder connectionString)
{
_ib.TryRegister($"{connectionString.Host}/{connectionString.Database}", () => new RedisClientPool(connectionString, TopOwner));
}
}
}
}
|
2881099/FreeRedis | 7,350 | src/FreeRedis/RedisClient/Adapter/TransactionsAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
public TransactionHook Multi()
{
CheckUseTypeOrThrow(UseType.Pooling, UseType.Cluster, UseType.Sentinel, UseType.SingleInside, UseType.SingleTemp);
return new TransactionHook(new TransactionAdapter(Adapter.TopOwner));
}
public class TransactionHook : RedisClient
{
internal TransactionHook(BaseAdapter adapter) : base(adapter) { }
public void Discard() => (Adapter as TransactionAdapter).Discard();
public object[] Exec() => (Adapter as TransactionAdapter).Exec();
public void UnWatch() => (Adapter as TransactionAdapter).UnWatch();
public void Watch(params string[] keys) => (Adapter as TransactionAdapter).Watch(keys);
~TransactionHook()
{
(Adapter as TransactionAdapter).Dispose();
}
}
class TransactionAdapter : BaseAdapter
{
IRedisSocket _redisSocket;
readonly List<TransactionCommand> _commands;
internal class TransactionCommand
{
public CommandPacket Command { get; set; }
public Func<object, object> Parse { get; set; }
#if isasync
public TaskCompletionSource<object> TaskCompletionSource { get; set; }
bool TaskCompletionSourceIsTrySeted { get; set; }
public void TrySetResult(object result, Exception exception)
{
if (TaskCompletionSource == null) return;
if (TaskCompletionSourceIsTrySeted) return;
TaskCompletionSourceIsTrySeted = true;
if (exception != null) TaskCompletionSource.TrySetException(exception);
else TaskCompletionSource.TrySetResult(result);
}
public void TrySetCanceled()
{
if (TaskCompletionSource == null) return;
if (TaskCompletionSourceIsTrySeted) return;
TaskCompletionSourceIsTrySeted = true;
TaskCompletionSource.TrySetCanceled();
}
#endif
}
public TransactionAdapter(RedisClient topOwner)
{
UseType = UseType.Transaction;
TopOwner = topOwner;
_commands = new List<TransactionCommand>();
}
public override void Dispose()
{
Discard();
}
public override void Refersh(IRedisSocket redisSocket)
{
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
TryMulti(null);
return DefaultRedisSocket.CreateTempProxy(_redisSocket, null);
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
TryMulti(null);
return TopOwner.LogCall(cmd, () =>
{
_redisSocket.Write(cmd);
_redisSocket.Read(cmd).ThrowOrValue<TValue>(useDefaultValue: true);
_commands.Add(new TransactionCommand
{
Command = cmd,
Parse = obj => parse(new RedisResult(obj, true, RedisMessageType.SimpleString) { Encoding = _redisSocket.Encoding })
});
return default(TValue);
});
}
#if isasync
async public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
//Read with non byte[], Object deserialization is not supported
//The value returned by the callback is null :
// tran.Get<Book>("key1").ContinueWith(t => t3 = t.Result)
var tsc = new TaskCompletionSource<object>();
TryMulti(null);
TopOwner.LogCall(cmd, () =>
{
_redisSocket.Write(cmd);
_redisSocket.Read(cmd).ThrowOrValue<TValue>(useDefaultValue: true);
_commands.Add(new TransactionCommand
{
Command = cmd,
Parse = obj => parse(new RedisResult(obj, true, RedisMessageType.SimpleString) { Encoding = _redisSocket.Encoding }),
TaskCompletionSource = tsc
});
return default(TValue);
});
var ret = await tsc.Task;
return (TValue)ret;
}
#endif
object SelfCall(CommandPacket cmd)
{
return TopOwner.LogCall(cmd, () =>
{
_redisSocket.Write(cmd);
return _redisSocket.Read(cmd).ThrowOrValue();
});
}
public void TryMulti(string[] watchKeys)
{
if (_redisSocket == null)
{
_redisSocket = TopOwner.Adapter.GetRedisSocket(null);
if (watchKeys?.Any() == true)
SelfCall("WATCH".InputKey(watchKeys));
SelfCall("MULTI");
}
}
void TryReset()
{
if (_redisSocket == null) return;
#if isasync
for (var a = 0; a < _commands.Count; a++)
_commands[a].TrySetCanceled();
#endif
_commands.Clear();
_redisSocket?.Dispose();
_redisSocket = null;
}
public void Discard()
{
if (_redisSocket == null) return;
SelfCall("DISCARD");
TryReset();
}
public object[] Exec()
{
if (_redisSocket == null) return new object[0];
try
{
var ret = SelfCall("EXEC") as object[];
if (ret == null) //watch changed
{
#if isasync
for (var a = 0; a < _commands.Count; a++)
_commands[a].TrySetResult(null, null); //tryset Async
#endif
return null;
}
var retparsed = new object[ret.Length];
for (var a = 0; a < ret.Length; a++)
{
retparsed[a] = _commands[a].Parse(ret[a]);
#if isasync
_commands[a].TrySetResult(retparsed[a], null); //tryset Async
#endif
}
return retparsed;
}
finally
{
TryReset();
}
}
public void UnWatch()
{
if (_redisSocket == null) return;
SelfCall("UNWATCH");
}
public void Watch(params string[] keys)
{
TryMulti(keys);
}
}
}
}
|
2881099/FreeRedis | 24,633 | src/FreeRedis/RedisClient/Adapter/ClusterAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
internal class ClusterAdapter : BaseAdapter
{
internal readonly IdleBus<RedisClientPool> _ib;
internal readonly ConnectionStringBuilder[] _clusterConnectionStrings;
internal readonly Dictionary<string, string> _hostMappings;
internal static Encoding _baseEncoding;
public ClusterAdapter(RedisClient topOwner, ConnectionStringBuilder[] clusterConnectionStrings, Dictionary<string, string> hostMappings)
{
UseType = UseType.Cluster;
TopOwner = topOwner;
if (clusterConnectionStrings.Any() != true)
throw new ArgumentNullException(nameof(clusterConnectionStrings));
_clusterConnectionStrings = clusterConnectionStrings.ToArray();
if (hostMappings != null)
{
_hostMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var kv in hostMappings)
_hostMappings.Add(kv.Key, kv.Value);
}
_hostMappings = hostMappings;
_baseEncoding = _clusterConnectionStrings.FirstOrDefault()?.Encoding;
_ib = new IdleBus<RedisClientPool>(TimeSpan.FromMinutes(10));
RefershClusterNodes();
}
bool isdisposed = false;
public override void Dispose()
{
foreach(var key in _ib.GetKeys())
{
var pool = _ib.Get(key);
TopOwner.Unavailable?.Invoke(TopOwner, new UnavailableEventArgs(pool.Key, pool));
}
isdisposed = true;
_ib.Dispose();
}
public override void Refersh(IRedisSocket redisSocket)
{
if (isdisposed) return;
var tmprds = redisSocket as DefaultRedisSocket.TempProxyRedisSocket;
if (tmprds != null) _ib.Get(tmprds._poolkey);
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
var slots = cmd?._keyIndexes.Select(a => GetClusterSlot(cmd._input[a].ToInvariantCultureToString(), _baseEncoding)).Distinct().ToArray();
var poolkeys = slots?.Select(a => _slotCache.TryGetValue(a, out var trykey) ? trykey : null).Distinct().Where(a => a != null).ToArray();
//if (poolkeys.Length > 1) throw new RedisClientException($"CROSSSLOT Keys in request don't hash to the same slot: {cmd}");
var poolkey = poolkeys?.FirstOrDefault();
Exception poolUnavailableException = null;
goto_getrndkey:
if (string.IsNullOrEmpty(poolkey))
{
var rndkeys = _ib.GetKeys(v => v == null || v.IsAvailable);
if (rndkeys.Any() == false) throw poolUnavailableException ?? new RedisClientException($"All nodes of the cluster failed to connect");
poolkey = rndkeys[_rnd.Value.Next(0, rndkeys.Length)];
}
var pool = _ib.Get(poolkey);
if (pool.IsAvailable == false)
{
poolUnavailableException = pool.UnavailableException;
poolkey = null;
goto goto_getrndkey;
}
var cli = pool.Get();
var rds = cli.Value.Adapter.GetRedisSocket(null);
var rdsproxy = DefaultRedisSocket.CreateTempProxy(rds, () => pool.Return(cli));
rdsproxy._poolkey = poolkey;
rdsproxy._pool = pool;
return rdsproxy;
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (cmd._keyIndexes.Count > 1) //Multiple key slot values not equal
{
cmd.Prefix(TopOwner.Prefix);
switch (cmd._command)
{
case "DEL":
case "UNLINK":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
case "MSET":
cmd._keyIndexes.ForEach(idx => AdapterCall(cmd.Reset().InputKey(cmd._input[idx].ToInvariantCultureToString()).InputRaw(cmd._input[idx + 1]), parse));
return default;
case "MGET":
return cmd._keyIndexes.Select((_, idx) =>
{
var rt = AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse);
return rt.ConvertTo<object[]>().FirstOrDefault();
}).ToArray().ConvertTo<TValue>();
case "PFCOUNT":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
}
}
return TopOwner.LogCall(cmd, () =>
{
RedisResult rt = null;
RedisClientPool pool = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
try
{
if (cmd._clusterMovedAsking)
{
cmd._clusterMovedAsking = false;
var askingCmd = "ASKING".SubCommand(null).FlagReadbytes(false);
rds.Write(askingCmd);
rds.Read(askingCmd);
}
rds.Write(cmd);
rt = rds.Read(cmd);
}
catch (ProtocolViolationException)
{
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
{
}
throw;
}
}
if (protocolRetry) return AdapterCall(cmd, parse);
if (rt.IsError && pool != null)
{
var moved = ClusterMoved.ParseSimpleError(rt.SimpleError);
if (moved != null && cmd._clusterMovedTryCount < 3)
{
cmd._clusterMovedTryCount++;
var testConnection = pool._policy._connectionStringBuilder;
if (moved.endpoint.StartsWith("127.0.0.1"))
moved.endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{moved.endpoint.Substring(10)}";
else if (moved.endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
moved.endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{moved.endpoint.Substring(10)}";
ConnectionStringBuilder connectionString = testConnection.ToString();
connectionString.Host = moved.endpoint;
connectionString.CertificateValidation = testConnection.CertificateValidation;
connectionString.CertificateSelection = testConnection.CertificateSelection;
RegisterClusterNode(connectionString);
if (moved.ismoved)
_slotCache.AddOrUpdate(moved.slot, connectionString.Host, (k1, v1) => connectionString.Host);
if (moved.isask)
cmd._clusterMovedAsking = true;
TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{(cmd.WriteTarget ?? "Not connected").PadRight(21)} > {cmd}\r\n{rt.SimpleError} ", null));
return AdapterCall(cmd, parse);
}
}
return parse(rt);
});
}
#if isasync
async public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (cmd._keyIndexes.Count > 1) //Multiple key slot values not equal
{
cmd.Prefix(TopOwner.Prefix);
switch (cmd._command)
{
case "DEL":
case "UNLINK":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
case "MSET":
cmd._keyIndexes.ForEach(idx => AdapterCall(cmd.Reset().InputKey(cmd._input[idx].ToInvariantCultureToString()).InputRaw(cmd._input[idx + 1]), parse));
return default;
case "MGET":
return cmd._keyIndexes.Select((_, idx) =>
{
var rt = AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse);
return rt.ConvertTo<object[]>().FirstOrDefault();
}).ToArray().ConvertTo<TValue>();
case "PFCOUNT":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd.Reset().InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
}
}
return await TopOwner.LogCallAsync(cmd, async () =>
{
RedisResult rt = null;
RedisClientPool pool = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
try
{
if (cmd._clusterMovedAsking)
{
cmd._clusterMovedAsking = false;
var askingCmd = "ASKING".SubCommand(null).FlagReadbytes(false);
await rds.WriteAsync(askingCmd);
await rds.ReadAsync(askingCmd);
}
await rds.WriteAsync(cmd);
rt = await rds.ReadAsync(cmd);
}
catch (ProtocolViolationException)
{
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
{
}
throw;
}
}
if (protocolRetry) return await AdapterCallAsync(cmd, parse);
if (rt.IsError && pool != null)
{
var moved = ClusterMoved.ParseSimpleError(rt.SimpleError);
if (moved != null && cmd._clusterMovedTryCount < 3)
{
cmd._clusterMovedTryCount++;
var testConnection = pool._policy._connectionStringBuilder;
if (moved.endpoint.StartsWith("127.0.0.1"))
moved.endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{moved.endpoint.Substring(10)}";
else if (moved.endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
moved.endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{moved.endpoint.Substring(10)}";
ConnectionStringBuilder connectionString = testConnection.ToString();
connectionString.Host = moved.endpoint;
connectionString.CertificateValidation = testConnection.CertificateValidation;
connectionString.CertificateSelection = testConnection.CertificateSelection;
RegisterClusterNode(connectionString);
if (moved.ismoved)
_slotCache.AddOrUpdate(moved.slot, connectionString.Host, (k1, v1) => connectionString.Host);
if (moved.isask)
cmd._clusterMovedAsking = true;
TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{(cmd.WriteTarget ?? "Not connected").PadRight(21)} > {cmd}\r\n{rt.SimpleError} ", null));
return await AdapterCallAsync(cmd, parse);
}
}
return parse(rt);
});
}
#endif
void RefershClusterNodes()
{
Exception clusterException = null;
foreach (var testConnection in _clusterConnectionStrings)
{
var minPoolSize = testConnection.MinPoolSize;
testConnection.MinPoolSize = 1;
RegisterClusterNode(testConnection);
//尝试求出其他节点,并缓存slot
try
{
var cnodes = AdapterCall<string>("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>()).Split('\n');
var cnodesDict = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
foreach (var cnode in cnodes)
{
if (string.IsNullOrEmpty(cnode)) continue;
var dt = cnode.Trim().Split(' ');
if (dt.Length < 9) continue;
if (!dt[2].StartsWith("master") && !dt[2].EndsWith("master")) continue;
if (dt[7] != "connected") continue;
var endpoint = dt[1];
var at40 = endpoint.IndexOf('@');
if (at40 != -1) endpoint = endpoint.Remove(at40);
if (endpoint.StartsWith("127.0.0.1"))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
else if (endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
else if (_hostMappings?.TryGetValue(endpoint, out var endpointMapping) == true)
endpoint = endpointMapping;
ConnectionStringBuilder connectionString = testConnection.ToString();
connectionString.Host = endpoint;
connectionString.CertificateValidation = testConnection.CertificateValidation;
connectionString.CertificateSelection = testConnection.CertificateSelection;
if (cnodesDict.ContainsKey(endpoint) == false) cnodesDict.Add(endpoint, true);
RegisterClusterNode(connectionString);
for (var slotIndex = 8; slotIndex < dt.Length; slotIndex++)
{
var slots = dt[slotIndex].Split('-');
if (slots.Length == 2)
{
if (ushort.TryParse(slots[0], out var tryslotStart) &&
ushort.TryParse(slots[1], out var tryslotEnd))
{
for (var slot = tryslotStart; slot <= tryslotEnd; slot++)
_slotCache.AddOrUpdate(slot, connectionString.Host, (k1, v1) => connectionString.Host);
}
}else
{
ushort.TryParse(slots[0], out var tryslotStart);
_slotCache.AddOrUpdate(tryslotStart,connectionString.Host, (k1, v1) => connectionString.Host);
}
}
}
if (cnodesDict.ContainsKey(testConnection.Host))
RedisClientPoolPolicy.PrevReheatConnectionPool(_ib.Get(testConnection.Host), minPoolSize);
else
_ib.TryRemove(testConnection.Host, true);
break;
}
catch (Exception ex)
{
clusterException = ex;
_ib.TryRemove(testConnection.Host, true);
}
}
if (_ib.GetKeys().Length == 0)
throw new RedisClientException($"All \"clusterConnectionStrings\" failed to connect. {(clusterException?.Message)}");
}
//closure connectionString
void RegisterClusterNode(ConnectionStringBuilder connectionString)
{
_ib.TryRegister(connectionString.Host, () => new RedisClientPool(connectionString, TopOwner));
}
ConcurrentDictionary<ushort, string> _slotCache = new ConcurrentDictionary<ushort, string>();
class ClusterMoved
{
public bool ismoved;
public bool isask;
public ushort slot;
public string endpoint;
public static ClusterMoved ParseSimpleError(string simpleError)
{
if (string.IsNullOrWhiteSpace(simpleError)) return null;
var ret = new ClusterMoved
{
ismoved = simpleError.StartsWith("MOVED "), //永久定向
isask = simpleError.StartsWith("ASK ") //临时性一次定向
};
if (ret.ismoved == false && ret.isask == false) return null;
var parts = simpleError.Split(new string[] { "\r\n" }, StringSplitOptions.None).FirstOrDefault().Split(new[] { ' ' }, 3);
if (parts.Length != 3 ||
ushort.TryParse(parts[1], out ret.slot) == false) return null;
ret.endpoint = parts[2];
return ret;
}
}
#region crc16
private static readonly ushort[] crc16tab = {
0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7,
0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef,
0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6,
0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de,
0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485,
0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d,
0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4,
0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc,
0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823,
0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b,
0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12,
0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a,
0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41,
0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49,
0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70,
0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78,
0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f,
0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067,
0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e,
0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256,
0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d,
0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405,
0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c,
0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634,
0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab,
0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3,
0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a,
0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92,
0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9,
0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1,
0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8,
0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0
};
public static ushort GetClusterSlot(string key, System.Text.Encoding encoding = null)
{
if (encoding == null) encoding = Encoding.UTF8;
//HASH_SLOT = CRC16(key) mod 16384
var blob = encoding.GetBytes(key);
int offset = 0, count = blob.Length, start = -1, end = -1;
byte lt = (byte)'{', rt = (byte)'}';
for (int a = 0; a < count - 1; a++)
if (blob[a] == lt)
{
start = a;
break;
}
if (start >= 0)
{
for (int a = start + 1; a < count; a++)
if (blob[a] == rt)
{
end = a;
break;
}
}
if (start >= 0
&& end >= 0
&& --end != start)
{
offset = start + 1;
count = end - start;
}
uint crc = 0;
for (int i = 0; i < count; i++)
crc = ((crc << 8) ^ crc16tab[((crc >> 8) ^ blob[offset++]) & 0x00FF]) & 0x0000FFFF;
return (ushort)(crc % 16384);
}
#endregion
}
}
}
|
2881099/FreeRedis | 7,746 | src/FreeRedis/RedisClient/Adapter/PoolingAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Net;
namespace FreeRedis
{
partial class RedisClient
{
internal class PoolingAdapter : BaseAdapter
{
internal readonly IdleBus<RedisClientPool> _ib;
internal readonly string _masterHost;
readonly bool _rw_splitting;
readonly bool _is_single;
public PoolingAdapter(RedisClient topOwner, ConnectionStringBuilder connectionString, params ConnectionStringBuilder[] slaveConnectionStrings)
{
UseType = UseType.Pooling;
TopOwner = topOwner;
_masterHost = connectionString.Host;
_rw_splitting = slaveConnectionStrings?.Any() == true;
_is_single = !_rw_splitting && connectionString.MaxPoolSize == 1;
_ib = new IdleBus<RedisClientPool>(TimeSpan.FromMinutes(10));
_ib.Register(_masterHost, () => new RedisClientPool(connectionString, TopOwner));
if (_rw_splitting)
foreach (var slave in slaveConnectionStrings)
_ib.TryRegister($"slave_{slave.Host}", () => new RedisClientPool(slave, TopOwner));
}
bool isdisposed = false;
public override void Dispose()
{
foreach (var key in _ib.GetKeys())
{
var pool = _ib.Get(key);
TopOwner.Unavailable?.Invoke(TopOwner, new UnavailableEventArgs(pool.Key, pool));
}
isdisposed = true;
_ib.Dispose();
}
public override void Refersh(IRedisSocket redisSocket)
{
if (isdisposed) return;
var tmprds = redisSocket as DefaultRedisSocket.TempProxyRedisSocket;
if (tmprds != null) _ib.Get(tmprds._poolkey);
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
var poolkey = GetIdleBusKey(cmd);
var pool = _ib.Get(poolkey);
var cli = pool.Get();
var rds = cli.Value.Adapter.GetRedisSocket(null);
var rdsproxy = DefaultRedisSocket.CreateTempProxy(rds, () => pool.Return(cli));
rdsproxy._poolkey = poolkey;
rdsproxy._pool = pool;
return rdsproxy;
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
return TopOwner.LogCall(cmd, () =>
{
RedisResult rt = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
try
{
rds.Write(cmd);
rt = rds.Read(cmd);
}
catch (ProtocolViolationException)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
{
}
throw;
}
}
if (protocolRetry) return AdapterCall(cmd, parse);
return parse(rt);
});
}
#if isasync
public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
return TopOwner.LogCallAsync(cmd, async () =>
{
RedisResult rt = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
try
{
await rds.WriteAsync(cmd);
rt = await rds.ReadAsync(cmd);
}
catch (ProtocolViolationException)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
{
}
throw;
}
}
if (protocolRetry) return await AdapterCallAsync(cmd, parse);
return parse(rt);
});
}
#endif
string GetIdleBusKey(CommandPacket cmd)
{
if (cmd != null && (_rw_splitting || !_is_single))
{
var cmdset = CommandSets.Get(cmd._command);
if (cmdset != null)
{
if (!_is_single && (cmdset.Status & CommandSets.LocalStatus.check_single) == CommandSets.LocalStatus.check_single)
throw new RedisClientException($"Method cannot be used in {UseType} mode. You can set \"max pool size=1\", but it is not singleton mode.");
if (_rw_splitting &&
((cmdset.Tag & CommandSets.ServerTag.read) == CommandSets.ServerTag.read ||
(cmdset.Flag & CommandSets.ServerFlag.@readonly) == CommandSets.ServerFlag.@readonly))
{
var rndkeys = _ib.GetKeys(v => v == null || v.IsAvailable && v._policy._connectionStringBuilder.Host != _masterHost);
if (rndkeys.Any())
{
var rndkey = rndkeys[_rnd.Value.Next(0, rndkeys.Length)];
return rndkey;
}
}
}
}
return _masterHost;
}
}
}
} |
2881099/FreeRedis | 1,191 | src/FreeRedis/RedisClient/Adapter/BaseAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
protected internal enum UseType
{
Pooling,
Cluster,
Sentinel,
SingleInside,
SingleTemp,
Pipeline,
Transaction,
}
protected internal abstract partial class BaseAdapter
{
public static ThreadLocal<Random> _rnd = new ThreadLocal<Random>(() => new Random());
public UseType UseType { get; protected set; }
protected internal RedisClient TopOwner { get; protected set; }
public abstract void Refersh(IRedisSocket redisSocket);
public abstract IRedisSocket GetRedisSocket(CommandPacket cmd);
public abstract void Dispose();
public abstract TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse);
#if isasync
public abstract Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse);
#endif
}
}
}
|
2881099/FreeRedis | 18,146 | src/FreeRedis/RedisClient/Adapter/SentinelAdapter.cs | using FreeRedis.Internal;
using FreeRedis.Internal.ObjectPool;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
internal class SentinelAdapter : BaseAdapter
{
internal readonly IdleBus<RedisClientPool> _ib;
internal readonly ConnectionStringBuilder _connectionString;
readonly LinkedList<ConnectionStringBuilder> _sentinels;
readonly List<RedisClient> _sentinelSubscribes;
string _masterHost;
readonly bool _rw_splitting;
readonly bool _is_single;
Exception _switchingException;
public SentinelAdapter(RedisClient topOwner, ConnectionStringBuilder sentinelConnectionString, string[] sentinels, bool rw_splitting)
{
UseType = UseType.Sentinel;
TopOwner = topOwner;
_connectionString = sentinelConnectionString;
_sentinels = new LinkedList<ConnectionStringBuilder>(sentinels?.Select(a =>
{
var csb = ConnectionStringBuilder.Parse(a);
csb.Host = csb.Host.ToLower();
csb.CertificateValidation = _connectionString.CertificateValidation;
csb.CertificateSelection = _connectionString.CertificateSelection;
csb.MaxPoolSize = 1;
csb.MinPoolSize = 1;
return csb;
}).GroupBy(a => a.Host, a => a).Select(a => a.First()) ?? new ConnectionStringBuilder[0]);
_rw_splitting = rw_splitting;
_is_single = !_rw_splitting && sentinelConnectionString.MaxPoolSize == 1;
if (_sentinels.Any() == false) throw new ArgumentNullException(nameof(sentinels));
_ib = new IdleBus<RedisClientPool>(TimeSpan.FromMinutes(10));
ResetSentinel();
_sentinelSubscribes = new List<RedisClient>();
foreach (var item in _sentinels)
{
var itemClient = new RedisClient(item);
itemClient.Subscribe("+switch-master", (chan, msg) =>
{
if (chan == "+switch-master" && msg != null)
{
var args = msg?.ToString().Split(' '); //mymaster 127.0.0.1 6381 127.0.0.1 6379
if (args == null || args.Length < 5) return;
if (_connectionString.Host != args[0]) return;
var masterhostEnd = $"{args[3]}:{args[4]}";
_ib.TryRemove(_masterHost);
ConnectionStringBuilder connectionString = _connectionString.ToString();
connectionString.Host = masterhostEnd;
connectionString.MinPoolSize = _connectionString.MinPoolSize;
connectionString.MaxPoolSize = _connectionString.MaxPoolSize;
connectionString.CertificateValidation = _connectionString.CertificateValidation;
connectionString.CertificateSelection = _connectionString.CertificateSelection;
_ib.TryRegister(masterhostEnd, () => new RedisClientPool(connectionString, TopOwner));
Interlocked.Exchange(ref _masterHost, masterhostEnd);
if (!TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{_connectionString.Host.PadRight(21)} > Redis Sentinel switch to {_masterHost}", null)))
TestTrace.WriteLine($"【{_connectionString.Host}】Redis Sentinel switch to {_masterHost}", ConsoleColor.DarkGreen);
}
});
_sentinelSubscribes.Add(itemClient);
}
}
bool isdisposed = false;
public override void Dispose()
{
//_sentinelSubscribe.Dispose();
foreach (var item in _sentinelSubscribes)
{
try
{
item.Dispose();
}
catch
{
}
}
_sentinelSubscribes.Clear();
foreach (var key in _ib.GetKeys())
{
var pool = _ib.Get(key);
TopOwner.Unavailable?.Invoke(TopOwner, new UnavailableEventArgs(pool.Key, pool));
}
isdisposed = true;
_ib.Dispose();
}
public override void Refersh(IRedisSocket redisSocket)
{
if (isdisposed) return;
var tmprds = redisSocket as DefaultRedisSocket.TempProxyRedisSocket;
if (tmprds != null) _ib.Get(tmprds._poolkey);
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
var poolkey = GetIdleBusKey(cmd);
if (string.IsNullOrWhiteSpace(poolkey)) throw new RedisClientException($"【{_connectionString.Host}】Redis Sentinel is switching{(_switchingException == null ? "" : $", {_switchingException.Message}")}");
var pool = _ib.Get(poolkey);
var cli = pool.Get();
var rds = cli.Value.Adapter.GetRedisSocket(null);
var rdsproxy = DefaultRedisSocket.CreateTempProxy(rds, () => pool.Return(cli));
rdsproxy._poolkey = poolkey;
rdsproxy._pool = pool;
return rdsproxy;
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
return TopOwner.LogCall(cmd, () =>
{
RedisResult rt = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
try
{
rds.Write(cmd);
rt = rds.Read(cmd);
}
catch (ProtocolViolationException)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
if (!protocolRetry) RecoverySentinel(false);
}
catch (Exception ex)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)?._pool;
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
RecoverySentinel(true);
throw;
}
}
if (protocolRetry) return AdapterCall(cmd, parse);
return parse(rt);
});
}
#if isasync
public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
return TopOwner.LogCallAsync(cmd, async () =>
{
RedisResult rt = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
var getTime = DateTime.Now;
try
{
await rds.WriteAsync(cmd);
rt = await rds.ReadAsync(cmd);
}
catch (ProtocolViolationException)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
if (!protocolRetry) RecoverySentinel(false);
}
catch (Exception ex)
{
var pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)?._pool;
if (cmd.IsBlockingCommand() == false && pool?.SetUnavailable(ex, getTime) == true)
RecoverySentinel(true);
throw;
}
}
if (protocolRetry) return await AdapterCallAsync(cmd, parse);
return parse(rt);
});
}
#endif
internal string GetIdleBusKey(CommandPacket cmd)
{
if (cmd != null && (_rw_splitting || !_is_single))
{
var cmdset = CommandSets.Get(cmd._command);
if (cmdset != null)
{
if (!_is_single && (cmdset.Status & CommandSets.LocalStatus.check_single) == CommandSets.LocalStatus.check_single)
throw new RedisClientException($"Method cannot be used in {UseType} mode. You can set \"max pool size=1\", but it is not singleton mode.");
if (_rw_splitting &&
((cmdset.Tag & CommandSets.ServerTag.read) == CommandSets.ServerTag.read ||
(cmdset.Flag & CommandSets.ServerFlag.@readonly) == CommandSets.ServerFlag.@readonly))
{
var rndkeys = _ib.GetKeys(v => v == null || v.IsAvailable && v._policy._connectionStringBuilder.Host != _masterHost);
if (rndkeys.Any())
{
var rndkey = rndkeys[_rnd.Value.Next(0, rndkeys.Length)];
return rndkey;
}
}
}
}
return _masterHost;
}
int ResetSentinelFlag = 0;
internal void ResetSentinel()
{
if (ResetSentinelFlag != 0) return;
if (Interlocked.Increment(ref ResetSentinelFlag) != 1)
{
Interlocked.Decrement(ref ResetSentinelFlag);
return;
}
_switchingException = null;
string masterhostEnd = _masterHost;
var allkeys = _ib.GetKeys().ToList();
for (int i = 0; i < _sentinels.Count; i++)
{
if (i > 0)
{
var first = _sentinels.First;
_sentinels.RemoveFirst();
_sentinels.AddLast(first.Value);
}
try
{
using (var sentinelcli = new RedisSentinelClient(_sentinels.First.Value))
{
var masterhost = sentinelcli.GetMasterAddrByName(_connectionString.Host);
var masterConnectionString = localTestHost(masterhost, RoleType.Master);
if (masterConnectionString == null) continue;
masterhostEnd = masterhost;
if (_rw_splitting)
{
foreach (var slave in sentinelcli.Salves(_connectionString.Host))
{
ConnectionStringBuilder slaveConnectionString = localTestHost($"{slave.ip}:{slave.port}", RoleType.Slave);
if (slaveConnectionString == null) continue;
}
}
foreach (var sentinel in sentinelcli.Sentinels(_connectionString.Host))
{
ConnectionStringBuilder remoteSentinelHost = _sentinels.First.Value.ToString();
remoteSentinelHost.Host = $"{sentinel.ip}:{sentinel.port}";
remoteSentinelHost.CertificateValidation = _connectionString.CertificateValidation;
remoteSentinelHost.CertificateSelection = _connectionString.CertificateSelection;
if (_sentinels.Any(a => string.Compare(a.Host, remoteSentinelHost.Host, true) == 0)) continue;
_sentinels.AddLast(remoteSentinelHost);
}
}
break;
}
catch (Exception ex)
{
_switchingException = ex;
}
}
foreach (var spkey in allkeys) _ib.TryRemove(spkey, true);
Interlocked.Exchange(ref _masterHost, masterhostEnd);
Interlocked.Decrement(ref ResetSentinelFlag);
ConnectionStringBuilder localTestHost(string host, RoleType role)
{
ConnectionStringBuilder connectionString = _connectionString.ToString();
connectionString.Host = host;
connectionString.MinPoolSize = 1;
connectionString.MaxPoolSize = 1;
connectionString.CertificateValidation = _connectionString.CertificateValidation;
connectionString.CertificateSelection = _connectionString.CertificateSelection;
using (var cli = new RedisClient(connectionString))
{
if (cli.Role().role != role)
return null;
if (role == RoleType.Master)
{
//test set/get
}
}
connectionString.MinPoolSize = _connectionString.MinPoolSize;
connectionString.MaxPoolSize = _connectionString.MaxPoolSize;
_ib.TryRegister(host, () => new RedisClientPool(connectionString, TopOwner));
allkeys.Remove(host);
return connectionString;
}
}
bool RecoverySentineling = false;
object RecoverySentinelingLock = new object();
bool RecoverySentinel(bool isSleep)
{
var ing = false;
if (RecoverySentineling == false)
lock (RecoverySentinelingLock)
{
if (RecoverySentineling == false)
RecoverySentineling = ing = true;
}
if (ing)
{
new Thread(() =>
{
while (true)
{
if(isSleep)
Thread.CurrentThread.Join(1000);
try
{
var oldMasterHost = _masterHost;
ResetSentinel();
if (oldMasterHost != _masterHost && _ib.Get(_masterHost).CheckAvailable())
{
if (!TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{_connectionString.Host.PadRight(21)} > Redis Sentinel switch to {_masterHost}", null)))
TestTrace.WriteLine($"【{_connectionString.Host}】Redis Sentinel switch to {_masterHost}", ConsoleColor.DarkGreen);
RecoverySentineling = false;
return;
}
else if (oldMasterHost == _masterHost && _ib.Get(_masterHost).CheckAvailable())
{
RecoverySentineling = false;
return;
}
}
catch (Exception ex21)
{
if (!TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{_connectionString.Host.PadRight(21)} > Redis Sentinel switch to {_masterHost}", null)))
TestTrace.WriteLine($"【{_connectionString.Host}】Redis Sentinel: {ex21.Message}", ConsoleColor.DarkYellow);
}
finally {
if (!isSleep)
Thread.CurrentThread.Join(1000);
}
}
}).Start();
}
return ing;
}
}
}
} |
2881099/FreeRedis | 7,339 | src/FreeRedis/RedisClient/Adapter/PipelineAdapter.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
// Pipeline
public PipelineHook StartPipe()
{
CheckUseTypeOrThrow(UseType.Pooling, UseType.Cluster, UseType.Sentinel, UseType.SingleInside, UseType.SingleTemp);
return new PipelineHook(new PipelineAdapter(Adapter));
}
public class PipelineHook : RedisClient
{
internal PipelineHook(BaseAdapter adapter) : base(adapter) { }
public object[] EndPipe() => (Adapter as PipelineAdapter).EndPipe();
~PipelineHook()
{
(Adapter as PipelineAdapter).Dispose();
}
}
internal class PipelineCommand
{
public CommandPacket Command { get; set; }
public Func<RedisResult, object> Parse { get; set; }
public bool IsBytes { get; set; }
public RedisResult RedisResult { get; set; }
public object Result { get; set; }
#if isasync
public TaskCompletionSource<object> TaskCompletionSource { get; set; }
bool TaskCompletionSourceIsTrySeted { get; set; }
public void TrySetResult(object result, Exception exception)
{
if (TaskCompletionSource == null) return;
if (TaskCompletionSourceIsTrySeted) return;
TaskCompletionSourceIsTrySeted = true;
if (exception != null) TaskCompletionSource.TrySetException(exception);
else TaskCompletionSource.TrySetResult(result);
}
public void TrySetCanceled()
{
if (TaskCompletionSource == null) return;
if (TaskCompletionSourceIsTrySeted) return;
TaskCompletionSourceIsTrySeted = true;
TaskCompletionSource.TrySetCanceled();
}
#endif
}
class PipelineAdapter : BaseAdapter
{
readonly List<PipelineCommand> _commands;
readonly BaseAdapter _baseAdapter;
public PipelineAdapter(BaseAdapter baseAdapter)
{
UseType = UseType.Pipeline;
TopOwner = baseAdapter.TopOwner;
_baseAdapter = baseAdapter;
_commands = new List<PipelineCommand>();
}
public override void Dispose()
{
#if isasync
for (var a = 0; a < _commands.Count; a++)
_commands[a].TrySetCanceled();
#endif
_commands.Clear();
}
public override void Refersh(IRedisSocket redisSocket)
{
}
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
throw new RedisClientException($"RedisClient: Method cannot be used in {UseType} mode.");
}
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
cmd.Prefix(TopOwner.Prefix);
_commands.Add(new PipelineCommand
{
Command = cmd,
Parse = rt => parse(rt),
IsBytes = cmd._flagReadbytes
});
TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Call, null, $"{"Pipeline".PadRight(21)} > {cmd}\r\n", null));
return default(TValue);
}
#if isasync
async public override Task<TValue> AdapterCallAsync<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
var tsc = new TaskCompletionSource<object>();
cmd.Prefix(TopOwner.Prefix);
_commands.Add(new PipelineCommand
{
Command = cmd,
Parse = rt => parse(rt),
IsBytes = cmd._flagReadbytes,
TaskCompletionSource = tsc
});
TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Call, null, $"{"Pipeline".PadRight(21)} > {cmd}\r\n", null));
var ret = await tsc.Task;
return (TValue)ret;
}
#endif
public object[] EndPipe()
{
if (_commands.Any() == false) return new object[0];
try
{
switch (UseType)
{
case UseType.Pooling: break;
case UseType.Cluster: return ClusterEndPipe();
case UseType.Sentinel:
case UseType.SingleInside: break;
case UseType.SingleTemp: break;
}
CommandPacket epcmd = "EndPipe";
return TopOwner.LogCall(epcmd, () =>
{
using (var rds = _baseAdapter.GetRedisSocket(null))
{
epcmd.WriteTarget = $"{rds.Host}/{rds.Database}";
EndPipe(rds, _commands);
}
return _commands.Select(a => a.Result).ToArray();
});
}
finally
{
Dispose();
}
object[] ClusterEndPipe()
{
throw new NotSupportedException();
}
}
internal static void EndPipe(IRedisSocket rds, IEnumerable<PipelineCommand> cmds)
{
var err = new List<PipelineCommand>();
var ms = new MemoryStream();
try
{
var respWriter = new RespHelper.Resp3Writer(ms, rds.Encoding, rds.Protocol);
foreach (var cmd in cmds)
respWriter.WriteCommand(cmd.Command);
if (rds.IsConnected == false) rds.Connect();
ms.Position = 0;
ms.CopyTo(rds.Stream);
foreach (var pc in cmds)
{
pc.RedisResult = rds.Read(pc.Command);
pc.Result = pc.Parse(pc.RedisResult);
if (pc.RedisResult.IsError) err.Add(pc);
#if isasync
pc.TrySetResult(pc.Result, pc.RedisResult.IsError ? new RedisServerException(pc.RedisResult.SimpleError) : null);
#endif
}
}
finally
{
ms.Close();
ms.Dispose();
}
if (err.Any())
{
var sb = new StringBuilder();
for (var a = 0; a < err.Count; a++)
{
var cmd = err[a].Command;
if (a > 0) sb.Append("\r\n");
sb.Append(err[a].RedisResult.SimpleError).Append(" {").Append(cmd.ToString()).Append("}");
}
throw new RedisServerException(sb.ToString());
}
}
}
}
}
|
2881099/FreeRedis | 5,028 | src/FreeRedis/RedisClient/Modules/RedisBloomCuckooFilter.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string> CfReserveAsync(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null) => CallAsync("CF.RESERVE"
.InputKey(key, capacity)
.InputIf(bucketSize != 2, "BUCKETSIZE", bucketSize)
.InputIf(maxIterations != 2, "MAXITERATIONS", maxIterations)
.InputIf(expansion != 2, "EXPANSION", expansion), rt => rt.ThrowOrValue<string>());
public Task<bool> CfAddAsync(string key, string item) => CallAsync("CF.ADD".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public Task<bool> CfAddNxAsync(string key, string item) => CallAsync("CF.ADDNX".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
async public Task<string> CfInsertAsync(string key, string[] items, long? capacity = null, bool noCreate = false) => await CfInsertAsync(false, key, items, capacity, noCreate);
async public Task<string> CfInsertNxAsync(string key, string[] items, long? capacity = null, bool noCreate = false) => await CfInsertAsync(true, key, items, capacity, noCreate);
Task<string> CfInsertAsync(bool nx, string key, string[] items, long? capacity = null, bool noCreate = false) => CallAsync((nx ? "CF.INSERTNX" : "CF.INSERT")
.InputKey(key)
.InputIf(capacity != null, "CAPACITY", capacity)
.InputIf(noCreate, "NOCREATE")
.Input("ITEMS", items), rt => rt.ThrowOrValue<string>());
public Task<bool> CfExistsAsync(string key, string item) => CallAsync("CF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public Task<bool> CfDelAsync(string key, string item) => CallAsync("CF.DEL".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public Task<long> CfCountAsync(string key, string item) => CallAsync("CF.COUNT".InputKey(key, item), rt => rt.ThrowOrValue<long>());
public Task<ScanResult<byte[]>> CfScanDumpAsync(string key, long iter) => CallAsync("CF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) =>
new ScanResult<byte[]>(a[0].ConvertTo<long>(), a[1].ConvertTo<byte[][]>())));
public Task<string> CfLoadChunkAsync(string key, long iter, byte[] data) => CallAsync("CF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue<string>());
public Task<Dictionary<string, string>> CfInfoAsync(string key) => CallAsync("CF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
#endregion
#endif
public string CfReserve(string key, long capacity, long? bucketSize = null, long? maxIterations = null, int? expansion = null) => Call("CF.RESERVE"
.InputKey(key, capacity)
.InputIf(bucketSize != 2, "BUCKETSIZE", bucketSize)
.InputIf(maxIterations != 2, "MAXITERATIONS", maxIterations)
.InputIf(expansion != 2, "EXPANSION", expansion), rt => rt.ThrowOrValue<string>());
public bool CfAdd(string key, string item) => Call("CF.ADD".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public bool CfAddNx(string key, string item) => Call("CF.ADDNX".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public string CfInsert(string key, string[] items, long? capacity = null, bool noCreate = false) => CfInsert(false, key, items, capacity, noCreate);
public string CfInsertNx(string key, string[] items, long? capacity = null, bool noCreate = false) => CfInsert(true, key, items, capacity, noCreate);
string CfInsert(bool nx, string key, string[] items, long? capacity = null, bool noCreate = false) => Call((nx ? "CF.INSERTNX" : "CF.INSERT")
.InputKey(key)
.InputIf(capacity != null, "CAPACITY", capacity)
.InputIf(noCreate, "NOCREATE")
.Input("ITEMS", items), rt => rt.ThrowOrValue<string>());
public bool CfExists(string key, string item) => Call("CF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public bool CfDel(string key, string item) => Call("CF.DEL".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public long CfCount(string key, string item) => Call("CF.COUNT".InputKey(key, item), rt => rt.ThrowOrValue<long>());
public ScanResult<byte[]> CfScanDump(string key, long iter) => Call("CF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) =>
new ScanResult<byte[]>(a[0].ConvertTo<long>(), a[1].ConvertTo<byte[][]>())));
public string CfLoadChunk(string key, long iter, byte[] data) => Call("CF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue<string>());
public Dictionary<string, string> CfInfo(string key) => Call("CF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
}
}
|
2881099/FreeRedis | 12,209 | src/FreeRedis/RedisClient/Modules/RediSearch.cs | using FreeRedis.RediSearch;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string[]> Ft_ListAsync() => CallAsync("FT._LIST", rt => rt.ThrowOrValue<string[]>());
public Task FtAliasAddAsync(string alias, string index) => CallAsync("FT.ALIASADD".Input(alias, index), rt => rt.ThrowOrValue<string>() == "OK");
public Task FtAliasDelAsync(string alias) => CallAsync("FT.ALIASDEL".Input(alias), rt => rt.ThrowOrValue<string>() == "OK");
public Task FtAliasUpdateAsync(string alias, string index) => CallAsync("FT.ALIASUPDATE".Input(alias, index), rt => rt.ThrowOrValue<string>() == "OK");
public Task<Dictionary<string, object>> FtConfigGetAsync(string option, string value) => CallAsync("FT.CONFIG".SubCommand("GET").Input(option, value), rt => rt.ThrowOrValue((a, _) => a.MapToHash<object>(rt.Encoding)));
public Task FtConfigSetAsync(string option, string value) => CallAsync("FT.CONFIG".SubCommand("SET").Input(option, value), rt => rt.ThrowOrValue<string>() == "OK");
public Task FtCursorDelAsync(string index, long cursor_id) => CallAsync("FT.CURSOR".SubCommand("DEL").Input(index, cursor_id), rt => rt.ThrowOrValue<string>() == "OK");
public Task<AggregationResult> FtCursorReadAsync(string index, long cursorId, int count = 0) => CallAsync("FT.CURSOR".SubCommand("READ")
.Input(index, cursorId)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new AggregationResult(a[0], a[1].ConvertTo<long>())));
public Task<long> FtDictAddAsync(string dict, params string[] terms) => CallAsync("FT.DICTADD".Input(dict).Input(terms.Select(a => (object)a).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<long> FtDictDelAsync(string dict, params string[] terms) => CallAsync("FT.DICTDEL".Input(dict).Input(terms.Select(a => (object)a).ToArray()), rt => rt.ThrowOrValue<long>());
public Task<string[]> FtDictDumpAsync(string dict) => CallAsync("FT.DICTDUMP".Input(dict), rt => rt.ThrowOrValue<string[]>());
public Task FtDropIndexAsync(string index, bool dd = false) => CallAsync("FT.DROPINDEX".Input(index).InputIf(dd, "DD"), rt => rt.ThrowOrValue<string>() == "OK");
public Task<string> FtExplainAsync(string index, string query, string dialect = null) => CallAsync("FT.EXPLAIN".Input(index, query).InputIf(!string.IsNullOrEmpty(dialect), "DIALECT", dialect), rt => rt.ThrowOrValue<string>());
public Task<Dictionary<string, Dictionary<string, double>>> FtSpellCheckAsync(string index, string query, int distance = 1, int? dialect = null) => CallAsync("FT.SPELLCHECK".Input(index, query)
.InputIf(distance > 1, "DISTANCE", distance)
.InputIf((dialect ?? ConnectionString.FtDialect) > 0, "DIALECT", dialect), rt => rt.ThrowOrValueToFtSpellCheckResult());
public Task<Dictionary<string, string[]>> FtSynDumpAsync(string index) => CallAsync("FT.SYNDUMP".Input(index), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string[]>(rt.Encoding)));
public Task FtSynUpdateAsync(string index, string synonymGroupId, bool skipInitialScan, params string[] terms) => CallAsync("FT.SYNUPDATE"
.Input(index, synonymGroupId)
.InputIf(skipInitialScan, "SKIPINITIALSCAN")
.Input(terms.Select(a => (object)a).ToArray()), rt => rt.ThrowOrValue<string>() == "OK");
public Task<long> FtSugAddAsync(string key, string str, double score, bool incr = false, string payload = null) => CallAsync("FT.SUGADD".InputKey(key).Input(str, score)
.InputIf(incr, "INCR")
.InputIf(payload != null, "PAYLOAD", payload), rt => rt.ThrowOrValue<long>());
public Task FtSugDelAsync(string key, string str) => CallAsync("FT.SUGDEL".InputKey(key).Input(str), rt => rt.ThrowOrValue<long>());
public Task<string[]> FtSugGetAsync(string key, string prefix, bool fuzzy = false, bool withScores = false, bool withPayloads = false, int? max = null) => CallAsync("FT.SUGGET".InputKey(key)
.Input(prefix)
.InputIf(fuzzy, "FUZZY")
.InputIf(withScores, "WITHSCORES")
.InputIf(withPayloads, "WITHPAYLOADS")
.InputIf(max != null, "MAX", max), rt => rt.ThrowOrValue<string[]>());
public Task FtSugLenAsync(string key) => CallAsync("FT.SUGLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public Task<string[]> FtTagValsAsync(string index, string fieldName) => CallAsync("FT.TAGVALS".Input(index, fieldName), rt => rt.ThrowOrValue<string[]>());
#endregion
#endif
public FtDocumentRepository<T> FtDocumentRepository<T>() => new FtDocumentRepository<T>(this);
public string[] Ft_List() => Call("FT._LIST", rt => rt.ThrowOrValue<string[]>());
public AggregateBuilder FtAggregate(string index, string query) => new AggregateBuilder(this, index, query);
public void FtAliasAdd(string alias, string index) => Call("FT.ALIASADD".Input(alias, index), rt => rt.ThrowOrValue<string>() == "OK");
public void FtAliasDel(string alias) => Call("FT.ALIASDEL".Input(alias), rt => rt.ThrowOrValue<string>() == "OK");
public void FtAliasUpdate(string alias, string index) => Call("FT.ALIASUPDATE".Input(alias, index), rt => rt.ThrowOrValue<string>() == "OK");
public AlterBuilder FtAlter(string index) => new AlterBuilder(this, index);
public Dictionary<string, object> FtConfigGet(string option, string value) => Call("FT.CONFIG".SubCommand("GET").Input(option, value), rt => rt.ThrowOrValue((a, _) => a.MapToHash<object>(rt.Encoding)));
public void FtConfigSet(string option, string value) => Call("FT.CONFIG".SubCommand("SET").Input(option, value), rt => rt.ThrowOrValue<string>() == "OK");
public CreateBuilder FtCreate(string index) => new CreateBuilder(this, index);
public void FtCursorDel(string index, long cursor_id) => Call("FT.CURSOR".SubCommand("DEL").Input(index, cursor_id), rt => rt.ThrowOrValue<string>() == "OK");
public AggregationResult FtCursorRead(string index, long cursorId, int count = 0) => Call("FT.CURSOR".SubCommand("READ")
.Input(index, cursorId)
.InputIf(count > 0, "COUNT", count), rt => rt.ThrowOrValue((a, _) => new AggregationResult(a[0], a[1].ConvertTo<long>())));
public long FtDictAdd(string dict, params string[] terms) => Call("FT.DICTADD".Input(dict).Input(terms.Select(a => (object)a).ToArray()), rt => rt.ThrowOrValue<long>());
public long FtDictDel(string dict, params string[] terms) => Call("FT.DICTDEL".Input(dict).Input(terms.Select(a => (object)a).ToArray()), rt => rt.ThrowOrValue<long>());
public string[] FtDictDump(string dict) => Call("FT.DICTDUMP".Input(dict), rt => rt.ThrowOrValue<string[]>());
public void FtDropIndex(string index, bool dd = false) => Call("FT.DROPINDEX".Input(index).InputIf(dd, "DD"), rt => rt.ThrowOrValue<string>() == "OK");
public string FtExplain(string index, string query, string dialect = null) => Call("FT.EXPLAIN".Input(index, query).InputIf(!string.IsNullOrEmpty(dialect), "DIALECT", dialect), rt => rt.ThrowOrValue<string>());
//public object FtInfo(string index) => Call("FT.INFO".Input(index), rt => rt.ThrowOrValue<object>());
//public object FtProfile(string index) => Call("FT.PROFILE".Input(index), rt => rt.ThrowOrValue<object>());
public SearchBuilder FtSearch(string index, string query) => new SearchBuilder(this, index, query);
public Dictionary<string, Dictionary<string, double>> FtSpellCheck(string index, string query, int distance = 1, int? dialect = null) => Call("FT.SPELLCHECK".Input(index, query)
.InputIf(distance > 1, "DISTANCE", distance)
.InputIf((dialect ?? ConnectionString.FtDialect) > 0, "DIALECT", dialect), rt => rt.ThrowOrValueToFtSpellCheckResult());
public Dictionary<string, string[]> FtSynDump(string index) => Call("FT.SYNDUMP".Input(index), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string[]>(rt.Encoding)));
public void FtSynUpdate(string index, string synonymGroupId, bool skipInitialScan, params string[] terms) => Call("FT.SYNUPDATE"
.Input(index, synonymGroupId)
.InputIf(skipInitialScan, "SKIPINITIALSCAN")
.Input(terms.Select(a => (object)a).ToArray()), rt => rt.ThrowOrValue<string>() == "OK");
public long FtSugAdd(string key, string str, double score, bool incr = false, string payload = null) => Call("FT.SUGADD".InputKey(key).Input(str, score)
.InputIf(incr, "INCR")
.InputIf(payload != null, "PAYLOAD", payload), rt => rt.ThrowOrValue<long>());
public void FtSugDel(string key, string str) => Call("FT.SUGDEL".InputKey(key).Input(str), rt => rt.ThrowOrValue<long>());
public string[] FtSugGet(string key, string prefix, bool fuzzy = false, bool withScores = false, bool withPayloads = false, int? max = null) => Call("FT.SUGGET".InputKey(key)
.Input(prefix)
.InputIf(fuzzy, "FUZZY")
.InputIf(withScores, "WITHSCORES")
.InputIf(withPayloads, "WITHPAYLOADS")
.InputIf(max != null, "MAX", max), rt => rt.ThrowOrValue<string[]>());
public void FtSugLen(string key) => Call("FT.SUGLEN".InputKey(key), rt => rt.ThrowOrValue<long>());
public string[] FtTagVals(string index, string fieldName) => Call("FT.TAGVALS".Input(index, fieldName), rt => rt.ThrowOrValue<string[]>());
}
static partial class RedisResultThrowOrValueExtensions
{
public static Dictionary<string, Dictionary<string, double>> ThrowOrValueToFtSpellCheckResult(this RedisResult rt) =>
rt.ThrowOrValue((rawTerms, _) =>
{
var returnTerms = new Dictionary<string, Dictionary<string, double>>(rawTerms.Length);
foreach (var term in rawTerms)
{
var rawElements = term as object[];
string termValue = rawElements[1].ConvertTo<string>();
var list = rawElements[2] as object[];
var entries = new Dictionary<string, double>(list.Length);
foreach (var entry in list)
{
var entryElements = entry as object[];
string suggestion = entryElements[1].ConvertTo<string>();
double score = entryElements[0].ConvertTo<double>();
entries.Add(suggestion, score);
}
returnTerms.Add(termValue, entries);
}
return returnTerms;
});
public static object ThrowOrValueToFtCursorRead(this RedisResult rt) =>
rt.ThrowOrValue((a, _) =>
{
return a;
});
public static bool IsParameter(this Expression exp)
{
var test = new TestParameterExpressionVisitor();
test.Visit(exp);
return test.Result;
}
}
class ReplaceVisitor : ExpressionVisitor
{
private Expression _oldexp;
private Expression _newexp;
public Expression Modify(Expression find, Expression oldexp, Expression newexp)
{
this._oldexp = oldexp;
this._newexp = newexp;
return Visit(find);
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Expression == _oldexp)
return Expression.Property(_newexp, node.Member.Name);
if (node == _oldexp)
return _newexp;
return base.VisitMember(node);
}
}
class TestParameterExpressionVisitor : ExpressionVisitor
{
public bool Result { get; private set; }
protected override Expression VisitParameter(ParameterExpression node)
{
if (!Result) Result = true;
return node;
}
}
} |
2881099/FreeRedis | 3,045 | src/FreeRedis/RedisClient/Modules/CRC16.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
public FreeRedisClusterCRC16 ClusterCRC16 = new FreeRedisClusterCRC16();
}
public class FreeRedisClusterCRC16
{
private int[] LOOKUP_TABLE = new int[]
{
0, 4129, 8258, 12387, 16516, 20645, 24774, 28903, 33032, 37161, 41290, 45419, 49548, 53677, 57806, 61935,
4657, 528, 12915, 8786, 21173, 17044, 29431, 25302, 37689, 33560, 45947, 41818, 54205, 50076, 62463, 58334,
9314, 13379, 1056, 5121, 25830, 29895, 17572, 21637, 42346, 46411, 34088, 38153, 58862, 62927, 50604, 54669,
13907, 9842, 5649, 1584, 30423, 26358, 22165, 18100, 46939, 42874, 38681, 34616, 63455, 59390, 55197, 51132,
18628, 22757, 26758, 30887, 2112, 6241, 10242, 14371, 51660, 55789, 59790, 63919, 35144, 39273, 43274,
47403, 23285, 19156, 31415, 27286, 6769, 2640, 14899, 10770, 56317, 52188, 64447, 60318, 39801, 35672,
47931, 43802, 27814, 31879, 19684, 23749, 11298, 15363, 3168, 7233, 60846, 64911, 52716, 56781, 44330,
48395, 36200, 40265, 32407, 28342, 24277, 20212, 15891, 11826, 7761, 3696, 65439, 61374, 57309, 53244,
48923, 44858, 40793, 36728, 37256, 33193, 45514, 41451, 53516, 49453, 61774, 57711, 4224, 161, 12482, 8419,
20484, 16421, 28742, 24679, 33721, 37784, 41979, 46042, 49981, 54044, 58239, 62302, 689, 4752, 8947, 13010,
16949, 21012, 25207, 29270, 46570, 42443, 38312, 34185, 62830, 58703, 54572, 50445, 13538, 9411, 5280, 1153,
29798, 25671, 21540, 17413, 42971, 47098, 34713, 38840, 59231, 63358, 50973, 55100, 9939, 14066, 1681, 5808,
26199, 30326, 17941, 22068, 55628, 51565, 63758, 59695, 39368, 35305, 47498, 43435, 22596, 18533, 30726,
26663, 6336, 2273, 14466, 10403, 52093, 56156, 60223, 64286, 35833, 39896, 43963, 48026, 19061, 23124,
27191, 31254, 2801, 6864, 10931, 14994, 64814, 60687, 56684, 52557, 48554, 44427, 40424, 36297, 31782,
27655, 23652, 19525, 15522, 11395, 7392, 3265, 61215, 65342, 53085, 57212, 44955, 49082, 36825, 40952,
28183, 32310, 20053, 24180, 11923, 16050, 3793, 7920
};
public int GetCRC16(byte[] bytes, int s, int e)
{
int crc = 0;
for (int i = s; i < e; ++i)
{
crc = crc << 8 ^ LOOKUP_TABLE[(crc >> 8 ^ bytes[i] & 255) & 255];
}
return crc & '\uffff';
}
public int GetSlot(string key)
{
return RedisClient.ClusterAdapter.GetClusterSlot(key);
}
public int GetCRC16(byte[] bytes)
{
return GetCRC16(bytes, 0, bytes.Length);
}
public int GetCRC16(string key)
{
byte[] bytesKey = Encoding.UTF8.GetBytes(key);
return GetCRC16(bytesKey, 0, bytesKey.Length);
}
}
} |
2881099/FreeRedis | 4,677 | src/FreeRedis/RedisClient/Modules/DelayQueue.cs | using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
/// <summary>
/// 延时队列
/// </summary>
/// <param name="queueKey">延时队列Key</param>
/// <returns></returns>
public DelayQueue DelayQueue(string queueKey) => new DelayQueue(this, queueKey);
}
/// <summary>
/// 延时队列
/// </summary>
public class DelayQueue
{
private readonly RedisClient _redisClient = null;
private readonly string _queueKey;
public DelayQueue(RedisClient redisClient, string queueKey)
{
_redisClient = redisClient;
_queueKey = queueKey;
}
/// <summary>
/// 写入延时队列
/// </summary>
/// <param name="value">队列值:值不可重复</param>
/// <param name="delay">延迟执行时间</param>
/// <returns></returns>
public bool Enqueue(string value, TimeSpan delay)
{
var time = DateTime.UtcNow.Add(delay);
long timestamp = (time.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerMillisecond;
var res = _redisClient.ZAdd(_queueKey, timestamp, value);
return res > 0;
}
/// <summary>
/// 写入延时队列
/// </summary>
/// <param name="value">队列值:值不可重复</param>
/// <param name="delay">延迟执行时间</param>
/// <returns></returns>
public bool Enqueue(string value, DateTime delay)
{
var time = TimeZoneInfo.ConvertTimeToUtc(delay);
long timestamp = (time.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerMillisecond;
var res = _redisClient.ZAdd(_queueKey, timestamp, value);
return res > 0;
}
/// <summary>
/// 消费延时队列,多个消费端不会重复
/// </summary>
/// <param name="action">消费委托</param>
/// <param name="choke">轮询队列时长,默认400毫秒,值越小越准确</param>
public void Dequeue(Action<string> action, int choke = 400, CancellationToken? token = null)
{
Thread thread = new Thread(() =>
{
while (true)
{
try
{
if (token != null && token.Value.IsCancellationRequested)
break;
//阻塞节省CPU
Thread.Sleep(choke);
var res = InternalDequeue();
if (!string.IsNullOrWhiteSpace(res))
action.Invoke(res);
}
catch
{
// ignored
}
}
});
thread.Start();
}
#if isasync
/// <summary>
/// 消费延时队列,多个消费端不会重复
/// </summary>
/// <param name="action">消费委托</param>
/// <param name="choke">轮询队列时长,默认400毫秒,值越小越准确</param>
/// <param name="token"></param>
public Task DequeueAsync(Func<string, Task> action, int choke = 400, CancellationToken? token = null)
{
return Task.Factory.StartNew(async () =>
{
while (true)
{
try
{
if (token != null && token.Value.IsCancellationRequested)
break;
//阻塞节省CPU
await Task.Delay(choke);
var res = InternalDequeue();
if (!string.IsNullOrWhiteSpace(res))
await action.Invoke(res);
}
catch
{
// ignored
}
}
}, TaskCreationOptions.LongRunning);
}
#endif
//取队列任务
private string InternalDequeue()
{
long timestamp = (DateTime.UtcNow.Ticks - new DateTime(1970, 1, 1).Ticks) / TimeSpan.TicksPerMillisecond;
//lua脚本保持原子性
var script = @"
local zrange = redis.call('zrangebyscore',KEYS[1],0,ARGV[1],'LIMIT',0,1)
if next(zrange) ~= nil and #zrange > 0 then
local rmnum = redis.call('zrem',KEYS[1],unpack(zrange))
if(rmnum > 0) then
return zrange
end
else
return {}
end";
if (_redisClient.Eval(script, new[] { _queueKey }, timestamp) is object[] eval && eval.Any())
{
var item = eval[0].ToString() ?? string.Empty;
return item;
}
return default;
}
}
} |
2881099/FreeRedis | 4,408 | src/FreeRedis/RedisClient/Modules/BloomFilter.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string> BfReserveAsync(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false) => CallAsync("BF.RESERVE"
.InputKey(key)
.Input(errorRate, capacity)
.InputIf(expansion != 2, "EXPANSION", expansion)
.InputIf(nonScaling, "NONSCALING"), rt => rt.ThrowOrValue<string>());
public Task<bool> BfAddAsync(string key, string item) => CallAsync("BF.ADD".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public Task<bool[]> BfMAddAsync(string key, string[] items) => CallAsync("BF.MADD".InputKey(key, items), rt => rt.ThrowOrValue<bool[]>());
public Task<string> BfInsertAsync(string key, string[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false) => CallAsync("BF.INSERT"
.InputKey(key)
.InputIf(capacity != null, "CAPACITY", capacity)
.InputIf(!string.IsNullOrWhiteSpace(error), "ERROR", error)
.InputIf(expansion != 2, "EXPANSION", expansion)
.InputIf(noCreate, "NOCREATE")
.InputIf(nonScaling, "NONSCALING")
.Input("ITEMS", items), rt => rt.ThrowOrValue<string>());
public Task<bool> BfExistsAsync(string key, string item) => CallAsync("BF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public Task<bool[]> BfMExistsAsync(string key, string[] items) => CallAsync("BF.MEXISTS".InputKey(key, items), rt => rt.ThrowOrValue<bool[]>());
public Task<ScanResult<byte[]>> BfScanDumpAsync(string key, long iter) => CallAsync("BF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) =>
new ScanResult<byte[]>(a[0].ConvertTo<long>(), a[1].ConvertTo<byte[][]>())));
public Task<string> BfLoadChunkAsync(string key, long iter, byte[] data) => CallAsync("BF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue<string>());
public Task<Dictionary<string, string>> BfInfoAsync(string key) => CallAsync("BF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
#endregion
#endif
public string BfReserve(string key, decimal errorRate, long capacity, int expansion = 2, bool nonScaling = false) => Call("BF.RESERVE"
.InputKey(key)
.Input(errorRate, capacity)
.InputIf(expansion != 2, "EXPANSION", expansion)
.InputIf(nonScaling, "NONSCALING"), rt => rt.ThrowOrValue<string>());
public bool BfAdd(string key, string item) => Call("BF.ADD".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public bool[] BfMAdd(string key, string[] items) => Call("BF.MADD".InputKey(key, items), rt => rt.ThrowOrValue<bool[]>());
public string BfInsert(string key, string[] items, long? capacity = null, string error = null, int expansion = 2, bool noCreate = false, bool nonScaling = false) => Call("BF.INSERT"
.InputKey(key)
.InputIf(capacity != null, "CAPACITY", capacity)
.InputIf(!string.IsNullOrWhiteSpace(error), "ERROR", error)
.InputIf(expansion != 2, "EXPANSION", expansion)
.InputIf(noCreate, "NOCREATE")
.InputIf(nonScaling, "NONSCALING")
.Input("ITEMS", items), rt => rt.ThrowOrValue<string>());
public bool BfExists(string key, string item) => Call("BF.EXISTS".InputKey(key, item), rt => rt.ThrowOrValue<bool>());
public bool[] BfMExists(string key, string[] items) => Call("BF.MEXISTS".InputKey(key, items), rt => rt.ThrowOrValue<bool[]>());
public ScanResult<byte[]> BfScanDump(string key, long iter) => Call("BF.SCANDUMP".InputKey(key, iter), rt => rt.ThrowOrValue((a, _) =>
new ScanResult<byte[]>(a[0].ConvertTo<long>(), a[1].ConvertTo<byte[][]>())));
public string BfLoadChunk(string key, long iter, byte[] data) => Call("BF.LOADCHUNK".InputKey(key, iter).InputRaw(data), rt => rt.ThrowOrValue<string>());
public Dictionary<string, string> BfInfo(string key) => Call("BF.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
}
}
|
2881099/FreeRedis | 6,371 | src/FreeRedis/RedisClient/Modules/SubscribeList.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FreeRedis.Internal.ObjectPool;
namespace FreeRedis
{
partial class RedisClient
{
/// <summary>
/// 使用lpush + blpop订阅端(多端争抢模式),只有一端收到消息
/// </summary>
/// <param name="listKey">list key(不含prefix前辍)</param>
/// <param name="onMessage">接收消息委托</param>
/// <returns></returns>
public SubscribeListObject SubscribeList(string listKey, Action<string> onMessage) => SubscribeList(new[] { listKey }, (k, v) => onMessage(v), false);
/// <summary>
/// 使用lpush + blpop订阅端(多端争抢模式),只有一端收到消息
/// </summary>
/// <param name="listKeys">支持多个 key(不含prefix前辍)</param>
/// <param name="onMessage">接收消息委托,参数1:key;参数2:消息体</param>
/// <returns></returns>
public SubscribeListObject SubscribeList(string[] listKeys, Action<string, string> onMessage) => SubscribeList(listKeys, onMessage, false);
private SubscribeListObject SubscribeList(string[] listKeys, Action<string, string> onMessage, bool ignoreEmpty)
{
if (listKeys == null || listKeys.Any() == false) throw new ArgumentException("Parameter listkeys cannot be empty");
var listKeysStr = string.Join(", ", listKeys);
var isMultiKey = listKeys.Length > 1;
var subobj = new SubscribeListObject();
TestTrace.WriteLine($"Subscribing to list(listKey:{listKeysStr})", ConsoleColor.DarkGreen);
new Thread(() =>
{
while (subobj.IsUnsubscribed == false)
{
try
{
if (isMultiKey)
{
var msg = this.BLPop(listKeys, 5);
if (msg != null)
if (!ignoreEmpty || (ignoreEmpty && !string.IsNullOrEmpty(msg.value)))
onMessage?.Invoke(msg.key, msg.value);
}
else
{
var msg = this.BLPop(listKeys[0], 5);
if (!ignoreEmpty || (ignoreEmpty && !string.IsNullOrEmpty(msg)))
onMessage?.Invoke(listKeys[0], msg);
}
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
TestTrace.WriteLine($"List subscription error(listKey:{listKeysStr}): {ex.Message}", ConsoleColor.DarkRed);
Thread.CurrentThread.Join(3000);
}
}
}).Start();
AppDomain.CurrentDomain.ProcessExit += (s1, e1) =>
{
subobj.Dispose();
};
try
{
Console.CancelKeyPress += (s1, e1) =>
{
if (e1.Cancel) return;
subobj.Dispose();
};
}
catch { }
return subobj;
}
/// <summary>
/// 使用lpush + blpop订阅端(多端非争抢模式),都可以收到消息
/// </summary>
/// <param name="listKey">list key(不含prefix前辍)</param>
/// <param name="clientId">订阅端标识,若重复则争抢,若唯一必然收到消息</param>
/// <param name="onMessage">接收消息委托</param>
/// <returns></returns>
public SubscribeListBroadcastObject SubscribeListBroadcast(string listKey, string clientId, Action<string> onMessage)
{
this.HSetNx($"{listKey}_SubscribeListBroadcast", clientId, 1);
var subobj = new SubscribeListBroadcastObject
{
OnDispose = () =>
{
this.HDel($"{listKey}_SubscribeListBroadcast", clientId);
}
};
//订阅其他端转发的消息
subobj.SubscribeLists.Add(this.SubscribeList($"{listKey}_{clientId}", onMessage));
//订阅主消息,接收消息后分发
subobj.SubscribeLists.Add(this.SubscribeList(new[] { listKey }, (key, msg) =>
{
try
{
this.HSetNx($"{listKey}_SubscribeListBroadcast", clientId, 1);
if (msg == null) return;
var clients = this.HKeys($"{listKey}_SubscribeListBroadcast");
var pipe = this.StartPipe();
foreach (var c in clients)
if (string.Compare(clientId, c, true) != 0) //过滤本端分发
pipe.LPush($"{listKey}_{c}", msg);
pipe.EndPipe();
onMessage?.Invoke(msg);
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
TestTrace.WriteLine($"List subscription error(listKey:{listKey}): {ex.Message}", ConsoleColor.DarkRed);
}
}, true));
AppDomain.CurrentDomain.ProcessExit += (s1, e1) =>
{
subobj.Dispose();
};
try
{
Console.CancelKeyPress += (s1, e1) =>
{
if (e1.Cancel) return;
subobj.Dispose();
};
}
catch { }
return subobj;
}
}
}
namespace FreeRedis.Internal
{
public class SubscribeListObject : IDisposable
{
internal List<SubscribeListObject> OtherSubs = new List<SubscribeListObject>();
public bool IsUnsubscribed { get; set; }
public void Dispose()
{
this.IsUnsubscribed = true;
foreach (var sub in OtherSubs) sub.Dispose();
}
}
public class SubscribeListBroadcastObject : IDisposable
{
internal Action OnDispose;
internal List<SubscribeListObject> SubscribeLists = new List<SubscribeListObject>();
public void Dispose()
{
try { OnDispose?.Invoke(); } catch (ObjectDisposedException) { }
foreach (var sub in SubscribeLists) sub.Dispose();
}
}
} |
2881099/FreeRedis | 2,994 | src/FreeRedis/RedisClient/Modules/RedisBloomCountMinSketch.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string> CmsInitByDimAsync(string key, long width, long depth) => CallAsync("CMS.INITBYDIM".InputKey(key, width, depth), rt => rt.ThrowOrValue<string>());
public Task<string> CmsInitByProbAsync(string key, decimal error, decimal probability) => CallAsync("CMS.INITBYPROB".InputKey(key, error, probability), rt => rt.ThrowOrValue<string>());
public Task<long> CmsIncrByAsync(string key, string item, long increment) => CallAsync("CMS.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue(a => a.ConvertTo<long[]>().FirstOrDefault()));
public Task<long[]> CmsIncrByAsync(string key, Dictionary<string, long> itemIncrements) => CallAsync("CMS.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue<long[]>());
public Task<long[]> CmsQueryAsync(string key, string[] items) => CallAsync("CMS.QUERY".InputKey(key, items), rt => rt.ThrowOrValue<long[]>());
public Task<string> CmsMergeAsync(string dest, long numKeys, string[] src, long[] weights) => CallAsync("CMS.MERGE"
.InputKey(dest, numKeys)
.InputKey(src)
.InputIf(weights?.Any() == true, "WEIGHTS", weights), rt => rt.ThrowOrValue<string>());
public Task<Dictionary<string, string>> CmsInfoAsync(string key) => CallAsync("CMS.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
#endregion
#endif
public string CmsInitByDim(string key, long width, long depth) => Call("CMS.INITBYDIM".InputKey(key, width, depth), rt => rt.ThrowOrValue<string>());
public string CmsInitByProb(string key, decimal error, decimal probability) => Call("CMS.INITBYPROB".InputKey(key, error, probability), rt => rt.ThrowOrValue<string>());
public long CmsIncrBy(string key, string item, long increment) => Call("CMS.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue(a => a.ConvertTo<long[]>().FirstOrDefault()));
public long[] CmsIncrBy(string key, Dictionary<string, long> itemIncrements) => Call("CMS.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue<long[]>());
public long[] CmsQuery(string key, string[] items) => Call("CMS.QUERY".InputKey(key, items), rt => rt.ThrowOrValue<long[]>());
public string CmsMerge(string dest, long numKeys, string[] src, long[] weights) => Call("CMS.MERGE"
.InputKey(dest, numKeys)
.InputKey(src)
.InputIf(weights?.Any() == true, "WEIGHTS", weights), rt => rt.ThrowOrValue<string>());
public Dictionary<string, string> CmsInfo(string key) => Call("CMS.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
}
}
|
2881099/FreeRedis | 6,709 | src/FreeRedis/RedisClient/Modules/Lock.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace FreeRedis
{
partial class RedisClient
{
/// <summary>
/// 开启分布式锁,若超时返回null
/// </summary>
/// <param name="name">锁名称</param>
/// <param name="timeoutSeconds">超时(秒)</param>
/// <param name="autoDelay">自动延长锁超时时间,看门狗线程的超时时间为timeoutSeconds/2 , 在看门狗线程超时时间时自动延长锁的时间为timeoutSeconds。除非程序意外退出,否则永不超时。</param>
/// <returns></returns>
public LockController Lock(string name, int timeoutSeconds, bool autoDelay = true)
{
name = $"RedisClientLock:{name}";
var startTime = DateTime.Now;
while (DateTime.Now.Subtract(startTime).TotalSeconds < timeoutSeconds)
{
var value = Guid.NewGuid().ToString();
if (SetNx(name, value, timeoutSeconds) == true)
{
double refreshSeconds = (double)timeoutSeconds / 2.0;
return new LockController(this, name, value, timeoutSeconds, refreshSeconds, autoDelay, CancellationToken.None);
}
Thread.CurrentThread.Join(3);
}
return null;
}
/// <summary>
/// 开启分布式锁,若超时返回null
/// </summary>
/// <param name="name">锁名称</param>
/// <param name="timeoutSeconds">独占锁过期时间</param>
/// <param name="refrshTimeoutSeconds">每隔多久自动延长一次锁,时间要比 timeoutSeconds 小,否则没有意义</param>
/// <param name="waitTimeoutSeconds">等待锁释放超时时间,如果这个时间内获取不到锁,则 LockController 为 null</param>
/// <param name="autoDelay">自动延长锁超时时间,看门狗线程的超时时间为timeoutSeconds/2 , 在看门狗线程超时时间时自动延长锁的时间为timeoutSeconds。除非程序意外退出,否则永不超时。</param>
/// <param name="token">CancellationToken 自动取消锁</param>
/// <returns></returns>
public LockController Lock(string name, int timeoutSeconds, int refrshTimeoutSeconds, int waitTimeoutSeconds, bool autoDelay = true, CancellationToken token = default)
{
if (refrshTimeoutSeconds == 0) throw new ArgumentException(nameof(refrshTimeoutSeconds), "刷新间隔时间不能为0");
if (waitTimeoutSeconds == 0) waitTimeoutSeconds = refrshTimeoutSeconds;
name = $"RedisClientLock:{name}";
var startTime = DateTime.Now;
// 规定时间内等待锁释放
while (DateTime.Now.Subtract(startTime).TotalSeconds < waitTimeoutSeconds)
{
var value = Guid.NewGuid().ToString();
if (SetNx(name, value, timeoutSeconds) == true)
{
return new LockController(this, name, value, timeoutSeconds, refrshTimeoutSeconds, autoDelay, token);
}
if (token.IsCancellationRequested) return null;
Thread.CurrentThread.Join(millisecondsTimeout: 3);
}
return null;
}
public class LockController : IDisposable
{
RedisClient _client;
string _name;
string _value;
int _timeoutSeconds;
Timer _autoDelayTimer;
private CancellationTokenSource _handleLostTokenSource;
private readonly CancellationToken _token;
/// <summary>
/// 当刷新锁时间的看门狗线程失去与Redis连接时,导致无法刷新延长锁时间时,触发此HandelLostToken Cancel
/// </summary>
public CancellationToken? HandleLostToken { get; }
internal LockController(RedisClient rds, string name, string value, int timeoutSeconds, double refreshSeconds, bool autoDelay, CancellationToken token)
{
_client = rds;
_name = name;
_value = value;
_timeoutSeconds = timeoutSeconds;
_token = token;
if (autoDelay)
{
_handleLostTokenSource = new CancellationTokenSource();
HandleLostToken = _handleLostTokenSource.Token;
var refreshMilli = (int)(refreshSeconds * 1000);
var timeoutMilli = timeoutSeconds * 1000;
_autoDelayTimer = new Timer(state2 => Refresh(timeoutMilli), null, refreshMilli, refreshMilli);
}
}
/// <summary>
/// 延长锁时间,锁在占用期内操作时返回true,若因锁超时被其他使用者占用则返回false
/// </summary>
/// <param name="milliseconds">延长的毫秒数</param>
/// <returns>成功/失败</returns>
public bool Delay(int milliseconds)
{
var ret = _client.Eval(@"local gva = redis.call('GET', KEYS[1])
if gva == ARGV[1] then
local ttlva = redis.call('PTTL', KEYS[1])
redis.call('PEXPIRE', KEYS[1], ARGV[2] + ttlva)
return 1
end
return 0", new[] { _name }, _value, milliseconds)?.ToString() == "1";
if (ret == false) _autoDelayTimer?.Dispose(); //未知情况,关闭定时器
return ret;
}
/// <summary>
/// 刷新锁时间,把key的ttl重新设置为milliseconds,锁在占用期内操作时返回true,若因锁超时被其他使用者占用则返回false
/// </summary>
/// <param name="milliseconds">刷新的毫秒数</param>
/// <returns>成功/失败</returns>
public bool Refresh(int milliseconds)
{
if (_token.IsCancellationRequested)
{
_autoDelayTimer?.Dispose();
}
try
{
var ret = _client.Eval(@"local gva = redis.call('GET', KEYS[1])
if gva == ARGV[1] then
redis.call('PEXPIRE', KEYS[1], ARGV[2])
return 1
end
return 0", new[] { _name }, _value, milliseconds)?.ToString() == "1";
if (ret == false)
{
_handleLostTokenSource?.Cancel();
_autoDelayTimer?.Dispose(); //未知情况,关闭定时器
}
return ret;
}
catch
{
_handleLostTokenSource?.Cancel();
_autoDelayTimer?.Dispose(); //未知情况,关闭定时器
return false;//这里必须要吞掉异常,否则会导致整个程序崩溃,因为Timer的异常没有地方去处理
}
}
/// <summary>
/// 释放分布式锁
/// </summary>
/// <returns>成功/失败</returns>
public bool Unlock()
{
_handleLostTokenSource?.Dispose();
_autoDelayTimer?.Dispose();
return _client.Eval(@"local gva = redis.call('GET', KEYS[1])
if gva == ARGV[1] then
redis.call('DEL', KEYS[1])
return 1
end
return 0", new[] { _name }, _value)?.ToString() == "1";
}
public void Dispose() => this.Unlock();
}
}
}
|
2881099/FreeRedis | 4,655 | src/FreeRedis/RedisClient/Modules/SubscribeStream.cs | using FreeRedis.Internal;
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Text;
using FreeRedis.Internal.ObjectPool;
namespace FreeRedis
{
partial class RedisClient
{
public SubscribeStreamObject SubscribeStream(string streamKey, Action<Dictionary<string, string>> onMessage)
{
if (string.IsNullOrEmpty(streamKey)) throw new ArgumentException("Parameter streamKey cannot be empty");
var redis = this;
var subobj = new SubscribeStreamObject();
var groupName = "FreeRedis__group";
var consumerName = "FreeRedis__consumer";
void CreateGroupAndConsumer()
{
using (var loc1 = redis.StartPipe())
{
loc1.XGroupCreate(streamKey, groupName, "$", true);
loc1.XGroupCreateConsumer(streamKey, groupName, consumerName);
loc1.EndPipe();
}
}
if (redis.Exists(streamKey) == false) CreateGroupAndConsumer();
else
{
if (redis.Type(streamKey) != KeyType.stream) throw new ArgumentException($"'{streamKey}' type is not STREAM");
if (redis.XInfoGroups(streamKey).Any(a => a.name == groupName) == false) CreateGroupAndConsumer();
else if (redis.XInfoConsumers(streamKey, groupName).Any(a => a.name == consumerName) == false) redis.XGroupCreateConsumer(streamKey, groupName, consumerName);
}
TestTrace.WriteLine($"Subscribing to stream(streamKey:{streamKey})", ConsoleColor.DarkGreen);
new Thread(() =>
{
while (subobj.IsUnsubscribed == false)
{
try
{
//var result = redis.XReadGroup(groupName, consumerName, 5000, streamKey, ">");
var result = Call("XREADGROUP"
.Input("GROUP", groupName, consumerName)
.Input("COUNT", 1)
.Input("BLOCK", 5000)
.InputRaw("STREAMS")
.InputKey(streamKey)
.Input(">"), rt =>
{
if (rt.IsError)
{
if (
rt.SimpleError == $"UNBLOCKED the stream key no longer exists" ||
rt.SimpleError == $"NOGROUP No such key '{streamKey}' or consumer group '{groupName}' in XREADGROUP with GROUP option")
{
CreateGroupAndConsumer();
return null;
}
}
return rt.ThrowOrValueToXRead();
})?.FirstOrDefault()?.entries?.FirstOrDefault();
if (result != null)
{
onMessage?.Invoke(result.fieldValues?.MapToHash<string>(Encoding.UTF8));
redis.XAck(streamKey, groupName, result.id);
}
}
catch (ObjectDisposedException)
{
}
catch (Exception ex)
{
TestTrace.WriteLine($"Stream subscription error(streamKey:{streamKey}): {ex.Message}", ConsoleColor.DarkRed);
Thread.CurrentThread.Join(3000);
}
}
}).Start();
AppDomain.CurrentDomain.ProcessExit += (s1, e1) =>
{
subobj.Dispose();
};
try
{
Console.CancelKeyPress += (s1, e1) =>
{
if (e1.Cancel) return;
subobj.Dispose();
};
}
catch { }
return subobj;
}
}
}
namespace FreeRedis.Internal
{
public class SubscribeStreamObject : IDisposable
{
internal List<SubscribeStreamObject> OtherSubs = new List<SubscribeStreamObject>();
public bool IsUnsubscribed { get; set; }
public void Dispose()
{
this.IsUnsubscribed = true;
foreach (var sub in OtherSubs) sub.Dispose();
}
}
} |
2881099/FreeRedis | 3,014 | src/FreeRedis/RedisClient/Modules/RedisBloomTopKFilter.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string> TopkReserveAsync(string key, long topk, long width, long depth, decimal decay) => CallAsync("TOPK.RESERVE".InputKey(key).Input(topk, width, depth, decay), rt => rt.ThrowOrValue<string>());
public Task<string[]> TopkAddAsync(string key, string[] items) => CallAsync("TOPK.ADD".InputKey(key, items), rt => rt.ThrowOrValue<string[]>());
public Task<string> TopkIncrByAsync(string key, string item, long increment) => CallAsync("TOPK.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo<string>()));
public Task<string[]> TopkIncrByAsync(string key, Dictionary<string, long> itemIncrements) => CallAsync("TOPK.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue<string[]>());
public Task<bool[]> TopkQueryAsync(string key, string[] items) => CallAsync("TOPK.QUERY".InputKey(key, items), rt => rt.ThrowOrValue<bool[]>());
public Task<long[]> TopkCountAsync(string key, string[] items) => CallAsync("TOPK.COUNT".InputKey(key, items), rt => rt.ThrowOrValue<long[]>());
public Task<string[]> TopkListAsync(string key) => CallAsync("TOPK.LIST".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public Task<Dictionary<string, string>> TopkInfoAsync(string key) => CallAsync("TOPK.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
#endregion
#endif
public string TopkReserve(string key, long topk, long width, long depth, decimal decay) => Call("TOPK.RESERVE".InputKey(key).Input(topk, width, depth, decay), rt => rt.ThrowOrValue<string>());
public string[] TopkAdd(string key, string[] items) => Call("TOPK.ADD".InputKey(key, items), rt => rt.ThrowOrValue<string[]>());
public string TopkIncrBy(string key, string item, long increment) => Call("TOPK.INCRBY".InputKey(key, item, increment), rt => rt.ThrowOrValue((a, _) => a.FirstOrDefault().ConvertTo<string>()));
public string[] TopkIncrBy(string key, Dictionary<string, long> itemIncrements) => Call("TOPK.INCRBY".InputKey(key).InputKv(itemIncrements, false, SerializeRedisValue), rt => rt.ThrowOrValue<string[]>());
public bool[] TopkQuery(string key, string[] items) => Call("TOPK.QUERY".InputKey(key, items), rt => rt.ThrowOrValue<bool[]>());
public long[] TopkCount(string key, string[] items) => Call("TOPK.COUNT".InputKey(key, items), rt => rt.ThrowOrValue<long[]>());
public string[] TopkList(string key) => Call("TOPK.LIST".InputKey(key), rt => rt.ThrowOrValue<string[]>());
public Dictionary<string, string> TopkInfo(string key) => Call("TOPK.INFO".InputKey(key), rt => rt.ThrowOrValue((a, _) => a.MapToHash<string>(rt.Encoding)));
}
}
|
2881099/FreeRedis | 12,814 | src/FreeRedis/RedisClient/Modules/RedisJson.cs | using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreeRedis
{
partial class RedisClient
{
#if isasync
#region async (copy from sync)
public Task<string> JsonGetAsync(string key, string indent = default, string newline = default, string space = default, params string[] paths)
=> CallAsync("JSON.GET".InputKey(key)
.InputIf(indent != null, "INDENT", indent)
.InputIf(newline != null, "NEWLINE", newline)
.InputIf(space != null, "SPACE", space)
.Input(paths), rt => rt.ThrowOrValue<string>());
public Task<string[]> JsonMGetAsync(string[] keys, string path = "$") => CallAsync("JSON.MGET".InputKey(keys).Input(path), rt => rt.ThrowOrValue<string[]>());
async public Task JsonSetAsync(string key, string value, string path = "$", bool nx = false, bool xx = false)
=> await CallAsync("JSON.SET".InputKey(key)
.Input(path)
.InputRaw(value)
.InputIf(nx, "NX")
.InputIf(xx, "XX"), rt => rt.ThrowOrValue<string>() == "OK");
async public Task JsonMSetAsync(string[] keys, string[] values, string[] paths)
{
if (keys?.Any() != true) throw new ArgumentException($"{nameof(keys)} not is null or empry");
if (values?.Any() != true) throw new ArgumentException($"{nameof(values)} not is null or empry");
if (paths?.Any() != true) throw new ArgumentException($"{nameof(paths)} not is null or empry");
if (keys.Length != values.Length || keys.Length != paths.Length) throw new ArgumentException($"{nameof(keys)}, {nameof(values)}, {nameof(paths)} Length must equals");
var cmd = new CommandPacket("JSON.MSET");
for (var a = 0; a < keys.Length; a++)
cmd = cmd.InputKey(keys[a]).Input(paths[a], values[a]);
await CallAsync(cmd, rt => rt.ThrowOrValue<string>() == "OK");
}
async public Task JsonMergeAsync(string key, string path, string value) => await CallAsync("JSON.MERGE".InputKey(key).Input(path, value), rt => rt.ThrowOrValue<string>() == "OK");
public Task<long> JsonDelAsync(string key, string path = "$") => CallAsync("JSON.DEL".InputKey(key).Input(path), rt => rt.ThrowOrValue<long>());
public Task<long[]> JsonArrInsertAsync(string key, string path, long index = 0, params object[] values) => CallAsync("JSON.ARRINSERT".InputKey(key).Input(path, index).Input(values.Select(SerializeRedisValue).ToArray()), rt => rt.ThrowOrValue<long[]>());
public Task<long[]> JsonArrAppendAsync(string key, string path, params object[] values) => CallAsync("JSON.ARRAPPEND".InputKey(key).Input(path).Input(values.Select(SerializeRedisValue).ToArray()), rt => rt.ThrowOrValue<long[]>());
public Task<long[]> JsonArrIndexAsync<T>(string key, string path, T value) where T : struct => CallAsync("JSON.ARRINDEX".InputKey(key).Input(path).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long[]>());
public Task<long[]> JsonArrLenAsync(string key, string path) => CallAsync("JSON.ARRLEN".InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
async public Task<object[]> JsonArrPopAsync(string key, string path, int index = -1) => await HReadArrayAsync<object>("JSON.ARRPOP".InputKey(key).Input(path).InputIf(index != -1, index));
public Task<long[]> JsonArrTrimAsync(string key, string path, int start, int stop) => CallAsync("JSON.ARRTRIM".InputKey(key).Input(path).Input(start, stop), rt => rt.ThrowOrValue<long[]>());
public Task<long> JsonClearAsync(string key, string path = "$") => CallAsync("JSON.CLEAR".InputKey(key).Input(path), rt => rt.ThrowOrValue<long>());
public Task<long[]> JsonDebugMemoryAsync(string key, string path = "$") => CallAsync("JSON.DEBUG".SubCommand("MEMORY").InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public Task<long> JsonForgetAsync(string key, string path = "$") => CallAsync("JSON.FORGET".InputKey(key).Input(path), rt => rt.ThrowOrValue<long>());
public Task<string> JsonNumIncrByAsync(string key, string path, double value) => CallAsync("JSON.NUMINCRBY".InputKey(key).Input(path).Input(value), rt => rt.ThrowOrValue<string>());
public Task<string> JsonNumMultByAsync(string key, string path, double value) => CallAsync("JSON.NUMMULTBY".InputKey(key).Input(path).Input(value), rt => rt.ThrowOrValue<string>());
public Task<string[][]> JsonObjKeysAsync(string key, string path = "$") => CallAsync("JSON.OBJKEYS".InputKey(key).Input(path), rt => rt.ThrowOrValue<string[][]>());
public Task<long[]> JsonObjLenAsync(string key, string path = "$") => CallAsync("JSON.OBJLEN".InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public Task<object[][]> JsonRespAsync(string key, string path = "$") => CallAsync("JSON.RESP".InputKey(key).Input(path), rt => rt.ThrowOrValue<object[][]>());
public Task<long[]> JsonStrAppendAsync(string key, string value, string path = "$") => CallAsync("JSON.STRAPPEND".InputKey(key).Input(path).Input(SerializeString(value)), rt => rt.ThrowOrValue<long[]>());
public Task<long[]> JsonStrLenAsync(string key, string path = "$") => CallAsync("JSON.STRLEN".InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public Task<bool[]> JsonToggleAsync(string key, string path = "$") => CallAsync("JSON.TOGGLE".InputKey(key).Input(path), rt => rt.ThrowOrValue<bool[]>());
public Task<string[]> JsonTypeAsync(string key, string path = "$") => CallAsync("JSON.TYPE".InputKey(key).Input(path), rt => rt.ThrowOrValue<string[]>());
#endregion
#endif
public string JsonGet(string key, string indent = default, string newline = default, string space = default, params string[] paths)
=> Call("JSON.GET".InputKey(key)
.InputIf(indent != null, "INDENT", indent)
.InputIf(newline != null, "NEWLINE", newline)
.InputIf(space != null, "SPACE", space)
.Input(paths), rt => rt.ThrowOrValue<string>());
public string[] JsonMGet(string[] keys, string path = "$") => Call("JSON.MGET".InputKey(keys).Input(path), rt => rt.ThrowOrValue<string[]>());
public void JsonSet(string key, string value, string path = "$", bool nx = false, bool xx = false)
=> Call("JSON.SET".InputKey(key).Input(path)
.InputRaw(value)
.InputIf(nx, "NX")
.InputIf(xx, "XX"), rt => rt.ThrowOrValue<string>() == "OK");
public void JsonMSet(string[] keys, string[] values, string[] paths)
{
if (keys?.Any() != true) throw new ArgumentException($"{nameof(keys)} not is null or empry");
if (values?.Any() != true) throw new ArgumentException($"{nameof(values)} not is null or empry");
if (paths?.Any() != true) throw new ArgumentException($"{nameof(paths)} not is null or empry");
if (keys.Length != values.Length || keys.Length != paths.Length) throw new ArgumentException($"{nameof(keys)}, {nameof(values)}, {nameof(paths)} Length must equals");
var cmd = new CommandPacket("JSON.MSET");
for (var a = 0; a < keys.Length; a++)
cmd = cmd.InputKey(keys[a]).Input(paths[a], values[a]);
Call(cmd, rt => rt.ThrowOrValue<string>() == "OK");
}
public void JsonMerge(string key, string path, string value) => Call("JSON.MERGE".InputKey(key).Input(path, value), rt => rt.ThrowOrValue<string>() == "OK");
public long JsonDel(string key, string path = "$") => Call("JSON.DEL".InputKey(key).Input(path), rt => rt.ThrowOrValue<long>());
public long[] JsonArrInsert(string key, string path, long index = 0, params object[] values) => Call("JSON.ARRINSERT".InputKey(key).Input(path, index).Input(values.Select(SerializeRedisValue).ToArray()), rt => rt.ThrowOrValue<long[]>());
public long[] JsonArrAppend(string key, string path, params object[] values) => Call("JSON.ARRAPPEND".InputKey(key).Input(path).Input(values.Select(SerializeRedisValue).ToArray()), rt => rt.ThrowOrValue<long[]>());
public long[] JsonArrIndex<T>(string key, string path, T value) where T : struct => Call("JSON.ARRINDEX".InputKey(key).Input(path).InputRaw(SerializeRedisValue(value)), rt => rt.ThrowOrValue<long[]>());
public long[] JsonArrLen(string key, string path) => Call("JSON.ARRLEN".InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public object[] JsonArrPop(string key, string path, int index = -1) => HReadArray<object>("JSON.ARRPOP".InputKey(key).Input(path).InputIf(index != -1, index));
public long[] JsonArrTrim(string key, string path, int start, int stop) => Call("JSON.ARRTRIM".InputKey(key).Input(path).Input(start, stop), rt => rt.ThrowOrValue<long[]>());
public long JsonClear(string key, string path = "$") => Call("JSON.CLEAR".InputKey(key).Input(path), rt => rt.ThrowOrValue<long>());
public long[] JsonDebugMemory(string key, string path = "$") => Call("JSON.DEBUG".SubCommand("MEMORY").InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public long JsonForget(string key, string path = "$") => Call("JSON.FORGET".InputKey(key).Input(path), rt => rt.ThrowOrValue<long>());
public string JsonNumIncrBy(string key, string path, double value) => Call("JSON.NUMINCRBY".InputKey(key).Input(path).Input(value), rt => rt.ThrowOrValue<string>());
public string JsonNumMultBy(string key, string path, double value) => Call("JSON.NUMMULTBY".InputKey(key).Input(path).Input(value), rt => rt.ThrowOrValue<string>());
public string[][] JsonObjKeys(string key, string path = "$") => Call("JSON.OBJKEYS".InputKey(key).Input(path), rt => rt.ThrowOrValue<string[][]>());
public long[] JsonObjLen(string key, string path = "$") => Call("JSON.OBJLEN".InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public object[][] JsonResp(string key, string path = "$") => Call("JSON.RESP".InputKey(key).Input(path), rt => rt.ThrowOrValue<object[][]>());
public long[] JsonStrAppend(string key, string value, string path = "$") => Call("JSON.STRAPPEND".InputKey(key).Input(path).Input(SerializeString(value)), rt => rt.ThrowOrValue<long[]>());
public long[] JsonStrLen(string key, string path = "$") => Call("JSON.STRLEN".InputKey(key).Input(path), rt => rt.ThrowOrValue<long[]>());
public bool[] JsonToggle(string key, string path = "$") => Call("JSON.TOGGLE".InputKey(key).Input(path), rt => rt.ThrowOrValue<bool[]>());
public string[] JsonType(string key, string path = "$") => Call("JSON.TYPE".InputKey(key).Input(path), rt => rt.ThrowOrValue<string[]>());
private static string SerializeString(string input)
{
if (input == null)
return "null";
var sb = new StringBuilder();
sb.Append('"');
foreach (char c in input)
{
switch (c)
{
case '"':
sb.Append("\\\"");
break;
case '\\':
sb.Append("\\\\");
break;
case '/':
// 正斜杠可以选择性转义,这里为了安全起见进行转义
sb.Append("\\/");
break;
case '\b':
sb.Append("\\b");
break;
case '\f':
sb.Append("\\f");
break;
case '\n':
sb.Append("\\n");
break;
case '\r':
sb.Append("\\r");
break;
case '\t':
sb.Append("\\t");
break;
default:
// 根据JSON标准,控制字符(0x00-0x1F)必须转义
if (c < 32)
{
sb.Append("\\u").Append(((int)c).ToString("X4"));
}
// 对于高位Unicode字符,也进行转义以确保兼容性
else if (c > 127)
{
sb.Append("\\u").Append(((int)c).ToString("X4"));
}
else
{
sb.Append(c);
}
break;
}
}
sb.Append('"');
return sb.ToString();
}
}
} |
2881099/FreeRedis | 58,610 | src/FreeRedis/RedisClient/Modules/RediSearchBuilder/FtDocumentRepository.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace FreeRedis.RediSearch
{
public class FtDocumentRepository<T>
{
static ConcurrentDictionary<Type, DocumentSchemaInfo> _schemaFactories = new ConcurrentDictionary<Type, DocumentSchemaInfo>();
internal protected class DocumentSchemaInfo
{
public Type DocumentType { get; set; }
public FtDocumentAttribute DocumentAttribute { get; set; }
public PropertyInfo KeyProperty { get; set; }
public List<DocumentSchemaFieldInfo> Fields { get; set; } = new List<DocumentSchemaFieldInfo>();
public Dictionary<string, DocumentSchemaFieldInfo> FieldsMap { get; set; } = new Dictionary<string, DocumentSchemaFieldInfo>();
public Dictionary<string, DocumentSchemaFieldInfo> FieldsMapRead { get; set; } = new Dictionary<string, DocumentSchemaFieldInfo>();
}
internal protected class DocumentSchemaFieldInfo
{
public DocumentSchemaInfo DocumentSchema { get; set; }
public PropertyInfo Property { get; set; }
public FtFieldAttribute FieldAttribute { get; set; }
public FieldType FieldType { get; set; }
}
internal protected RedisClient _client;
internal protected DocumentSchemaInfo _schema;
public FtDocumentRepository(RedisClient client)
{
var type = typeof(T);
_client = client;
_schema = _schemaFactories.GetOrAdd(type, t =>
{
var fieldProprties = type.GetProperties().Select(p => new
{
attribute = p.GetCustomAttributes(false).FirstOrDefault(a => a is FtFieldAttribute) as FtFieldAttribute,
property = p
}).Where(a => a.attribute != null);
var schema = new DocumentSchemaInfo
{
DocumentType = type,
};
foreach (var fieldProperty in fieldProprties)
{
var field = new DocumentSchemaFieldInfo
{
DocumentSchema = schema,
Property = fieldProperty.property,
FieldAttribute = fieldProperty.attribute,
FieldType = GetMapFieldType(fieldProperty.property, fieldProperty.attribute)
};
schema.Fields.Add(field);
schema.FieldsMap[field.Property.Name] = field;
schema.FieldsMapRead[field.FieldAttribute.Name] = field;
}
if (schema.Fields.Any() == false) throw new Exception($"Not found: [FtFieldAttribute]");
schema.DocumentAttribute = type.GetCustomAttributes(false).FirstOrDefault(a => a is FtDocumentAttribute) as FtDocumentAttribute;
schema.KeyProperty = type.GetProperties().FirstOrDefault(p => p.GetCustomAttributes(false).FirstOrDefault(a => a is FtKeyAttribute) != null);
return schema;
});
}
protected FieldType GetMapFieldType(PropertyInfo property, FtFieldAttribute ftattr)
{
//Text, Tag, Numeric, Geo, Vector, GeoShape
if (ftattr is FtTextFieldAttribute) return FieldType.Text;
if (ftattr is FtTagFieldAttribute) return FieldType.Tag;
if (ftattr is FtNumericFieldAttribute) return FieldType.Numeric;
if (ftattr is FtGeoFieldAttribute) return FieldType.Geo;
if (ftattr is FtGeoShapeFieldAttribute) return FieldType.GeoShape;
return FieldType.Text;
}
CreateBuilder GetCreateBuilder()
{
var attr = _schema.DocumentAttribute;
var createBuilder = _client.FtCreate(attr.Name);
// 组合全局前缀和文档前缀
var finalPrefix = _client.ConnectionString.Prefix + attr.Prefix;
if (!string.IsNullOrWhiteSpace(finalPrefix))
createBuilder.Prefix(finalPrefix);
if (!string.IsNullOrWhiteSpace(attr.Filter)) createBuilder.Prefix(attr.Filter);
if (!string.IsNullOrWhiteSpace(attr.Language)) createBuilder.Language(attr.Language);
foreach (var field in _schema.Fields)
{
switch (field.FieldType)
{
case FieldType.Text:
{
var ftattr = field.FieldAttribute as FtTextFieldAttribute;
createBuilder.AddTextField(ftattr.Name, new TextFieldOptions
{
Alias = ftattr.Alias,
EmptyIndex = ftattr.EmptyIndex,
MissingIndex = ftattr.MissingIndex,
NoIndex = ftattr.NoIndex,
NoStem = ftattr.NoStem,
Phonetic = ftattr.Phonetic,
Sortable = ftattr.Sortable,
Unf = ftattr.Unf,
Weight = ftattr.Weight,
WithSuffixTrie = ftattr.WithSuffixTrie,
});
}
break;
case FieldType.Tag:
{
var ftattr = field.FieldAttribute as FtTagFieldAttribute;
createBuilder.AddTagField(ftattr.Name, new TagFieldOptions
{
Alias = ftattr.Alias,
CaseSensitive = ftattr.CaseSensitive,
EmptyIndex = ftattr.EmptyIndex,
MissingIndex = ftattr.MissingIndex,
NoIndex = ftattr.NoIndex,
Separator = ftattr.Separator,
Sortable = ftattr.Sortable,
Unf = ftattr.Unf,
WithSuffixTrie = ftattr.WithSuffixTrie,
});
}
break;
case FieldType.Numeric:
{
var ftattr = field.FieldAttribute as FtNumericFieldAttribute;
createBuilder.AddNumericField(ftattr.Name, new NumbericFieldOptions
{
Alias = ftattr.Alias,
MissingIndex = ftattr.MissingIndex,
NoIndex = ftattr.NoIndex,
Sortable = ftattr.Sortable,
});
}
break;
case FieldType.Geo:
{
var ftattr = field.FieldAttribute as FtGeoFieldAttribute;
createBuilder.AddGeoField(ftattr.Name, new GeoFieldOptions
{
Alias = ftattr.Alias,
MissingIndex = ftattr.MissingIndex,
NoIndex = ftattr.NoIndex,
Sortable = ftattr.Sortable,
});
}
break;
case FieldType.GeoShape:
{
var ftattr = field.FieldAttribute as FtGeoShapeFieldAttribute;
createBuilder.AddGeoShapeField(ftattr.Name, new GeoShapeFieldOptions
{
Alias = ftattr.Alias,
System = ftattr.System,
MissingIndex = ftattr.MissingIndex
});
}
break;
}
}
return createBuilder;
}
public void DropIndex(bool dd = false) => _client.FtDropIndex(_schema.DocumentAttribute.Name, dd);
public void CreateIndex() => GetCreateBuilder().Execute();
void Save(T doc, RedisClient.PipelineHook pipe)
{
var key = $"{_schema.DocumentAttribute.Prefix}{_schema.KeyProperty.GetValue(doc, null)}";
var opts = _schema.Fields.Where((a, b) => b > 0).Select((a, b) => new object[]
{
a.FieldAttribute.FieldName,
toRedisValue(a)
}).SelectMany(a => a).ToArray();
var field = _schema.Fields[0].FieldAttribute.FieldName;
var value = _schema.Fields[0].Property.GetValue(doc, null);
if (pipe != null) pipe.HMSet(key, field, value, opts);
else _client.HMSet(key, field, value, opts);
object toRedisValue(DocumentSchemaFieldInfo dsf)
{
var val = dsf.Property.GetValue(doc, null);
if (dsf.FieldType == FieldType.Tag)
{
if (dsf.Property.PropertyType.IsArrayOrList())
val = string.Join((dsf.FieldAttribute as FtTagFieldAttribute).Separator ?? ",", typeof(string[]).FromObject(val) as string[]);
}
return val;
}
}
public void Save(T doc) => Save(doc, null);
public void Save(T[] docs) => Save(docs as IEnumerable<T>);
public void Save(IEnumerable<T> docs)
{
if (docs == null) return;
using (var pipe = _client.StartPipe())
{
foreach (var doc in docs)
Save(doc, pipe);
pipe.EndPipe();
}
}
public long Delete(params long[] id)
{
if (id == null || id.Length == 0) return 0;
return _client.Del(id.Select(a => $"{_schema.DocumentAttribute.Prefix}{a}").ToArray());
}
public long Delete(params string[] id)
{
if (id == null || id.Length == 0) return 0;
return _client.Del(id.Select(a => $"{_schema.DocumentAttribute.Prefix}{a}").ToArray());
}
#if isasync
public Task DropIndexAsync(bool dd = false) => _client.FtDropIndexAsync(_schema.DocumentAttribute.Name, dd);
public Task CreateIndexAsync() => GetCreateBuilder().ExecuteAsync();
async Task SaveAsync(T doc, RedisClient.PipelineHook pipe)
{
var key = $"{_schema.DocumentAttribute.Prefix}{_schema.KeyProperty.GetValue(doc, null)}";
var opts = _schema.Fields.Where((a, b) => b > 0).Select((a, b) => new object[]
{
a.FieldAttribute.FieldName,
toRedisValue(a)
}).SelectMany(a => a).ToArray();
var field = _schema.Fields[0].FieldAttribute.FieldName;
var value = _schema.Fields[0].Property.GetValue(doc, null);
if (pipe != null) pipe.HMSet(key, field, value, opts);
else await _client.HMSetAsync(key, field, value, opts);
object toRedisValue(DocumentSchemaFieldInfo dsf)
{
var val = dsf.Property.GetValue(doc, null);
if (dsf.FieldType == FieldType.Tag)
{
if (dsf.Property.PropertyType.IsArrayOrList())
val = string.Join((dsf.FieldAttribute as FtTagFieldAttribute).Separator ?? ",", typeof(string[]).FromObject(val) as string[]);
}
return val;
}
}
public Task SaveAsync(T doc) => SaveAsync(doc, null);
public Task SaveAsync(T[] docs) => SaveAsync(docs as IEnumerable<T>);
async public Task SaveAsync(IEnumerable<T> docs)
{
if (docs == null) return;
using (var pipe = _client.StartPipe())
{
foreach (var doc in docs)
await SaveAsync(doc, pipe);
pipe.EndPipe();
}
}
async public Task<long> DeleteAsync(params long[] id)
{
if (id == null || id.Length == 0) return 0;
return await _client.DelAsync(id.Select(a => $"{_schema.DocumentAttribute.Prefix}{a}").ToArray());
}
async public Task<long> DeleteAsync(params string[] id)
{
if (id == null || id.Length == 0) return 0;
return await _client.DelAsync(id.Select(a => $"{_schema.DocumentAttribute.Prefix}{a}").ToArray());
}
#endif
public FtDocumentRepositorySearchBuilder<T> Search(Expression<Func<T, bool>> query) => Search(ParseQueryExpression(query.Body, null));
public FtDocumentRepositorySearchBuilder<T> Search(string query = "*")
{
if (string.IsNullOrEmpty(query)) query = "*";
var q = _client.FtSearch(_schema.DocumentAttribute.Name, query);
if (!string.IsNullOrEmpty(_schema.DocumentAttribute.Language)) q.Language(_schema.DocumentAttribute.Language);
return new FtDocumentRepositorySearchBuilder<T>(this, _schema.DocumentAttribute.Name, query);
}
internal protected int ToTimestamp(DateTime dt) => (int)dt.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
internal protected List<KeyValuePair<string, string>> ParseSelectorExpression(Expression selector, bool isQuoteFieldName = false)
{
var fieldValues = new List<KeyValuePair<string, string>>();
if (selector is LambdaExpression lambdaExp) selector = lambdaExp.Body;
if (selector is UnaryExpression unaryExp) selector = unaryExp.Operand;
switch (selector.NodeType)
{
case ExpressionType.MemberAccess:
{
var memExp = selector as MemberExpression;
var left = memExp.Member.Name;
var right = ParseQueryExpression(memExp, new ParseQueryExpressionOptions { IsQuoteFieldName = isQuoteFieldName });
fieldValues.Add(new KeyValuePair<string, string>(left, right));
}
break;
case ExpressionType.New:
{
var newExp = selector as NewExpression;
for (var a = 0; a < newExp?.Members?.Count; a++)
{
var left = newExp.Members[a].Name;
var right = ParseQueryExpression(newExp.Arguments[a], new ParseQueryExpressionOptions { IsQuoteFieldName = isQuoteFieldName });
fieldValues.Add(new KeyValuePair<string, string>(left, right));
}
}
break;
case ExpressionType.MemberInit:
{
var initExp = selector as MemberInitExpression;
for (var a = 0; a < initExp?.Bindings.Count; a++)
{
var initAssignExp = (initExp.Bindings[a] as MemberAssignment);
if (initAssignExp == null) continue;
var left = initAssignExp.Member.Name;
var right = ParseQueryExpression(initAssignExp.Expression, new ParseQueryExpressionOptions { IsQuoteFieldName = isQuoteFieldName });
fieldValues.Add(new KeyValuePair<string, string>(left, right));
}
}
break;
}
return fieldValues;
}
internal protected class ParseQueryExpressionOptions
{
public bool IsQuoteFieldName { get; set; } = true;
public Func<MemberExpression, string> DiyParse { get; set; }
}
internal protected string ParseQueryExpression(Expression exp, ParseQueryExpressionOptions options)
{
if (options == null) options = new ParseQueryExpressionOptions();
string parseExp(Expression thenExp) => ParseQueryExpression(thenExp, options);
string toFt(object obj) => string.Format(CultureInfo.InvariantCulture, "{0}", toFtObject(obj));
object toFtObject(object param)
{
if (param == null) return "NULL";
if (param is bool || param is bool?)
return (bool)param ? 1 : 0;
else if (param is string str)
return string.Concat("'", str.Replace("\\", "\\\\").Replace("'", "\\'"), "'");
else if (param is char chr)
return string.Concat("'", chr.ToString().Replace("\\", "\\\\").Replace("'", "\\'").Replace('\0', ' '), "'");
else if (param is Enum enm)
return string.Concat("'", enm.ToString().Replace("\\", "\\\\").Replace("'", "\\'").Replace(", ", ","), "'");
else if (decimal.TryParse(string.Concat(param), out var trydec))
return param;
else if (param is DateTime || param is DateTime?)
return ToTimestamp((DateTime)param);
return string.Concat("\"", param.ToString().Replace("\\", "\\\\").Replace("'", "\\'"), "'");
}
string toFtTagString(string expResultStr)
{
if (expResultStr == null) return "";
if (expResultStr.StartsWith("'") && expResultStr.EndsWith("'"))
return expResultStr.Substring(1, expResultStr.Length - 2)
.Replace("\\'", "'").Replace("\\\\", "\\");
return expResultStr;
}
if (exp == null) return "";
switch (exp.NodeType)
{
case ExpressionType.Not:
var notExp = (exp as UnaryExpression)?.Operand;
return $"-({parseExp(notExp)})";
case ExpressionType.Quote: return parseExp((exp as UnaryExpression)?.Operand);
case ExpressionType.Lambda: return parseExp((exp as LambdaExpression)?.Body);
case ExpressionType.Invoke:
var invokeExp = exp as InvocationExpression;
var invokeReplaceExp = invokeExp.Expression;
var invokeLambdaExp = invokeReplaceExp as LambdaExpression;
if (invokeLambdaExp == null) return toFt(Expression.Lambda(exp).Compile().DynamicInvoke());
var invokeReplaceVistor = new ReplaceVisitor();
var len = Math.Min(invokeExp.Arguments.Count, invokeLambdaExp.Parameters.Count);
for (var a = 0; a < len; a++)
invokeReplaceExp = invokeReplaceVistor.Modify(invokeReplaceExp, invokeLambdaExp.Parameters[a], invokeExp.Arguments[a]);
return parseExp(invokeReplaceExp);
case ExpressionType.TypeAs:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
var expOperand = (exp as UnaryExpression)?.Operand;
if (expOperand.Type.NullableTypeOrThis().IsEnum && exp.IsParameter() == false)
return toFt(Expression.Lambda(exp).Compile().DynamicInvoke());
return parseExp(expOperand);
case ExpressionType.Negate:
case ExpressionType.NegateChecked: return $"-({parseExp((exp as UnaryExpression)?.Operand)})";
case ExpressionType.Constant: return toFt((exp as ConstantExpression)?.Value);
case ExpressionType.Conditional:
var condExp = exp as ConditionalExpression;
if (condExp.Test.IsParameter())
return "";
if ((bool)Expression.Lambda(condExp.Test).Compile().DynamicInvoke())
return parseExp(condExp.IfTrue);
else
return parseExp(condExp.IfFalse);
case ExpressionType.MemberAccess:
var memberExp = exp as MemberExpression;
var memberType = memberExp.Expression?.Type ?? memberExp.Type;
var memberParseResult = "";
switch (memberType.FullName)
{
case "System.String": memberParseResult = ParseMemberAccessString(); break;
case "System.DateTime": memberParseResult = ParseMemberAccessDateTime(); break;
}
if (string.IsNullOrEmpty(memberParseResult) == false) return memberParseResult;
if (memberExp.IsParameter() == false) return toFt(Expression.Lambda(exp).Compile().DynamicInvoke());
if (memberExp.Expression.NodeType == ExpressionType.Parameter)
{
if (_schema.KeyProperty.Name == memberExp.Member.Name)
return options.IsQuoteFieldName ? $"@__key" : "__key";
if (_schema.FieldsMap.TryGetValue(memberExp.Member.Name, out var field))
return options.IsQuoteFieldName ? $"@{field.FieldAttribute.FieldName}" : field.FieldAttribute.FieldName;
}
else
{
return options?.DiyParse(memberExp);
}
break;
string ParseMemberAccessString()
{
if (memberExp.Expression != null)
{
var left = parseExp(memberExp.Expression);
switch (memberExp.Member.Name)
{
case "Length": return $"strlen({left})";
}
}
return null;
}
string ParseMemberAccessDateTime()
{
if (memberExp.Expression == null)
{
switch (memberExp.Member.Name)
{
case "Now": return ToTimestamp(DateTime.Now).ToString();
case "UtcNow": return ToTimestamp(DateTime.UtcNow).ToString();
case "Today": return ToTimestamp(DateTime.Today).ToString();
case "MinValue": return "0";
case "MaxValue": return ToTimestamp(new DateTime(2050, 1, 1)).ToString();
}
return null;
}
var left = parseExp(memberExp.Expression);
switch (memberExp.Member.Name)
{
case "Date": return $"timefmt({left},'%Y-%m-%d')";
case "TimeOfDay": return $"timefmt({left},'%H:%M:%S')";
case "DayOfWeek": return $"dayofweek({left})";
case "Day": return $"dayofmonth({left})";
case "DayOfYear": return $"dayofyear({left})+1";
case "Month": return $"month({left})";
case "Year": return $"year({left})";
case "Hour": return $"hour({left})";
case "Minute": return $"minute({left})";
case "Second": return $"timefmt({left},'%S')";
}
return null;
}
case ExpressionType.Call:
var callExp = exp as MethodCallExpression;
var callType = callExp.Object?.Type ?? callExp.Method.DeclaringType;
var callParseResult = "";
switch (callType.FullName)
{
case "System.String": callParseResult = ParseCallString(); break;
case "System.Math": callParseResult = ParseCallMath(); break;
case "System.DateTime": callParseResult = ParseCallDateTime(); break;
case "FreeRedis.RediSearch.SearchBuilderStringExtensions":
callParseResult = ParseCallStringExtension();
break;
default: callParseResult = ParseCallOther(); break;
}
if (!string.IsNullOrEmpty(callParseResult)) return callParseResult;
break;
string ParseCallString()
{
if (callExp.Object != null)
{
var left = parseExp(callExp.Object);
switch (callExp.Method.Name)
{
case "StartsWith":
case "EndsWith":
case "Contains":
var right = parseExp(callExp.Arguments[0]);
if (right.StartsWith("'"))
{
switch (callExp.Method.Name)
{
case "StartsWith":
case "Contains":
right = $"'*{right.Substring(1)}";
break;
}
}
if (right.EndsWith("'"))
{
switch (callExp.Method.Name)
{
case "EndsWith":
case "Contains":
right = $"{right.Substring(0, right.Length - 1)}*'";
break;
}
}
return $"{left}:{right}";
case "ToLower": return $"lower({left})";
case "ToUpper": return $"upper({left})";
case "Substring":
var substrArgs1 = parseExp(callExp.Arguments[0]);
if (callExp.Arguments.Count == 1) return $"substr({left},{substrArgs1},-1)";
return $"substr({left},{substrArgs1},{parseExp(callExp.Arguments[1])})";
case "Equals":
var equalRight = parseExp(callExp.Arguments[0]);
return $"{left}:[{equalRight} {equalRight}]";
}
}
return null;
}
string ParseCallStringExtension()
{
var left = parseExp(callExp.Arguments[0]);
switch (callExp.Method.Name)
{
case "GeoRadius":
var lon = parseExp(callExp.Arguments[1]);
var lat = parseExp(callExp.Arguments[2]);
var radius = parseExp(callExp.Arguments[3]);
var unit = parseExp(callExp.Arguments[4]);
return $"{left}:[{lon} {lat} {radius} {unit.Replace("'", "")}]";
case "ShapeWithin":
{
var parameterName = parseExp(callExp.Arguments[1]);
return $"{left}:[WITHIN ${parameterName.Replace("'", "")}]";
}
case "ShapeContains":
{
var parameterName = parseExp(callExp.Arguments[1]);
return $"{left}:[CONTAINS ${parameterName.Replace("'", "")}]";
}
case "ShapeIntersects":
{
var parameterName = parseExp(callExp.Arguments[1]);
return $"{left}:[INTERSECTS ${parameterName.Replace("'", "")}]";
}
case "ShapeDisjoint":
{
var parameterName = parseExp(callExp.Arguments[1]);
return $"{left}:[DISJOINT ${parameterName.Replace("'", "")}]";
}
}
return null;
}
string ParseCallMath()
{
switch (callExp.Method.Name)
{
case "Abs": return $"abs({parseExp(callExp.Arguments[0])})";
case "Sign": return $"sign({parseExp(callExp.Arguments[0])})";
case "Floor": return $"floor({parseExp(callExp.Arguments[0])})";
case "Ceiling": return $"ceiling({parseExp(callExp.Arguments[0])})";
case "Round":
if (callExp.Arguments.Count > 1 && callExp.Arguments[1].Type.FullName == "System.Int32") return $"round({parseExp(callExp.Arguments[0])}, {parseExp(callExp.Arguments[1])})";
return $"round({parseExp(callExp.Arguments[0])})";
case "Exp": return $"exp({parseExp(callExp.Arguments[0])})";
case "Log": return $"log({parseExp(callExp.Arguments[0])})";
case "Log10": return $"log10({parseExp(callExp.Arguments[0])})";
case "Pow": return $"pow({parseExp(callExp.Arguments[0])}, {parseExp(callExp.Arguments[1])})";
case "Sqrt": return $"sqrt({parseExp(callExp.Arguments[0])})";
case "Cos": return $"cos({parseExp(callExp.Arguments[0])})";
case "Sin": return $"sin({parseExp(callExp.Arguments[0])})";
case "Tan": return $"tan({parseExp(callExp.Arguments[0])})";
case "Acos": return $"acos({parseExp(callExp.Arguments[0])})";
case "Asin": return $"asin({parseExp(callExp.Arguments[0])})";
case "Atan": return $"atan({parseExp(callExp.Arguments[0])})";
case "Atan2": return $"atan2({parseExp(callExp.Arguments[0])}, {parseExp(callExp.Arguments[1])})";
case "Truncate": return $"truncate({parseExp(callExp.Arguments[0])}, 0)";
}
return null;
}
string ParseCallDateTime()
{
if (callExp.Object != null)
{
var left = parseExp(callExp.Object);
var args1 = callExp.Arguments.Count == 0 ? null : parseExp(callExp.Arguments[0]);
switch (callExp.Method.Name)
{
case "Equals": return $"{left}:[{args1} {args1}]";
case "ToString":
if (callExp.Arguments.Count == 0) return $"timefmt({left},'%Y-%m-%d %H:%M:%S')";
switch (args1)
{
case "'yyyy-MM-dd HH:mm:ss'": return $"timefmt({left},'%Y-%m-%d %H:%M:%S')";
case "'yyyy-MM-dd HH:mm'": return $"timefmt({left},'%Y-%m-%d %H:%M')";
case "'yyyy-MM-dd HH'": return $"timefmt({left},'%Y-%m-%d %H')";
case "'yyyy-MM-dd'": return $"timefmt({left},'%Y-%m-%d')";
case "'yyyy-MM'": return $"timefmt({left},'%Y-%m')";
case "'yyyyMMddHHmmss'": return $"timefmt({left},'%Y%m%d%H%M%S')";
case "'yyyyMMddHHmm'": return $"timefmt({left},'%Y%m%d%H%M')";
case "'yyyyMMddHH'": return $"timefmt({left},'%Y%m%d%H')";
case "'yyyyMMdd'": return $"timefmt({left},'%Y%m%d')";
case "'yyyyMM'": return $"timefmt({left},'%Y%m')";
case "'yyyy'": return $"timefmt({left},'%Y')";
case "'HH:mm:ss'": return $"timefmt({left},'%H:%M:%S')";
}
args1 = Regex.Replace(args1, "(yyyy|MM|dd|HH|mm|ss)", m =>
{
switch (m.Groups[1].Value)
{
case "yyyy": return $"%Y";
case "MM": return $"%m";
case "dd": return $"%d";
case "HH": return $"%H";
case "mm": return $"%M";
case "ss": return $"%S";
}
return m.Groups[0].Value;
});
return args1;
}
}
return null;
}
string ParseCallOther()
{
var objExp = callExp.Object;
var objType = objExp?.Type;
if (objType?.FullName == "System.Byte[]") return null;
var argIndex = 0;
if (objType == null && callExp.Method.DeclaringType == typeof(Enumerable))
{
objExp = callExp.Arguments.FirstOrDefault();
objType = objExp?.Type;
argIndex++;
if (objType == typeof(string))
{
switch (callExp.Method.Name)
{
case "First":
case "FirstOrDefault":
return $"substr({parseExp(callExp.Arguments[0])},0,1)";
}
}
}
if (objType == null) objType = callExp.Method.DeclaringType;
if (objType != null || objType.IsArrayOrList())
{
string left = null;
switch (callExp.Method.Name)
{
case "Contains":
left = objExp == null ? null : parseExp(objExp);
var args1 = parseExp(callExp.Arguments[argIndex]);
return $"{left}:{{{toFtTagString(args1)}}}";
}
}
return null;
}
}
if (exp is BinaryExpression expBinary && expBinary != null)
{
switch (expBinary.NodeType)
{
case ExpressionType.OrElse:
case ExpressionType.Or:
return $"({parseExp(expBinary.Left)}|{parseExp(expBinary.Right)})";
case ExpressionType.AndAlso:
case ExpressionType.And:
return $"{parseExp(expBinary.Left)} {parseExp(expBinary.Right)}";
case ExpressionType.GreaterThan:
return $"{parseExp(expBinary.Left)}:[({parseExp(expBinary.Right)} +inf]";
case ExpressionType.GreaterThanOrEqual:
return $"{parseExp(expBinary.Left)}:[{parseExp(expBinary.Right)} +inf]";
case ExpressionType.LessThan:
return $"{parseExp(expBinary.Left)}:[-inf ({parseExp(expBinary.Right)}]";
case ExpressionType.LessThanOrEqual:
return $"{parseExp(expBinary.Left)}:[-inf {parseExp(expBinary.Right)}]";
case ExpressionType.NotEqual:
case ExpressionType.Equal:
var equalRight = parseExp(expBinary.Right);
if (ParseTryGetField(expBinary.Left, out var field))
{
if (field.FieldType == FieldType.Text)
return $"{(expBinary.NodeType == ExpressionType.NotEqual ? "-" : "")}{parseExp(expBinary.Left)}:{equalRight}";
else if (field.FieldType == FieldType.Tag)
return $"{(expBinary.NodeType == ExpressionType.NotEqual ? "-" : "")}{parseExp(expBinary.Left)}:{{{toFtTagString(equalRight)}}}";
}
return $"{(expBinary.NodeType == ExpressionType.NotEqual ? "-" : "")}{parseExp(expBinary.Left)}:[{equalRight} {equalRight}]";
case ExpressionType.Add:
case ExpressionType.AddChecked:
return $"({parseExp(expBinary.Left)}+{parseExp(expBinary.Right)})";
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return $"({parseExp(expBinary.Left)}-{parseExp(expBinary.Right)})";
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return $"{parseExp(expBinary.Left)}*{parseExp(expBinary.Right)}";
case ExpressionType.Divide:
return $"{parseExp(expBinary.Left)}/{parseExp(expBinary.Right)}";
case ExpressionType.Modulo:
return $"{parseExp(expBinary.Left)}%{parseExp(expBinary.Right)}";
}
}
if (exp.IsParameter() == false) return toFt(Expression.Lambda(exp).Compile().DynamicInvoke());
throw new Exception($"Unable to parse this expression: {exp}");
}
internal protected bool ParseTryGetField(Expression exp, out DocumentSchemaFieldInfo field)
{
field = null;
if (exp == null) return false;
if (exp.NodeType != ExpressionType.MemberAccess) return false;
var memberExp = exp as MemberExpression;
if (memberExp == null) return false;
if (memberExp.Expression.IsParameter() == false) return false;
return _schema.FieldsMap.TryGetValue(memberExp.Member.Name, out field);
}
}
[AttributeUsage(AttributeTargets.Class)]
public class FtDocumentAttribute : Attribute
{
public string Name { get; set; }
public string Prefix { get; set; }
public string Filter { get; set; }
public string Language { get; set; } = "chinese";
public FtDocumentAttribute(string name)
{
Name = name;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class FtKeyAttribute : Attribute { }
public abstract class FtFieldAttribute : Attribute
{
public string Name { get; set; }
public string Alias { get; set; }
public string FieldName => string.IsNullOrEmpty(Alias) ? Name : Alias;
}
[AttributeUsage(AttributeTargets.Property)]
public class FtTextFieldAttribute : FtFieldAttribute
{
public double Weight { get; set; }
public bool NoStem { get; set; }
public string Phonetic { get; set; }
public bool Sortable { get; set; }
public bool Unf { get; set; }
public bool NoIndex { get; set; }
public bool WithSuffixTrie { get; set; }
public bool MissingIndex { get; set; }
public bool EmptyIndex { get; set; }
public FtTextFieldAttribute() { }
public FtTextFieldAttribute(string name)
{
Name = name;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class FtTagFieldAttribute : FtFieldAttribute
{
public bool Sortable { get; set; }
public bool Unf { get; set; }
public bool NoIndex { get; set; }
public string Separator { get; set; }
public bool CaseSensitive { get; set; }
public bool WithSuffixTrie { get; set; }
public bool MissingIndex { get; set; }
public bool EmptyIndex { get; set; }
public FtTagFieldAttribute() { }
public FtTagFieldAttribute(string name)
{
Name = name;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class FtNumericFieldAttribute : FtFieldAttribute
{
public bool Sortable { get; set; }
public bool NoIndex { get; set; }
public bool MissingIndex { get; set; }
public FtNumericFieldAttribute() { }
public FtNumericFieldAttribute(string name)
{
Name = name;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class FtGeoFieldAttribute : FtFieldAttribute
{
public bool Sortable { get; set; }
public bool NoIndex { get; set; }
public bool MissingIndex { get; set; }
public FtGeoFieldAttribute() { }
public FtGeoFieldAttribute(string name)
{
Name = name;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class FtGeoShapeFieldAttribute : FtFieldAttribute
{
public CoordinateSystem System { get; set; }
public bool MissingIndex { get; set; }
public FtGeoShapeFieldAttribute() { }
public FtGeoShapeFieldAttribute(string name)
{
Name = name;
}
}
public class FtDocumentRepositorySearchBuilder<T>
{
SearchBuilder _searchBuilder;
FtDocumentRepository<T> _repository;
internal FtDocumentRepositorySearchBuilder(FtDocumentRepository<T> repository, string index, string query)
{
_repository = repository;
_searchBuilder = new SearchBuilder(_repository._client, index, query);
}
List<T> FetchResult(SearchResult result)
{
var ttype = typeof(T);
var prefix = _repository._schema.DocumentAttribute.Prefix;
var keyProperty = _repository._schema.KeyProperty;
return result.Documents.Select(doc =>
{
var item = (T)ttype.CreateInstanceGetDefaultValue();
foreach (var kv in doc.Body)
{
var name = kv.Key.Replace("-", "_");
FtDocumentRepository<T>.DocumentSchemaFieldInfo field = null;
if (_searchBuilder._return.Any()) //属性匹配
{
var prop = ttype.GetPropertyOrFieldIgnoreCase(name);
if (prop == null || !_repository._schema.FieldsMap.TryGetValue(prop.Name, out field)) continue;
}
else if (!_repository._schema.FieldsMapRead.TryGetValue(name, out field)) continue;
if (kv.Value == null) continue;
if (kv.Value is string valstr && field.FieldType == FieldType.Tag)
ttype.SetPropertyOrFieldValue(item, field.Property.Name,
field.Property.PropertyType.IsArrayOrList() ?
field.Property.PropertyType.FromObject(valstr.Split(new[] { (field.FieldAttribute as FtTagFieldAttribute).Separator ?? "," }, StringSplitOptions.None)) : valstr
);
else
ttype.SetPropertyOrFieldValue(item, field.Property.Name, field.Property.PropertyType.FromObject(kv.Value));
}
var itemId = doc.Id;
if (!string.IsNullOrEmpty(prefix))
if (itemId.StartsWith(prefix))
itemId = itemId.Substring(prefix.Length);
typeof(T).SetPropertyOrFieldValue(item, keyProperty.Name, keyProperty.PropertyType.FromObject(itemId));
return item;
}).ToList();
}
public long Total { get; private set; }
public List<T> ToList() => ToList(out var _);
public List<T> ToList(out long total)
{
var result = _searchBuilder.Execute();
total = Total = result.Total;
return FetchResult(result);
}
#if isasync
async public Task<List<T>> ToListAsync()
{
var result = await _searchBuilder.ExecuteAsync();
Total = result.Total;
return FetchResult(result);
}
#endif
public FtDocumentRepositorySearchBuilder<T> NoContent(bool value = true)
{
_searchBuilder.NoContent(value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Verbatim(bool value = true)
{
_searchBuilder.Verbatim(value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Filter(Expression<Func<T, object>> selector, object min, object max)
{
var fields = _repository.ParseSelectorExpression(selector.Body);
if (fields.Any()) _searchBuilder.Filter(fields.FirstOrDefault().Value, min, max);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Filter(string field, object min, object max)
{
_searchBuilder.Filter(field, min, max);
return this;
}
public FtDocumentRepositorySearchBuilder<T> InKeys(params string[] keys)
{
_searchBuilder.InKeys(keys);
return this;
}
public FtDocumentRepositorySearchBuilder<T> InFields(Expression<Func<T, object>> selector)
{
var fields = _repository.ParseSelectorExpression(selector.Body).Select(a => a.Value).ToArray();
if (fields.Any()) _searchBuilder.InFields(fields);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Return(Expression<Func<T, object>> selector)
{
var identifiers = _repository.ParseSelectorExpression(selector.Body)
.Select(a => new KeyValuePair<string, string>(a.Value, a.Key)).ToArray();
if (identifiers.Any()) _searchBuilder.Return(identifiers);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Sumarize(Expression<Func<T, object>> selector, long frags = -1, long len = -1, string separator = null)
{
var fields = _repository.ParseSelectorExpression(selector.Body).Select(a => a.Value).ToArray();
if (fields.Any()) _searchBuilder.Sumarize(fields, frags, len, separator);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Sumarize(string[] fields, long frags = -1, long len = -1, string separator = null)
{
_searchBuilder.Sumarize(fields, frags, len, separator);
return this;
}
public FtDocumentRepositorySearchBuilder<T> HighLight(Expression<Func<T, object>> selector, string tagsOpen = null, string tagsClose = null)
{
var fields = _repository.ParseSelectorExpression(selector.Body).Select(a => a.Value).ToArray();
if (fields.Any()) _searchBuilder.HighLight(fields, tagsOpen, tagsClose);
return this;
}
public FtDocumentRepositorySearchBuilder<T> HighLight(string[] fields, string tagsOpen = null, string tagsClose = null)
{
_searchBuilder.HighLight(fields, tagsOpen, tagsClose);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Slop(decimal value)
{
_searchBuilder.Slop(value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Timeout(long milliseconds)
{
_searchBuilder.Timeout(milliseconds);
return this;
}
public FtDocumentRepositorySearchBuilder<T> InOrder(bool value = true)
{
_searchBuilder.InOrder(value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Language(string value)
{
_searchBuilder.Language(value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Scorer(string value)
{
_searchBuilder.Scorer(value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> SortBy(Expression<Func<T, object>> selector)
{
_searchBuilder.SortBy(_repository.ParseQueryExpression(selector, new FtDocumentRepository<T>.ParseQueryExpressionOptions { IsQuoteFieldName = false }), false);
return this;
}
public FtDocumentRepositorySearchBuilder<T> SortByDesc(Expression<Func<T, object>> selector)
{
_searchBuilder.SortBy(_repository.ParseQueryExpression(selector, new FtDocumentRepository<T>.ParseQueryExpressionOptions { IsQuoteFieldName = false }), true);
return this;
}
public FtDocumentRepositorySearchBuilder<T> SortBy(string sortBy, bool desc = false)
{
_searchBuilder.SortBy(sortBy, desc);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Limit(long offset, long num)
{
_searchBuilder.Limit(offset, num);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Params(string name, string value)
{
_searchBuilder.Params(name, value);
return this;
}
public FtDocumentRepositorySearchBuilder<T> Dialect(int value)
{
_searchBuilder.Dialect(value);
return this;
}
}
public class FtDocumentRepositoryAggregateTuple<TDocument, TExtra>
{
public TDocument Document { get; set; }
public TExtra Extra { get; set; }
}
public class FtDocumentRepositoryAggregateBuilder<TDocument, TExtra>
{
AggregateBuilder _aggregateBuilder;
FtDocumentRepository<TDocument> _repository;
internal FtDocumentRepositoryAggregateBuilder(FtDocumentRepository<TDocument> repository, AggregateBuilder aggregateBuilder)
{
_repository = repository;
_aggregateBuilder = aggregateBuilder;
}
internal FtDocumentRepositoryAggregateBuilder(FtDocumentRepository<TDocument> repository, string index, string query)
{
_repository = repository;
_aggregateBuilder = new AggregateBuilder(_repository._client, index, query);
}
//public List<T> ToList() => ToList(out var _);
//public List<T> ToList(out long total)
//{
// var prefix = _repository._schema.DocumentAttribute.Prefix;
// var keyProperty = _repository._schema.KeyProperty;
// var result = _aggregateBuilder.Execute();
// total = result.Total;
// var ttype = typeof(T);
// return result.Documents.Select(doc =>
// {
// var item = (T)ttype.CreateInstanceGetDefaultValue();
// foreach (var kv in doc.Body)
// {
// var name = kv.Key.Replace("-", "_");
// var prop = ttype.GetPropertyOrFieldIgnoreCase(name);
// if (prop == null) continue;
// if (kv.Value == null) continue;
// if (kv.Value is string valstr && _repository._schema.FieldsMap.TryGetValue(prop.Name, out var field) && field.FieldType == FieldType.Tag)
// ttype.SetPropertyOrFieldValue(item, prop.Name, valstr.Split(new[] { (field.FieldAttribute as FtTagFieldAttribute).Separator ?? "," }, StringSplitOptions.None));
// else
// ttype.SetPropertyOrFieldValue(item, prop.Name, prop.GetPropertyOrFieldType().FromObject(kv.Value));
// }
// var itemId = doc.Id;
// if (!string.IsNullOrEmpty(prefix))
// if (itemId.StartsWith(prefix))
// itemId = itemId.Substring(prefix.Length);
// typeof(T).SetPropertyOrFieldValue(item, keyProperty.Name, keyProperty.PropertyType.FromObject(itemId));
// return item;
// }).ToList();
//}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Verbatim(bool value = true)
{
_aggregateBuilder.Verbatim(value);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Load(Expression<Func<TDocument, object>> selector)
{
var fields = _repository.ParseSelectorExpression(selector.Body).Select(a => a.Value).ToArray();
if (fields.Any()) _aggregateBuilder.Load(fields);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Timeout(long milliseconds)
{
_aggregateBuilder.Timeout(milliseconds);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TNewExtra> GroupBy<TNewExtra>(Expression<Func<FtDocumentRepositoryAggregateTuple<TDocument, TExtra>, TNewExtra>> selector)
{
var fieldValues = new List<KeyValuePair<string, string>>();
var exp = selector.Body;
if (exp.NodeType == ExpressionType.New)
{
var newExp = exp as NewExpression;
for (var a = 0; a < newExp?.Members?.Count; a++)
{
var left = newExp.Members[a].Name;
var right = _repository.ParseQueryExpression(newExp.Arguments[a], new FtDocumentRepository<TDocument>.ParseQueryExpressionOptions { IsQuoteFieldName = false });
fieldValues.Add(new KeyValuePair<string, string>(left, right));
}
}
else if (exp.NodeType == ExpressionType.MemberInit)
{
var initExp = exp as MemberInitExpression;
for (var a = 0; a < initExp?.Bindings.Count; a++)
{
var initAssignExp = (initExp.Bindings[a] as MemberAssignment);
if (initAssignExp == null) continue;
var left = initAssignExp.Member.Name;
var right = _repository.ParseQueryExpression(initAssignExp.Expression, new FtDocumentRepository<TDocument>.ParseQueryExpressionOptions { IsQuoteFieldName = false });
fieldValues.Add(new KeyValuePair<string, string>(left, right));
}
}
return new FtDocumentRepositoryAggregateBuilder<TDocument, TNewExtra>(_repository, _aggregateBuilder);
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> GroupBy(string[] properties = null, params AggregateReduce[] reduces)
{
_aggregateBuilder.GroupBy(properties, reduces);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> SortBy(string property, bool desc = false)
{
_aggregateBuilder.SortBy(property, desc);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> SortBy(string[] properties, bool[] desc, int max = 0)
{
_aggregateBuilder.SortBy(properties, desc, max);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TNewExtra> Apply<TNewExtra>(Expression<Func<TDocument, TExtra, TNewExtra>> selector)
{
var applies = _repository.ParseSelectorExpression(selector.Body, true);
_aggregateBuilder._applies.Clear();
foreach (var apply in applies)
_aggregateBuilder.Apply(apply.Value, apply.Key);
return new FtDocumentRepositoryAggregateBuilder<TDocument, TNewExtra>(_repository, _aggregateBuilder);
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Limit(long offset, long num)
{
_aggregateBuilder.Limit(offset, num);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Filter(string value)
{
_aggregateBuilder.Filter(value);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> WithCursor(int count = -1, long maxIdle = -1)
{
_aggregateBuilder.WithCursor(count, maxIdle);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Params(string name, string value)
{
_aggregateBuilder.Params(name, value);
return this;
}
public FtDocumentRepositoryAggregateBuilder<TDocument, TExtra> Dialect(int value)
{
_aggregateBuilder.Dialect(value);
return this;
}
}
}
|
2881099/FreeRedis | 16,162 | src/FreeRedis/RedisClient/Modules/RediSearchBuilder/CreateBuilder.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis.RediSearch
{
public class AlterBuilder : SchemaBuilder<AlterBuilder>
{
RedisClient _redis;
string _index;
internal AlterBuilder(RedisClient redis, string index)
{
_redis = redis;
_index = index;
}
public void Execute() => _redis.Call(GetCommandPacket(), rt => rt.ThrowOrValue<string>() == "OK");
#if isasync
public Task ExecuteAsync() => _redis.CallAsync(GetCommandPacket(), rt => rt.ThrowOrValue<string>() == "OK");
#endif
CommandPacket GetCommandPacket() => "FT.ALTER".Input(_index)
.InputIf(_skipInitialScan, "SKIPINITIALSCAN")
.Input("SCHEMA")
.Input(_schemaArgs.ToArray());
private bool _skipInitialScan;
public AlterBuilder SkipInitialScan(bool value = true)
{
_skipInitialScan = value;
return this;
}
}
public class CreateBuilder : SchemaBuilder<CreateBuilder>
{
RedisClient _redis;
string _index;
internal CreateBuilder(RedisClient redis, string index)
{
_redis = redis;
_index = index;
_language = redis.ConnectionString.FtLanguage;
}
public void Execute() => _redis.Call(GetCommandPacket(), rt => rt.ThrowOrValue<string>() == "OK");
#if isasync
public Task ExecuteAsync() => _redis.CallAsync(GetCommandPacket(), rt => rt.ThrowOrValue<string>() == "OK");
#endif
CommandPacket GetCommandPacket()
{
var cmd = "FT.CREATE".Input(_index).InputIf(_on.HasValue, "ON", _on.ToString().ToUpper());
if (_prefix?.Any() == true) cmd.Input("PREFIX", _prefix.Length).Input(_prefix.Select(a => (object)a).ToArray());
cmd
.InputIf(!string.IsNullOrWhiteSpace(_filter), "FILTER", _filter)
.InputIf(!string.IsNullOrWhiteSpace(_language), "LANGUAGE", _language)
.InputIf(!string.IsNullOrWhiteSpace(_languageField), "LANGUAGE_FIELD", _languageField)
.InputIf(_score > 0, "SCORE", _score)
.InputIf(_scoreField > 0, "SCORE_FIELD", _scoreField)
.InputIf(!string.IsNullOrWhiteSpace(_payloadField), "PAYLOAD_FIELD", _payloadField)
.InputIf(_maxTextFields, "MAXTEXTFIELDS")
.InputIf(_temporary > 0, "TEMPORARY", _temporary)
.InputIf(_noOffsets, "NOOFFSETS")
.InputIf(_noHL, "NOHL")
.InputIf(_noFields, "NOFIELDS")
.InputIf(_noFreqs, "NOFREQS");
if (_stopwords?.Any() == true) cmd.Input("STOPWORDS", _stopwords.Length).Input(_stopwords.Select(a => (object)a).ToArray());
cmd.InputIf(_skipInitialScan, "SKIPINITIALSCAN")
.Input("SCHEMA")
.Input(_schemaArgs.ToArray());
return cmd;
}
private IndexDataType? _on = IndexDataType.Hash;
private string[] _prefix;
private string _filter;
private string _language;
private string _languageField;
private decimal _score;
private decimal _scoreField;
private string _payloadField;
private bool _maxTextFields;
private long _temporary;
private bool _noOffsets;
private bool _noHL;
private bool _noFields;
private bool _noFreqs;
private string[] _stopwords;
private bool _skipInitialScan;
public CreateBuilder On(IndexDataType value)
{
_on = value;
return this;
}
public CreateBuilder Prefix(params string[] value)
{
_prefix = value;
return this;
}
public CreateBuilder Filter(string value)
{
_filter = value;
return this;
}
public CreateBuilder Language(string value)
{
_language = value;
return this;
}
public CreateBuilder LanguageField(string value)
{
_languageField = value;
return this;
}
public CreateBuilder Score(decimal value)
{
_score = value;
return this;
}
public CreateBuilder ScoreField(decimal value)
{
_scoreField = value;
return this;
}
public CreateBuilder PayloadField(string value)
{
_payloadField = value;
return this;
}
public CreateBuilder MaxTextFields(bool value = true)
{
_maxTextFields = value;
return this;
}
public CreateBuilder Temporary(long seconds)
{
_temporary = seconds;
return this;
}
public CreateBuilder NoOffsets(bool value = true)
{
_noOffsets = value;
return this;
}
public CreateBuilder NoHL(bool value = true)
{
_noHL = value;
return this;
}
public CreateBuilder NoFields(bool value = true)
{
_noFields = value;
return this;
}
public CreateBuilder NoFreqs(bool value = true)
{
_noFreqs = value;
return this;
}
public CreateBuilder Stopwords(params string[] value)
{
_stopwords = value;
return this;
}
public CreateBuilder SkipInitialScan(bool value = true)
{
_skipInitialScan = value;
return this;
}
}
public class SchemaBuilder<TBuilder> where TBuilder : class
{
protected List<object> _schemaArgs = new List<object>();
public TBuilder AddTextField(string name, string alias = null, double weight = 1.0, bool sortable = false, bool unf = false, bool noStem = false,
string phonetic = null, bool noIndex = false, bool withSuffixTrie = false, bool missingIndex = false, bool emptyIndex = false) => AddTextField(name, new TextFieldOptions
{
Alias = alias,
Weight = weight,
Sortable = sortable,
Unf = unf,
NoStem = noStem,
Phonetic = phonetic,
NoIndex = noIndex,
WithSuffixTrie = withSuffixTrie,
MissingIndex = missingIndex,
EmptyIndex = emptyIndex
});
public TBuilder AddTextField(string name, TextFieldOptions options)
{
_schemaArgs.Add(name);
if (options != null)
{
if (!string.IsNullOrWhiteSpace(options.Alias))
{
_schemaArgs.Add("AS");
_schemaArgs.Add(options.Alias);
}
_schemaArgs.Add("TEXT");
if (options.NoStem) _schemaArgs.Add("NOSTEM");
if (options.NoIndex) _schemaArgs.Add("NOINDEX");
if (options.Phonetic != null)
{
_schemaArgs.Add("PHONETIC");
_schemaArgs.Add(options.Phonetic);
}
if (options.Weight != 1.0)
{
_schemaArgs.Add("WEIGHT");
_schemaArgs.Add(options.Weight);
}
if (options.WithSuffixTrie) _schemaArgs.Add("WITHSUFFIXTRIE");
if (options.Sortable) _schemaArgs.Add("SORTABLE");
if (options.Unf) _schemaArgs.Add("UNF");
if (options.MissingIndex) _schemaArgs.Add("INDEXMISSING");
if (options.EmptyIndex) _schemaArgs.Add("INDEXEMPTY");
}
return this as TBuilder;
}
public TBuilder AddTagField(string name, string alias = null, bool sortable = false, bool unf = false, bool noIndex = false, string separator = ",",
bool caseSensitive = false, bool withSuffixTrie = false, bool missingIndex = false, bool emptyIndex = false) => AddTagField(name, new TagFieldOptions
{
Alias = alias,
Sortable = sortable,
Unf = unf,
NoIndex = noIndex,
Separator = separator,
CaseSensitive = caseSensitive,
WithSuffixTrie = withSuffixTrie,
MissingIndex = missingIndex,
EmptyIndex = emptyIndex
});
public TBuilder AddTagField(string name, TagFieldOptions options)
{
_schemaArgs.Add(name);
if (options != null)
{
if (!string.IsNullOrWhiteSpace(options.Alias))
{
_schemaArgs.Add("AS");
_schemaArgs.Add(options.Alias);
}
_schemaArgs.Add("TAG");
if (options.NoIndex) _schemaArgs.Add("NOINDEX");
if (options.WithSuffixTrie) _schemaArgs.Add("WITHSUFFIXTRIE");
if (!string.IsNullOrWhiteSpace(options.Separator) && options.Separator != ",")
{
_schemaArgs.Add("SEPARATOR");
_schemaArgs.Add(options.Separator);
}
if (options.CaseSensitive) _schemaArgs.Add("CASESENSITIVE");
if (options.Sortable) _schemaArgs.Add("SORTABLE");
if (options.Unf) _schemaArgs.Add("UNF");
if (options.MissingIndex) _schemaArgs.Add("INDEXMISSING");
if (options.EmptyIndex) _schemaArgs.Add("INDEXEMPTY");
}
return this as TBuilder;
}
public TBuilder AddNumericField(string name, string alias = null, bool sortable = false, bool noIndex = false, bool missingIndex = false) => AddNumericField(name, new NumbericFieldOptions
{
Alias = alias,
Sortable = sortable,
NoIndex = noIndex,
MissingIndex = missingIndex
});
public TBuilder AddNumericField(string name, NumbericFieldOptions options)
{
_schemaArgs.Add(name);
if (options != null)
{
if (!string.IsNullOrWhiteSpace(options.Alias))
{
_schemaArgs.Add("AS");
_schemaArgs.Add(options.Alias);
}
_schemaArgs.Add("NUMERIC");
if (options.NoIndex) _schemaArgs.Add("NOINDEX");
if (options.Sortable) _schemaArgs.Add("SORTABLE");
if (options.MissingIndex) _schemaArgs.Add("INDEXMISSING");
}
return this as TBuilder;
}
public TBuilder AddGeoField(string name, string alias = null, bool sortable = false, bool noIndex = false, bool missingIndex = false) => AddGeoField(name, new GeoFieldOptions
{
Alias = alias,
Sortable = sortable,
NoIndex = noIndex,
MissingIndex = missingIndex
});
public TBuilder AddGeoField(string name, GeoFieldOptions options)
{
_schemaArgs.Add(name);
if (options != null)
{
if (!string.IsNullOrWhiteSpace(options.Alias))
{
_schemaArgs.Add("AS");
_schemaArgs.Add(options.Alias);
}
_schemaArgs.Add("GEO");
if (options.NoIndex) _schemaArgs.Add("NOINDEX");
if (options.Sortable) _schemaArgs.Add("SORTABLE");
if (options.MissingIndex) _schemaArgs.Add("INDEXMISSING");
}
return this as TBuilder;
}
public TBuilder AddGeoShapeField(string name, string alias = null, CoordinateSystem system = CoordinateSystem.FLAT, bool missingIndex = false) => AddGeoShapeField(name, new GeoShapeFieldOptions
{
Alias = alias,
System = system,
MissingIndex = missingIndex
});
public TBuilder AddGeoShapeField(string name, GeoShapeFieldOptions options)
{
_schemaArgs.Add(name);
if (options != null)
{
if (!string.IsNullOrWhiteSpace(options.Alias))
{
_schemaArgs.Add("AS");
_schemaArgs.Add(options.Alias);
}
_schemaArgs.Add("GEOSHAPE");
_schemaArgs.Add(options.System.ToString().ToUpper());
if (options.MissingIndex) _schemaArgs.Add("INDEXMISSING");
}
return this as TBuilder;
}
public TBuilder AddVectorField(string name, string alias = null, VectorAlgo algorithm = VectorAlgo.FLAT, Dictionary<string, object> attributes = null, bool missingIndex = false) => AddVectorField(name, new VectorFieldOptions
{
Alias = alias,
Algorithm = algorithm,
Attributes = attributes,
MissingIndex = missingIndex
});
public TBuilder AddVectorField(string name, VectorFieldOptions options)
{
_schemaArgs.Add(name);
if (options != null)
{
if (!string.IsNullOrWhiteSpace(options.Alias))
{
_schemaArgs.Add("AS");
_schemaArgs.Add(options.Alias);
}
_schemaArgs.Add("VECTOR");
_schemaArgs.Add(options.Algorithm.ToString().ToUpper());
if (options.Attributes != null)
{
_schemaArgs.Add(options.Attributes.Count * 2);
foreach (var attribute in options.Attributes)
{
_schemaArgs.Add(attribute.Key);
_schemaArgs.Add(attribute.Value);
}
}
if (options.MissingIndex) _schemaArgs.Add("INDEXMISSING");
}
return this as TBuilder;
}
}
public enum IndexDataType { Hash, Json }
public enum FieldType { Text, Tag, Numeric, Geo, Vector, GeoShape }
public class TextFieldOptions
{
public string Alias { get; set; }
public double Weight { get; set; } = 1.0;
public bool NoStem { get; set; }
public string Phonetic { get; set; }
public bool Sortable { get; set; }
public bool Unf { get; set; }
public bool NoIndex { get; set; }
public bool WithSuffixTrie { get; set; }
public bool MissingIndex { get; set; }
public bool EmptyIndex { get; set; }
}
public class TagFieldOptions
{
public string Alias { get; set; }
public bool Sortable { get; set; }
public bool Unf { get; set; }
public bool NoIndex { get; set; }
public string Separator { get; set; } = ",";
public bool CaseSensitive { get; set; }
public bool WithSuffixTrie { get; set; }
public bool MissingIndex { get; set; }
public bool EmptyIndex { get; set; }
}
public class NumbericFieldOptions
{
public string Alias { get; set; }
public bool Sortable { get; set; }
public bool NoIndex { get; set; }
public bool MissingIndex { get; set; }
}
public class GeoFieldOptions
{
public string Alias { get; set; }
public bool Sortable { get; set; }
public bool NoIndex { get; set; }
public bool MissingIndex { get; set; }
}
public enum CoordinateSystem { FLAT, SPHERICAL }
public class GeoShapeFieldOptions
{
public string Alias { get; set; }
public CoordinateSystem System { get; set; }
public bool MissingIndex { get; set; }
}
public enum VectorAlgo { FLAT, HNSW }
public class VectorFieldOptions
{
public string Alias { get; set; }
public VectorAlgo Algorithm { get; set; }
public Dictionary<string, object> Attributes { get; set; }
public bool MissingIndex { get; set; }
}
}
|
2881099/FreeRedis | 13,184 | src/FreeRedis/RedisClient/Modules/RediSearchBuilder/SearchBuilder.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis.RediSearch
{
public class SearchResult
{
public long Total { get; }
public List<Document> Documents { get; }
public SearchResult(long total, List<Document> docs)
{
Total = total;
Documents = docs;
}
}
public class Document
{
public string Id { get; }
public double Score { get; set; }
public byte[] Payload { get; }
public string[] ScoreExplained { get; private set; }
public Dictionary<string, object> Body { get; } = new Dictionary<string, object>();
public object this[string key]
{
get => Body.TryGetValue(key, out var val) ? val : null;
internal set => Body[key] = value;
}
public Document(string id, double score, byte[] payload)
{
Id = id;
Score = score;
Payload = payload;
}
public static Document Load(string id, double score, byte[] payload, object[] fieldValues, string[] scoreExplained)
{
Document ret = new Document(id, score, payload);
if (fieldValues != null)
{
for (int i = 0; i < fieldValues.Length; i += 2)
{
string fieldName = fieldValues[i].ConvertTo<string>();
if (fieldName == "$")
ret.Body["json"] = fieldValues[i + 1];
else
ret.Body[fieldName] = fieldValues[i + 1];
}
}
ret.ScoreExplained = scoreExplained;
return ret;
}
}
public class SearchBuilder
{
RedisClient _redis;
string _index;
string _query;
internal SearchBuilder(RedisClient redis, string index, string query)
{
_redis = redis;
_index = index;
_query = query;
_dialect = redis.ConnectionString.FtDialect;
_language = redis.ConnectionString.FtLanguage;
}
internal CommandPacket GetCommandPacket()
{
var cmd = "FT.SEARCH".Input(_index).Input(_query)
.InputIf(_noContent, "NOCONTENT")
.InputIf(_verbatim, "VERBATIM")
.InputIf(_noStopwords, "NOSTOPWORDS")
.InputIf(_withScores, "WITHSCORES")
.InputIf(_withPayloads, "WITHPAYLOADS")
.InputIf(_withSortKeys, "WITHSORTKEYS");
if (_filters.Any()) cmd.Input("FILTER").Input(_filters.ToArray());
if (_geoFilter.Any()) cmd.Input("GEOFILTER").Input(_geoFilter.ToArray());
if (_inKeys.Any()) cmd.Input("INKEYS", _inKeys.Count).Input(_inKeys.ToArray());
if (_inFields.Any()) cmd.Input("INFIELDS", _inFields.Count).Input(_inFields.ToArray());
if (_return.Any())
{
cmd.Input("RETURN", _return.Sum(a => a[1] == null ? 1 : 3));
foreach (var ret in _return)
if (ret[1] == null) cmd.Input(ret[0]);
else cmd.Input(ret[0], "AS", ret[1]);
}
if (_sumarize)
{
cmd.Input("SUMMARIZE");
if (_sumarizeFields.Any()) cmd.Input("FIELDS", _sumarizeFields.Count).Input(_sumarizeFields.ToArray());
if (_sumarizeFrags != -1) cmd.Input("FRAGS", _sumarizeFrags);
if (_sumarizeLen != -1) cmd.Input("LEN", _sumarizeLen);
if (_sumarizeSeparator != null) cmd.Input("SEPARATOR", _sumarizeSeparator);
}
if (_highLight)
{
cmd.Input("HIGHLIGHT");
if (_highLightFields.Any()) cmd.Input("FIELDS", _highLightFields.Count).Input(_highLightFields.ToArray());
if (_highLightTags != null) cmd.Input("TAGS").Input(_highLightTags);
}
cmd
.InputIf(_slop >= 0, "SLOP", _slop)
.InputIf(_timeout >= 0, "TIMEOUT", _timeout)
.InputIf(_inOrder, "INORDER")
.InputIf(!string.IsNullOrWhiteSpace(_language), "LANGUAGE", _language)
.InputIf(!string.IsNullOrWhiteSpace(_expander), "EXPANDER", _expander)
.InputIf(!string.IsNullOrWhiteSpace(_scorer), "SCORER", _scorer)
.InputIf(_explainScore, "EXPLAINSCORE")
.InputIf(!string.IsNullOrWhiteSpace(_payLoad), "PAYLOAD", _payLoad)
.InputIf(!string.IsNullOrWhiteSpace(_sortBy), "SORTBY", _sortBy).InputIf(_sortByDesc, "DESC")
.InputIf(_limitOffset > 0 || _limitNum != 10, "LIMIT", _limitOffset, _limitNum);
if (_params.Any())
{
cmd.Input("PARAMS", _params.Count);
_params.ForEach(item => cmd.Input(item));
}
cmd
.InputIf(_dialect > 0, "DIALECT", _dialect);
return cmd;
}
SearchResult FetchResult(RedisResult rt) => rt.ThrowOrValue((a, _) =>
{
var ret = new SearchResult(a[0].ConvertTo<long>(), new List<Document>());
if (a.Any() != true || ret.Total <= 0) return ret;
int step = 1;
int scoreOffset = 0;
int contentOffset = 1;
int payloadOffset = 0;
if (_withScores)
{
step++;
scoreOffset = 1;
contentOffset++;
}
if (_noContent == false)
{
step++;
if (_withPayloads)
{
payloadOffset = scoreOffset + 1;
step++;
contentOffset++;
}
}
for (var x = 1; x < a.Length; x += step)
{
var id = a[x].ConvertTo<string>();
double score = 1.0;
byte[] payload = null;
object[] fieldValues = null;
string[] scoreExplained = null;
if (_withScores) score = a[x + scoreOffset].ConvertTo<double>();
if (_withPayloads) payload = a[x + payloadOffset].ConvertTo<byte[]>();
if (_noContent == false) fieldValues = a[x + contentOffset].ConvertTo<object[]>();
ret.Documents.Add(Document.Load(id, score, payload, fieldValues, scoreExplained));
}
return ret;
});
public SearchResult Execute()
{
var cmd = GetCommandPacket();
return _redis.Call(cmd, FetchResult);
}
#if isasync
public Task<SearchResult> ExecuteAsync()
{
var cmd = GetCommandPacket();
return _redis.CallAsync(cmd, FetchResult);
}
#endif
internal bool _noContent, _verbatim, _noStopwords, _withScores, _withPayloads, _withSortKeys;
internal List<object> _filters = new List<object>();
internal List<object> _geoFilter = new List<object>();
internal List<object> _inKeys = new List<object>();
internal List<object> _inFields = new List<object>();
internal List<string[]> _return = new List<string[]>();
internal bool _sumarize;
internal List<object> _sumarizeFields = new List<object>();
internal long _sumarizeFrags = -1;
internal long _sumarizeLen = -1;
internal string _sumarizeSeparator;
internal bool _highLight;
internal List<object> _highLightFields = new List<object>();
internal object[] _highLightTags;
internal decimal _slop = -1;
internal long _timeout = -1;
internal bool _inOrder;
internal string _language;
internal string _expander, _scorer;
internal bool _explainScore;
internal string _payLoad;
internal string _sortBy;
internal bool _sortByDesc;
internal long _limitOffset, _limitNum = 10;
internal List<string> _params = new List<string>();
internal int _dialect;
public SearchBuilder NoContent(bool value = true)
{
_noContent = value;
return this;
}
public SearchBuilder Verbatim(bool value = true)
{
_verbatim = value;
return this;
}
public SearchBuilder NoStopwords(bool value = true)
{
_noStopwords = value;
return this;
}
public SearchBuilder WithScores(bool value = true)
{
_withScores = value;
return this;
}
public SearchBuilder WithPayloads(bool value = true)
{
_withPayloads = value;
return this;
}
public SearchBuilder WithSortKeys(bool value = true)
{
_withSortKeys = value;
return this;
}
public SearchBuilder Filter(string field, object min, object max)
{
_filters.AddRange(new object[] { field, min, max });
return this;
}
public SearchBuilder GeoFilter(string field, decimal lon, decimal lat, decimal radius, GeoUnit unit = GeoUnit.m)
{
_geoFilter.AddRange(new object[] { field, lon, lat, radius, unit });
return this;
}
public SearchBuilder InKeys(params string[] keys)
{
if (keys?.Any() == true) _inKeys.AddRange(keys);
return this;
}
public SearchBuilder InFields(params string[] fields)
{
if (fields?.Any() == true) _inFields.AddRange(fields);
return this;
}
public SearchBuilder Return(params string[] identifiers)
{
if (identifiers?.Any() == true) _return.AddRange(identifiers.Select(a => new[] { a, null }));
return this;
}
public SearchBuilder Return(params KeyValuePair<string, string>[] identifierProperties)
{
if (identifierProperties?.Any() == true) _return.AddRange(identifierProperties.Select(a => new[] { a.Key, a.Value }));
return this;
}
public SearchBuilder Sumarize(string[] fields, long frags = -1, long len = -1, string separator = null)
{
_sumarize = true;
_sumarizeFields.AddRange(fields);
_sumarizeFrags = frags;
_sumarizeLen = len;
_sumarizeSeparator = separator;
return this;
}
public SearchBuilder HighLight(string[] fields, string tagsOpen = null, string tagsClose = null)
{
_highLight = true;
_highLightFields.AddRange(fields);
_highLightTags = new[] { tagsOpen, tagsClose };
return this;
}
public SearchBuilder Slop(decimal value)
{
_slop = value;
return this;
}
public SearchBuilder Timeout(long milliseconds)
{
_timeout = milliseconds;
return this;
}
public SearchBuilder InOrder(bool value = true)
{
_inOrder = value;
return this;
}
public SearchBuilder Language(string value)
{
_language = value;
return this;
}
public SearchBuilder Expander(string value)
{
_expander = value;
return this;
}
public SearchBuilder Scorer(string value)
{
_scorer = value;
return this;
}
public SearchBuilder ExplainScore(bool value = true)
{
_explainScore = value;
return this;
}
public SearchBuilder Payload(string value)
{
_payLoad = value;
return this;
}
public SearchBuilder SortBy(string sortBy, bool desc = false)
{
_sortBy = sortBy;
_sortByDesc = desc;
return this;
}
public SearchBuilder Limit(long offset, long num)
{
_limitOffset = offset;
_limitNum = num;
return this;
}
public SearchBuilder Params(string name, string value)
{
_params.Add(name);
_params.Add(value);
return this;
}
public SearchBuilder Dialect(int value)
{
_dialect = value;
return this;
}
}
public static class SearchBuilderStringExtensions
{
// 替换为判断field字段是否在以(lon, lat)为圆心,半径为radius的圆内更好,但是只用于Search方法的话还是不用那么复杂的实现了
public static bool GeoRadius(this string field, decimal lon, decimal lat, decimal radius, GeoUnit unit) => true;
public static bool ShapeWithin(this string field, string parameterName) => true;
public static bool ShapeContains(this string field, string parameterName) => true;
public static bool ShapeIntersects(this string field, string parameterName) => true;
public static bool ShapeDisjoint(this string field, string parameterName) => true;
}
}
|
2881099/FreeRedis | 7,607 | src/FreeRedis/RedisClient/Modules/RediSearchBuilder/AggregateBuilder.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace FreeRedis.RediSearch
{
public class AggregationResult
{
public long CursorId { get; }
public Dictionary<string, object>[] Results { get; }
public AggregationResult(object result, long cursorId = -1)
{
var arr = result as object[];
Results = new Dictionary<string, object>[arr.Length - 1];
for (int i = 1; i < arr.Length; i++)
{
var raw = arr[i] as object[];
var cur = new Dictionary<string, object>();
for (int j = 0; j < raw.Length;)
{
var key = raw[j++].ConvertTo<string>();
var val = raw[j++];
cur.Add(key, val);
}
Results[i - 1] = cur;
}
CursorId = cursorId;
}
}
public class AggregateBuilder
{
RedisClient _redis;
string _index;
string _query;
internal AggregateBuilder(RedisClient redis, string index, string query)
{
_redis = redis;
_index = index;
_query = query;
_dialect = redis.ConnectionString.FtDialect;
}
public AggregationResult Execute() => _redis.Call(GetCommandPacket(), rt => rt.ThrowOrValue((a, _) =>
{
if (_withCursor) return new AggregationResult(a[0], a[1].ConvertTo<long>());
else return new AggregationResult(a);
}));
#if isasync
public Task<AggregationResult> ExecuteAsync() => _redis.CallAsync(GetCommandPacket(), rt => rt.ThrowOrValue((a, _) =>
{
if (_withCursor) return new AggregationResult(a[0], a[1].ConvertTo<long>());
else return new AggregationResult(a);
}));
#endif
CommandPacket GetCommandPacket()
{
var cmd = "FT.AGGREGATE".Input(_index).Input(_query)
.InputIf(_verbatim, "VERBATIM");
if (_load.Any()) cmd.Input("LOAD", _load.Count).Input(_load.ToArray());
cmd.InputIf(_applies.Any(), _applies.ToArray())
.InputIf(_timeout >= 0, "TIMEOUT", _timeout);
if (_groupBy.Any())
{
cmd.Input("GROUPBY", _groupBy.Count).Input(_groupBy.ToArray());
foreach (var reduce in _groupByReduces)
cmd.Input("REDUCE", reduce.Function, reduce.Arguments?.Length ?? 0)
.InputIf(reduce.Arguments?.Any() == true, reduce.Arguments)
.InputIf(!string.IsNullOrWhiteSpace(reduce.Alias), "AS", reduce.Alias);
}
if (_sortBy.Any()) cmd.InputIf(_sortBy.Any(), "SORTBY").Input(_sortBy.ToArray()).InputIf(_sortByMax > 0, "MAX", _sortByMax);
cmd
.InputIf(_limitOffset > 0 || _limitNum != 10, "LIMIT", _limitOffset, _limitNum)
.InputIf(!string.IsNullOrWhiteSpace(_filter), "FILTER", _filter);
if (_withCursor) cmd.Input("WITHCURSOR").InputIf(_withCursorCount != -1, "COUNT", _withCursorCount).InputIf(_withCursorMaxIdle != -1, "MAXIDLE", _withCursorMaxIdle);
if (_params.Any())
{
cmd.Input("PARAMS", _params.Count);
_params.ForEach(item => cmd.Input(item));
}
cmd
.InputIf(_dialect > 0, "DIALECT", _dialect);
return cmd;
}
private bool _verbatim;
private List<object> _load = new List<object>();
private long _timeout = -1;
private List<object> _groupBy = new List<object>();
private List<AggregateReduce> _groupByReduces = new List<AggregateReduce>();
private List<object> _sortBy = new List<object>();
private int _sortByMax;
internal List<object> _applies = new List<object>();
private long _limitOffset, _limitNum = 10;
private string _filter;
private bool _withCursor;
private int _withCursorCount = -1;
private long _withCursorMaxIdle = -1;
private List<string> _params = new List<string>();
private int _dialect;
public AggregateBuilder Verbatim(bool value = true)
{
_verbatim = value;
return this;
}
public AggregateBuilder Load(params string[] fields)
{
if (fields?.Any() == true)
{
_load.Clear();
_load.AddRange(fields);
}
return this;
}
public AggregateBuilder Timeout(long milliseconds)
{
_timeout = milliseconds;
return this;
}
public AggregateBuilder GroupBy(params string[] properties)
{
if (properties?.Any() == true)
{
_groupBy.Clear();
_groupBy.AddRange(properties);
}
return this;
}
public AggregateBuilder GroupBy(string[] properties = null, params AggregateReduce[] reduces)
{
if (properties?.Any() == true)
{
_groupBy.Clear();
_groupBy.AddRange(properties);
}
if (reduces?.Any() == true)
{
_groupByReduces.Clear();
_groupByReduces.AddRange(reduces);
}
return this;
}
public AggregateBuilder SortBy(string property, bool desc = false)
{
if (!string.IsNullOrWhiteSpace(property))
{
_sortBy.Add(property);
if (desc) _sortBy.Add("DESC");
}
return this;
}
public AggregateBuilder SortBy(string[] properties, bool[] desc, int max = 0)
{
if (properties != null)
{
for (var a = 0; a < properties.Length; a++)
{
if (!string.IsNullOrWhiteSpace(properties[a]))
{
_sortBy.Add(properties[a]);
if (desc != null && a < desc.Length && desc[a]) _sortBy.Add("DESC");
}
}
}
_sortByMax = max;
return this;
}
public AggregateBuilder Apply(string expression, string alias)
{
_applies.Add("APPLY");
_applies.Add(expression);
_applies.Add("AS");
_applies.Add(alias);
return this;
}
public AggregateBuilder Limit(long offset, long num)
{
_limitOffset = offset;
_limitNum = num;
return this;
}
public AggregateBuilder Filter(string value)
{
_filter = value;
return this;
}
public AggregateBuilder WithCursor(int count = -1, long maxIdle = -1)
{
_withCursor = true;
_withCursorCount = count;
_withCursorMaxIdle = maxIdle;
return this;
}
public AggregateBuilder Params(string name, string value)
{
_params.Add(name);
_params.Add(value);
return this;
}
public AggregateBuilder Dialect(int value)
{
_dialect = value;
return this;
}
}
public class AggregateReduce
{
public string Function { get; set; }
public object[] Arguments { get; set; }
public string Alias { get; set; }
}
}
|
2881099/IdleBus | 3,281 | readme.md | IdleBus 空闲对象管理容器,有效组织对象重复利用,自动创建、销毁,解决【实例】过多且长时间占用的问题。有时候想做一个单例对象重复使用提升性能,但是定义多了,有的又可能一直空闲着占用资源。
专门解决:又想重复利用,又想少占资源的场景。
## 快速开始
> dotnet add package IdleBus
```csharp
class Program
{
static void Main(string[] args)
{
//超过20秒没有使用,就销毁【实例】
var ib = new IdleBus(TimeSpan.FromSeconds(20));
ib.Notice += (_, e) =>
{
Console.WriteLine(" " + e.Log);
if (e.NoticeType == IdleBus<IDisposable>.NoticeType.AutoRelease)
Console.WriteLine($" [{DateTime.Now.ToString("g")}] {e.Key} 空闲被回收");
};
while (true)
{
Console.WriteLine("输入 > ");
var line = Console.ReadLine().Trim();
if (string.IsNullOrEmpty(line)) break;
// 注册
ib.TryRegister(line, () => new TestInfo());
// 第一次:创建
TestInfo item = ib.Get(line) as TestInfo;
// 第二次:直接获取,长驻内存直到空闲销毁
item = ib.Get(line) as TestInfo;
}
ib.Dispose();
}
class TestInfo : IDisposable
{
public void Dispose() { }
}
}
```
输出:
```shell
输入 >
aa1
aa1 注册成功,0/1
aa1 实例+++创建成功,耗时 0.1658ms,1/1
aa1 实例获取成功 1次
aa1 实例获取成功 2次
输入 >
aa2
aa2 注册成功,1/2
aa2 实例+++创建成功,耗时 0.0065ms,2/2
aa2 实例获取成功 1次
aa2 实例获取成功 2次
输入 >
aa3
aa3 注册成功,2/3
aa3 实例+++创建成功,耗时 0.0073ms,3/3
aa3 实例获取成功 1次
aa3 实例获取成功 2次
输入 >
aa1 ---自动释放成功,耗时 0.7607ms,2/3
[2020/1/7 14:22] aa1 空闲被回收
aa2 ---自动释放成功,耗时 0.0289ms,1/3
[2020/1/7 14:22] aa2 空闲被回收
aa3 ---自动释放成功,耗时 0.0046ms,0/3
[2020/1/7 14:22] aa3 空闲被回收
```
## API
new IdleBus 可使用任何 IDisposable 实现类【混合注入】
new IdleBus\<T\> 可【自定义类型】注入,如: new IdleBus\<IFreeSql\>()
| Method | 说明 |
| -- | -- |
| void Ctor() | 创建空闲容器 |
| void Ctor(TimeSpan idle) | 指定空闲时间,创建空闲容器 |
| IdleBus Register(string key, Func\<T\> create) | 注册(其类型必须实现 IDisposable) |
| IdleBus Register(string key, Func\<T\> create, TimeSpan idle) | 注册,单独设置空间时间 |
| T Get(string key) | 获取【实例】(线程安全),key 未注册时,抛出异常 |
| List\<T\> GetAll() | 获得所有【实例】(线程安全) |
| bool Exists(string key) | 判断 key 是否已注册 |
| void Remove(string key) | 删除已注册的 |
| int Quantity | 注册数量 |
| int UsageQuantity | 已创建【实例】数量 |
| event Notice | 容器内部的变化通知,如:自动释放、自动创建 |
> 注意:Register 参数 create 属于对象创建器,切莫直接返回外部创建好的对象
```csharp
var obj = new Xxx();
ib.Register("key01", () => obj); //错了,错了,错了
ib.Register("key01", () => new Xxx()); //正确
```
## 设计思路
IdleBus 和对象池不同,对象池是队列设计,我们是 KV 设计。
IdleBus 又像缓存,又像池,又像容器,无法具体描述。
1、注册:向容器中注册对象,指定 key + 创建器 + 空闲时间,可以注册和管理任何实现 IDisposable 接口对象
2、获取对象:开发人员使用 key 作为参数调用方法获得对象
- 存在时,直接返回
- 不存在时,创建对象(保证线程安全)
3、过期销毁:当容器中有实例运行,会启用后台线程定时检查,超过空闲时间设置的将被释放(Dispose)
## 使用场景
- 多租户按数据库区分的场景,假设有1000个租户;
- Redis 客户端需要操作 N 个 服务器;
- Socket 长连接闲置后自动释放;
- 管理 1000个 rabbitmq 服务器的客户端;
- [IdleScheduler](https://github.com/2881099/IdleBus/tree/master/IdleScheduler) 利用 IdleBus 实现的轻量定时任务调度;
- 等等等。。。
举例:向 1000个 (不同的、不同的、不同的) rabbitmq 服务器发送消息,正常有两种做法:
1、定义 1000 个静态 client 一直 open 着,重复利用
缺点:1000个里面不是每个都活跃,然后也一直占用着资源
2、每次发送消息的时候 open,使用完再 close
```csharp
new client("mq_0001server").pub(...).close();
new client("mq_0002server").pub(...).close();
new client("mq_0003server").pub(...).close();
new client("mq_0004server").pub(...).close();
```
缺点:性能损耗会比较大,socket 没有有效的重复利用
|
2881099/IdleBus | 4,696 | IdleBus/IdleBus.xml | <?xml version="1.0"?>
<doc>
<assembly>
<name>IdleBus</name>
</assembly>
<members>
<member name="T:IdleBus">
<summary>
空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
</summary>
</member>
<member name="M:IdleBus.#ctor">
<summary>
按空闲时间1分钟,创建空闲容器
</summary>
</member>
<member name="M:IdleBus.#ctor(System.TimeSpan)">
<summary>
指定空闲时间、创建空闲容器
</summary>
<param name="idle">空闲时间</param>
</member>
<member name="T:IdleBus`1">
<summary>
空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
</summary>
</member>
<member name="M:IdleBus`1.#ctor">
<summary>
按空闲时间1分钟,创建空闲容器
</summary>
</member>
<member name="M:IdleBus`1.#ctor(System.TimeSpan)">
<summary>
指定空闲时间、创建空闲容器
</summary>
<param name="idle">空闲时间</param>
</member>
<member name="T:IdleBus`2">
<summary>
空闲对象容器管理,可实现自动创建、销毁、扩张收缩,解决【实例】长时间占用问题
</summary>
</member>
<member name="M:IdleBus`2.#ctor">
<summary>
按空闲时间1分钟,创建空闲容器
</summary>
</member>
<member name="M:IdleBus`2.#ctor(System.TimeSpan)">
<summary>
指定空闲时间、创建空闲容器
</summary>
<param name="idle">空闲时间</param>
</member>
<member name="M:IdleBus`2.Get(`0)">
<summary>
根据 key 获得或创建【实例】(线程安全)<para></para>
key 未注册时,抛出异常
</summary>
<param name="key"></param>
<returns></returns>
</member>
<member name="M:IdleBus`2.GetAll">
<summary>
获得或创建所有【实例】(线程安全)
</summary>
<returns></returns>
</member>
<member name="M:IdleBus`2.GetKeys(System.Func{`1,System.Boolean})">
<summary>
获得所有已注册的 key(线程安全)
</summary>
<returns></returns>
</member>
<member name="M:IdleBus`2.Exists(`0)">
<summary>
判断 key 是否注册
</summary>
<param name="key"></param>
<returns></returns>
</member>
<member name="M:IdleBus`2.Register(`0,System.Func{`1})">
<summary>
注册【实例】
</summary>
<param name="key"></param>
<param name="create">实例创建方法</param>
<returns></returns>
</member>
<member name="P:IdleBus`2.UsageQuantity">
<summary>
已创建【实例】数量
</summary>
</member>
<member name="P:IdleBus`2.Quantity">
<summary>
注册数量
</summary>
</member>
<member name="E:IdleBus`2.Notice">
<summary>
通知事件
</summary>
</member>
<member name="F:IdleBus`2.NoticeType.Register">
<summary>
执行 Register 方法的时候
</summary>
</member>
<member name="F:IdleBus`2.NoticeType.Remove">
<summary>
执行 Remove 方法的时候,注意:实际会延时释放【实例】
</summary>
</member>
<member name="F:IdleBus`2.NoticeType.AutoCreate">
<summary>
自动创建【实例】的时候
</summary>
</member>
<member name="F:IdleBus`2.NoticeType.AutoRelease">
<summary>
自动释放不活跃【实例】的时候
</summary>
</member>
<member name="F:IdleBus`2.NoticeType.Get">
<summary>
获取【实例】的时候
</summary>
</member>
<member name="P:IdleBus`2.TimeoutScanOptions.Interval">
<summary>
扫描线程间隔(默认值:2秒)
</summary>
</member>
<member name="P:IdleBus`2.TimeoutScanOptions.QuitWaitSeconds">
<summary>
扫描线程空闲多少秒退出(默认值:10秒)
</summary>
</member>
<member name="P:IdleBus`2.TimeoutScanOptions.BatchQuantity">
<summary>
扫描的每批数量(默认值:512)<para></para>
可防止注册数量太多时导致 CPU 占用过高
</summary>
</member>
<member name="P:IdleBus`2.TimeoutScanOptions.BatchQuantityWait">
<summary>
达到扫描的每批数量时,线程等待(默认值:1秒)
</summary>
</member>
<member name="P:IdleBus`2.ScanOptions">
<summary>
扫描过期对象的设置<para></para>
机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。<para></para>
连续多少秒都没存活的对象时,才退出扫描。
</summary>
</member>
</members>
</doc>
|
2881099/IdleBus | 4,158 | IdleBus/IdleBus`1.ThreadScan.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
partial class IdleBus<TKey, TValue>
{
bool _threadStarted = false;
object _threadStartedLock = new object();
void ThreadScanWatch(ItemInfo item)
{
var startThread = false;
if (_threadStarted == false)
lock (_threadStartedLock)
if (_threadStarted == false)
startThread = _threadStarted = true;
if (startThread)
new Thread(() =>
{
this.ThreadScanWatchHandler();
lock (_threadStartedLock)
_threadStarted = false;
}).Start();
}
public class TimeoutScanOptions
{
/// <summary>
/// 扫描线程间隔(默认值:2秒)
/// </summary>
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(2);
/// <summary>
/// 扫描线程空闲多少秒退出(默认值:10秒)
/// </summary>
public int QuitWaitSeconds { get; set; } = 10;
/// <summary>
/// 扫描的每批数量(默认值:512)<para></para>
/// 可防止注册数量太多时导致 CPU 占用过高
/// </summary>
public int BatchQuantity { get; set; } = 512;
/// <summary>
/// 达到扫描的每批数量时,线程等待(默认值:1秒)
/// </summary>
public TimeSpan BatchQuantityWait { get; set; } = TimeSpan.FromSeconds(1);
}
/// <summary>
/// 扫描过期对象的设置<para></para>
/// 机制:当窗口里有存活对象时,扫描线程才会开启(只开启一个线程)。<para></para>
/// 连续多少秒都没存活的对象时,才退出扫描。
/// </summary>
public TimeoutScanOptions ScanOptions { get; } = new TimeoutScanOptions();
void ThreadScanWatchHandler()
{
var couter = 0;
while (IsDisposed == false)
{
if (ThreadJoin(ScanOptions.Interval) == false) return;
this.InternalRemoveDelayHandler();
if (_usageQuantity == 0)
{
couter = couter + (int)ScanOptions.Interval.TotalSeconds;
if (couter < ScanOptions.QuitWaitSeconds) continue;
break;
}
couter = 0;
var keys = _dic.Keys.ToArray();
long keysIndex = 0;
foreach (var key in keys)
{
if (IsDisposed) return;
++keysIndex;
if (ScanOptions.BatchQuantity > 0 && keysIndex % ScanOptions.BatchQuantity == 0)
{
if (ThreadJoin(ScanOptions.BatchQuantityWait) == false) return;
}
if (_dic.TryGetValue(key, out var item) == false) continue;
if (item.value == null) continue;
if (DateTime.Now.Subtract(item.lastActiveTime) <= item.idle) continue;
try
{
var now = DateTime.Now;
if (item.Release(() => DateTime.Now.Subtract(item.lastActiveTime) > item.idle && item.lastActiveTime >= item.createTime))
//防止并发有其他线程创建,最后活动时间 > 创建时间
this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, null, $"{key} ---自动释放成功,耗时 {DateTime.Now.Subtract(now).TotalMilliseconds}ms,{_usageQuantity}/{Quantity}"));
}
catch (Exception ex)
{
this.OnNotice(new NoticeEventArgs(NoticeType.AutoRelease, item.key, ex, $"{key} ---自动释放执行出错:{ex.Message}"));
}
}
}
}
bool ThreadJoin(TimeSpan interval)
{
if (interval <= TimeSpan.Zero) return true;
var milliseconds = interval.TotalMilliseconds;
var seconds = Math.Floor(milliseconds / 1000);
milliseconds = milliseconds - seconds * 1000;
for (var a = 0; a < seconds; a++)
{
Thread.CurrentThread.Join(TimeSpan.FromSeconds(1));
if (IsDisposed) return false;
}
for (var a = 0; a < milliseconds; a += 200)
{
Thread.CurrentThread.Join(TimeSpan.FromMilliseconds(200));
if (IsDisposed) return false;
}
return true;
}
} |
Subsets and Splits
PyTorch Neural Network Imports
This query filters for code examples containing a specific PyTorch import pattern, which is useful for finding code snippets that use PyTorch's neural network module but doesn't provide deeper analytical insights about the dataset.
HTML Files in Train Set
Retrieves all records from the dataset where the file path ends with .html or .htm, providing a basic filter for HTML files.
SQL Console for nick007x/github-code-2025
Retrieves 200 file paths that end with '.html' or '.htm', providing a basic overview of HTML files in the dataset.
Top HTML Files
The query retrieves a sample of HTML file paths, providing basic filtering but limited analytical value.
CSharp Repositories Excluding Unity
Retrieves all records for repositories that contain C# files but are not related to Unity, providing a basic filter of the dataset.
C# File Count per Repository
Counts the total number of C# files across distinct repositories, providing a basic measure of C# file presence.
SQL Console for nick007x/github-code-2025
Lists unique repository IDs containing C# files, providing basic filtering to understand which repositories have C# code.
Select Groovy Files: Train Set
Retrieves the first 1000 entries from the 'train' dataset where the file path ends with '.groovy', providing a basic sample of Groovy files.
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.