为什么做Redis Client?

Redis Client顾名思义,redis的客户端,主要是封装了一些对于Redis的操作。

而目前用的比较广泛的 ServiceStack.Redis 不学好,居然开始收费了。

作为轮子狂魔,是可忍孰不可忍啊。于是我决定自己造轮子了。

 

Redis通信协议

先给个Redis官方的通信协议地址:http://redisdoc.com/topic/protocol.html

【轮子狂魔】手把手教你自造Redis Client

关键是我截图的部分,我们可以得到以下几个信息:

1.tcp协议

2.默认端口6379

3.命令以 \r\n 结尾

 

实现Redis交互(Get、Set)

Set命令说明:http://redisdoc.com/string/set.html

Get命令说明:http://redisdoc.com/string/get.html

C#的Tcp交互选用TcpClient

 

  实现Set指令

 代码意图大概说一下:

1.创建TcpClient

2.连接Redis (127.0.0.1:6379)

3.发送指令 set test csharp\r\n (注意\r\n是一开始通信协议就提到的,命令以\r\n结尾)

4.使用UTF8来编码和解码

5.接收返回信息

PS:get指令类似,我就不贴出来了

 1             var tcpClient = new System.Net.Sockets.TcpClient();
 2 
 3             tcpClient.Connect("127.0.0.1", 6379);
 4 
 5             string setCommand = "set test csharp\r\n";
 6             tcpClient.Client.Send(Encoding.UTF8.GetBytes(setCommand));
 7             System.Diagnostics.Trace.Write(setCommand);
 8             byte[] buffer = new byte[256];
 9             tcpClient.Client.Receive(buffer);
10             System.Diagnostics.Trace.Write(Encoding.UTF8.GetString(buffer).Replace("\0", ""));    
View Code

相关文章:

  • 2022-01-30
  • 2021-09-12
  • 2021-12-06
  • 2021-12-31
  • 2021-11-07
  • 2022-12-23
  • 2021-04-01
  • 2021-07-13
猜你喜欢
  • 2022-02-09
  • 2021-12-10
  • 2021-06-27
  • 2022-01-07
  • 2021-10-08
  • 2021-10-29
  • 2021-11-27
相关资源
相似解决方案