.NET Core Simple and Advanced Library csredis

.NET Core Simple and Advanced Library csredis

Open source free Redis package

Last updated 4/11/2021 9:50 AM
FreeSql & CSRedis
6 min read
Category
.NET
Tags
.NET C# Open Source Redis csredis

1 Preface

The release of .NET Core 1.0 has gone through many hardships, from the initial lack of libraries to the current partial completeness. It has not been easy to get to where it is today.

For example, the redis-cli SDK has endless pitfalls.

In the past, the most famous .NET ServiceStack.Redis had already become commercial; using it in .NET Core required payment. The later StackExchange.Redis, although usable, caused various Timeout errors online that left developers frustrated, and the issue remained unresolved for over two years. Whether the recently released version 2.0 has completely solved the underlying problems remains unknown.

2 csredis v3.0.0 Update

  1. All method names are consistent with redis-cli;

    It is understood that method names in java/python/go/nodejs/php SDKs are basically the same as those in redis-cli. Libraries that rename methods are opposed.

  2. Added deserialized object retrieval, e.g., Get<byte[]>, HGet<byte[]>. All get methods are overloaded, and the default retrieval is still string.

  3. Introduction and use of SafeObjectPool.

3 Usage

nuget Install-Package CSRedisCore
var rds = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=13,poolsize=50,ssl=false,writeBuffer=10240,prefix=key前辍");
rds.Set("test1", "123123", 60);
rds.Get("test1");
//函数名与 redis-cli 的命令相同,rds 一定是单例单例单例

4 Advanced Play: Partitioning

Realize shared storage among multiple service nodes, different from official partitioning, clustering, and high-availability solutions.

For example: If cached data reaches 500G, using a single redis-server with only memory storage would be very difficult, and using hard disks affects performance.

This feature can automatically manage N redis-server nodes to share storage, with each node requiring approximately (500/N)G of memory, and each node can be configured with an official high-availability architecture.

var rds = new CSRedis.CSRedisClient(null,
  "127.0.0.1:6371,password=123,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍",
  "127.0.0.1:6372,password=123,defaultDatabase=12,poolsize=11,ssl=false,writeBuffer=10240,prefix=key前辍",
  "127.0.0.1:6373,password=123,defaultDatabase=13,poolsize=12,ssl=false,writeBuffer=10240,prefix=key前辍",
  "127.0.0.1:6374,password=123,defaultDatabase=14,poolsize=13,ssl=false,writeBuffer=10240,prefix=key前辍");
//实现思路:根据key.GetHashCode() % 节点总数量,确定连向的节点
//也可以自定义规则(第一个参数设置)

rds.MSet("key1", 1, "key2", 2, "key3", 3, "key4", 4);
rds.MGet("key1", "key2", "key3", "key4");

5 Advanced Play: Publish & Subscribe

//普通订阅
rds.Subscribe(
  ("chan1", msg => Console.WriteLine(msg.Body)),
  ("chan2", msg => Console.WriteLine(msg.Body)));

//模式订阅(通配符)
rds.PSubscribe(new[] { "test*", "*test001", "test*002" }, msg => {
  Console.WriteLine($"PSUB   {msg.MessageId}:{msg.Body}    {msg.Pattern}: chan:{msg.Channel}");
});
//模式订阅已经解决的难题:
//1、分区的节点匹配规则,导致通配符最大可能匹配全部节点,所以全部节点都要订阅
//2、本组 "test*", "*test001", "test*002" 订阅全部节点时,需要解决同一条消息不可执行多次

//发布
rds.Publish("chan1", "123123123");
//无论是分区或普通模式,rds.Publish 都可以正常通信

6 Advanced Play: Cache Shell

//不加缓存的时候,要从数据库查询
var t1 = Test.Select.WhereId(1).ToOne();

//一般的缓存代码,如不封装还挺繁琐的
var cacheValue = rds.Get("test1");
if (!string.IsNullOrEmpty(cacheValue)) {
	try {
		return JsonConvert.DeserializeObject(cacheValue);
	} catch {
		//出错时删除key
		rds.Remove("test1");
		throw;
	}
}
var t1 = Test.Select.WhereId(1).ToOne();
rds.Set("test1", JsonConvert.SerializeObject(t1), 10); //缓存10秒

//使用缓存壳效果同上,以下示例使用 string 和 hash 缓存数据
var t1 = rds.CacheShell("test1", 10, () => Test.Select.WhereId(1).ToOne());
var t2 = rds.CacheShell("test", "1", 10, () => Test.Select.WhereId(1).ToOne());
var t3 = rds.CacheShell("test", new [] { "1", "2" }, 10, notCacheFields => new [] {
  ("1", Test.Select.WhereId(1).ToOne()),
  ("2", Test.Select.WhereId(2).ToOne())
});

7 Advanced Play: Pipeline

Use pipeline mode to batch multiple commands together for improved performance.

var ret1 = rds.StartPipe().Set("a", "1").Get("a").EndPipe();
var ret2 = rds.StartPipe(p => p.Set("a", "1").Get("a"));

var ret3 = rds.StartPipe().Get("b").Get("a").Get("a").EndPipe();
//与 rds.MGet("b", "a", "a") 性能相比,经测试差之毫厘

8 Advanced Play: Multiple Databases

If you absolutely must have the need to switch databases, see the following code:

var connectionString = "127.0.0.1:6379,password=123,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍";
var redis = new CSRedisClient[14]; //定义成单例
for (var a = 0; a< redis.Length; a++) redis[a] = new CSRedisClient(connectionString + "; defualtDatabase=" + a);

//访问数据库1的数据
redis[1].Get("test1");

9 Performance Comparison

10 Conclusion

Still supporting open source, thank you for watching!

csredis source code: https://github.com/2881099/csredis

Author: FreeSql & CSRedis

Link: https://www.cnblogs.com/kellynic/p/9803314.html

About the blogger: Comments and private messages will be replied to as soon as possible. You can also send me a direct message.

Copyright: All articles in this blog are licensed under the BY-NC-SA license unless otherwise stated. Please indicate the source when reprinting!

Support the blogger: If you find the article helpful, you can click [Recommend] at the bottom right corner of the article. Your encouragement is the blogger's greatest motivation!

Keep Exploring

Related Reading

More Articles
Same category / Same tag 3/21/2024

Microsoft Goes After Redis' Multi-Hundred Million Dollar Revenue? Open-Source Garnet Outperforms: No Modifications Needed, Redis Clients Can Connect Directly

Recently, Microsoft officially open-sourced the cache storage system Garnet. According to Badrish Chandramouli, Senior Principal Researcher at Microsoft Research's database group, the Garnet project was built from scratch with performance as a core consideration (especially thread scalability in throughput and a higher proportion of low latency).

Continue Reading