. net redis client open source component freeredis (rewritten after csrediscore)

nicye 2020-11-08 19:06:03
redis client open source component


What is? FreeRedis

FreeRedis Is a .NET redis Client open source components , With MIT The open source protocol is hosted in github, At present, we support .NET 5、.NETCore 2.1+、.NETFramework 4.0+、Xamarin, It may have supported AOT compile ( It's not currently tested , But it will go in this direction ).

FreeRedis Will strictly follow FreeSql Open source way of , Do unit test well , Compatible platforms , Simple and easy to use , Have a craigslist , Be responsive to what you want , For China .NET Open source cause to make a little contribution .

Thank you for your support , The project has been obtained before it has been made public 66 star . The project is still in its infancy , Welcome to join us , Contribution test 、 Or code 、 Or suggest it .

The current status of the project :

  • edition 0.0.8( It is not recommended for use in production environments at present )
  • unit testing 268 individual
  • Support colony 、 sentry 、 Master-slave ( Test passed )
  • Support Connection pool
  • Support .NET5/.NETCore 2.1+/.NET4.0+
  • Support Redis6.0 All types
  • Support Redis6.0 RESP3 agreement
  • API Still with redis-cli The orders are consistent
  • Adopt the most relaxed open source protocol MIT https://github.com/2881099/FreeRedis

The origin of the project

it's a long story ,2016 I wrote more than a year ago nodejs Server applications , Have used node-redis Components , Sincere and easy to use . During this period, some colleagues kept Amway .NET It's cross platform , Tell me to come back soon .NET, At first I resisted being the first crab , I don't know which afternoon I went to experience the pain of eggs .NETCore 1.0-previewXX( I don't remember which version ). Tried one and was attracted to , Experience feelings and expressjs It's like , Never see the past again webform/mvc The shortcomings of .

So I'm ready to go into the pit , The first thing to do in the pit is hello world, We need to do some research :

  • performance OK
  • Design OK
  • Development OK( Temporary grading )
  • Related components OK(HttpClient、Redis、Ado.NET、 And so on, the basic components )

After the initial research is completed , The next step is to take time to select the framework , Finally, one of the right teams was chosen from many frameworks :https://github.com/simplcommerce/SimplCommerce , Based on the original project , According to the requirements of enterprise standard, we can customize and transform , It took about two months to complete the producible state .( The framework doesn't start to be perfect , Just keep polishing in use , And finally to perfection )

The ideal is full, the reality backbone , The next story is a production failure ,StackExchange.Redis、HttpClient Questions about these two components , I said it before, but I don't want to talk about it now ( I didn't expect that there would be problems with such a large component ). If you eat crab, you will fall into the pit , If you fall into a hole, you have to find a way to solve it , Finally with csredis Components are bound together .

Take a general view of the situation at that time .NET all redis Client component , Only csredis Source code is the easiest to transform and support .NETCore( Limited level. Sorry ),csredis 2014 Stop updating in , I am on 2016 It was transformed to support .NETCore Mainly , And add connection pool management 、 colony 、 sentry 、redis2.8 The above order , After one and a half years of using the production environment of the company's project, open source .

CSRedisCore Open source has been going on for a long time ,nuget Download volume reached 60W, Collect a number of requirements ,bug A number of ( There's a solution 、 There are also those that have not been reproduced ), Based on what I've done to redis This one is very familiar , then redis 5.0/6.0 A lot of new features have been added , Write a new one bug less 、 The idea of better maintainability came into being .

After a few months of ink, it is finally available , The project was finally named :FreeRedis


How to use

Single machine redis ( stand-alone )

public static RedisClient cli = new RedisClient("127.0.0.1:6379,password=123,defaultDatabase=13");
//cli.Serialize = obj => JsonConvert.SerializeObject(obj);
//cli.Deserialize = (json, type) => JsonConvert.DeserializeObject(json, type);
cli.Notice += (s, e) => Console.WriteLine(e.Log); //print command log
cli.Set("key1", "value1");
cli.MSet("key1", "value1", "key2", "value2");
string value1 = cli.Get("key1");
string[] vals = cli.MGet("key1", "key2");

API Still with redis-cli The orders are consistent , So if you want to understand FreeRedis How to use each method , Go to Baidu search “redis command ”, There's a lot, a lot of information .don't say so much!!!

Support Redis6.0 All supported data types :strings, hashes, lists, sets, sorted sets, bitmaps, hyperloglogs, geo, streams And BloomFilter.

Parameter Default Explain
protocol RESP2 If you use RESP3, you need redis 6.0 environment
user <empty> Redis server username, requires redis-server 6.0
password <empty> Redis server password
defaultDatabase 0 Redis server database
max poolsize 100 Connection max pool size
min poolsize 5 Connection min pool size
idleTimeout 20000 Idle time of elements in the connection pool (MS)
connectTimeout 10000 Connection timeout (MS)
receiveTimeout 10000 Receive timeout (MS)
sendTimeout 10000 Send timeout (MS)
encoding utf-8 string charset
ssl false Enable encrypted transmission
name <empty> Connection name, use client list command to view

If you need to connect IPv6, Please use : [fe80::b164:55b3:4b4f:7ce6%15]:6379


Master-Slave ( Read / write separation )

public static RedisClient cli = new RedisClient(
"127.0.0.1:6379,password=123,defaultDatabase=13",
"127.0.0.1:6380,password=123,defaultDatabase=13",
"127.0.0.1:6381,password=123,defaultDatabase=13"
);
var value = cli.Get("key1");

Created in this way cli, All write commands are connected to 127.0.0.1:6379 perform , All read commands are only randomly connected 127.0.0.1:6380 or 127.0.0.1:6381 perform .( Internally, each command has been marked for read and write )

Redis Sentinel ( Sentinel high availability )

public static RedisClient cli = new RedisClient(
"mymaster,password=123",
new [] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" },
true // Whether reading and writing are separated
);

Sentinel is a distributed system , by Redis Provide high availability solutions , When the host master After downtime , There's going to be a new master You can use , Make sure the service is working properly .

Sentinel mode can also set read-write separation , relieve master The pressure to read data frequently , shortcoming : It's possible that the data you read is not up to date , because redis from master Synchronize to slave There is a delay .

Redis Cluster ( colony )

If you have one Redis Cluster colony , There are three master nodes (7001-7003)、 Three slave nodes (7004-7006), Then the code connecting to this cluster :

public static RedisClient cli = new RedisClient(
new ConnectionStringBuilder[] { "192.168.0.2:7001", "192.168.0.2:7001", "192.168.0.2:7003" }
);

Subscribe ( subscribe )

using (cli.Subscribe("abc", ondata)) //wait .Dispose()
{
Console.ReadKey();
}
void ondata(string channel, string data) =>
Console.WriteLine($"{channel} -> {data}");

Scripting ( Script )

var r1 = cli.Eval("return {KEYS[1],KEYS[2],ARGV[1],ARGV[2]}",
new[] { "key1", "key2" }, "first", "second") as object[];
var r2 = cli.Eval("return {1,2,{3,'Hello World!'}}") as object[];
cli.Eval("return redis.call('set',KEYS[1],'bar')",
new[] { Guid.NewGuid().ToString() })

Pipeline ( The Conduit )

using (var pipe = cli.StartPipe())
{
pipe.IncrBy("key1", 10);
pipe.Set("key2", Null);
pipe.Get("key1");
object[] ret = pipe.EndPipe();
Console.WriteLine(ret[0] + ", " + ret[2]);
}
// or Async Callback
using (var pipe = cli.StartPipe())
{
var tasks = new List<Task>();
long t0 = 0;
task.Add(pipe.IncrByAsync("key1", 10).ContinueWith(t => t0 = t.Result)); //callback
pipe.SetAsync("key2", Null);
string t2 = null;
task.Add(pipe.GetAsync("key1").ContinueWith(t => t2 = t.Result)); //callback
pipe.EndPipe();
Task.WaitAll(tasks.ToArray()); //wait all callback
Console.WriteLine(t0 + ", " + t2);
}

Transaction ( Business )

using (var tran = cli.Multi())
{
tran.IncrBy("key1", 10);
tran.Set("key2", Null);
tran.Get("key1");
object[] ret = tran.Exec();
Console.WriteLine(ret[0] + ", " + ret[2]);
}
// or Async Callback
using (var tran = cli.Multi())
{
var tasks = new List<Task>();
long t0 = 0;
task.Add(tran.IncrByAsync("key1", 10).ContinueWith(t => t0 = t.Result)); //callback
tran.SetAsync("key2", Null);
string t2 = null;
task.Add(tran.GetAsync("key1").ContinueWith(t => t2 = t.Result)); //callback
tran.Exec();
Task.WaitAll(tasks.ToArray()); //wait all callback
Console.WriteLine(t0 + ", " + t2);
}

GetDatabase ( Cheku )

using (var db = cli.GetDatabase(10))
{
db.Set("key1", 10);
var val1 = db.Get("key1");
}

Conclusion

The project is still in its infancy , Welcome to join us , Contribution test 、 Or code 、 Or suggest it .

FreeRedis Use the loosest open source protocol MIT https://github.com/2881099/FreeRedis

If you have good redis Realize the idea , Welcome to leave a message for the author to discuss , Thank you for watching !

版权声明
本文为[nicye]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云