NET Core simple and advanced library csredis

NET Core simple and advanced library csredis

Open source free redis package

最后更新 4/11/2021 9:50 AM
FreeSql & CSRedis
预计阅读 6 分钟
分类
.NET
标签
.NET C# open source Redis csredis

1 Introduction

NET Core has experienced ups and downs since its release in 1.0. At the beginning, various libraries were missing and now they are partially improved. It is not easy to get to today.

For example, the redis-cli SDK is simply a trap.

过去 .net 最有名望的 ServiceStack.Redis 早已沦为商业用途,在 .NETCore 中使用只能充值;后来居上的 StackExchange.Redis 虽然能用,但线上各种 Timeout 错误把人坑到没脾气,两年多都不解决,最近发布的 2.0 版本不知道是否彻底解决了底层。

2 csredis v3.0.0 update

  1. Keep all method names consistent with redis-cli;

It is understood that the java/python/go/nodejs/php SDK method names are basically the same as redis-cli, and are opposed to secondary-named libraries.

  1. Add anti-serial object acquisition, such as Get<byte[]>, HGet<byte[]>, all acquisition methods are overloaded, and the default acquisition is still string;

  2. Introduction and use of SafeObjectPool;

3 uses

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 gameplay: zoning

In reality, multiple service nodes share storage, which is different from official zoning, clustering, and high availability solutions.

For example, if cached data reaches 500G, it will be very difficult to store it in memory alone if you use a redis-server, and using a hard disk will affect performance.

You can use this function to automatically manage N redis-server servers to share storage. Each server only requires about (500/N)G of memory, and each server can be configured with the official highly available 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 gameplay: Publish subscriptions

//普通订阅
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 gameplay: 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 package multiple commands for execution together to improve 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 gameplay: Multiple databases

If you are sure that there is a need to switch databases, please 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 competition

10 Ending

Still support open source, thank you for watching!

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

Author of this article: FreeSql & CSRedis

Link to this article: www.cnblogs.com/kellynic/p/9803314.html

About bloggers: Comments and private messages will be responded to as soon as possible. Or directly send me a message privately.

Copyright Statement: Except for special announcements, all articles in this blog adopt the BY-NC-SA license agreement. Please indicate the source of the reprint!

Support bloggers: If you think the article is helpful to you, you can click on [Recommendation] in the lower right corner of the article. Your encouragement is the biggest motivation for bloggers!

Keep Exploring

延伸阅读

更多文章
同分类 / 同标签 3/21/2024

Microsoft opens a job for Redis, which earns hundreds of millions of dollars in annual revenue? Garnet, which is far ahead in open source performance: No modification, Redis client can directly access it

Recently, Microsoft officially opened source cache storage system Garnet. According to Badrish Chandramouli, senior principal researcher in the Microsoft Research Database Group, the Garnet project was built from scratch and has performance as its core considerations (especially thread scalability in throughput and a higher proportion of low latency levels).

继续阅读
同分类 / 同标签 4/22/2026

Support for. NET by operating system versions (250707 update)

Use virtual machines and test machines to test the support of each version of the operating system for. NET. After installing the operating system, it is passed by measuring the corresponding running time of the installation and being able to run the Stardust Agent.

继续阅读