JSON

c#实现redis客户端(一)(2)

字号+ 作者:H5之家 来源:H5之家 2017-08-04 17:06 我要评论( )

平常使用ServiceStack.Redis客户端都直接set了,其实是set、expire 2个命令。 简单实现如下: public void CreatePipeline(){SendCommand(RedisCommand.MULTI, new string[] {}, true);}public string EnqueueComma

平常使用ServiceStack.Redis客户端都直接set了,其实是set、expire 2个命令。 简单实现如下:

复制代码

public void CreatePipeline() { SendCommand(RedisCommand.MULTI, new string[] {}, true); } public string EnqueueCommand(RedisCommand command, params string[] args) { return SendCommand(command, args, true); } public string FlushPipeline() { var result = SendCommand(RedisCommand.EXEC, new string[] {}, true); Close(); return result; } public string SendCommand(RedisCommand command, string[] args, bool isPipeline=false) { //请求头部格式, *\r\n const string headstr = "*{0}\r\n"; //参数信息 $\r\n\r\n const string bulkstr = "${0}\r\n{1}\r\n"; var sb = new StringBuilder(); sb.AppendFormat(headstr, args.Length + 1); var cmd = command.ToString(); sb.AppendFormat(bulkstr, cmd.Length, cmd); foreach (var arg in args) { sb.AppendFormat(bulkstr, arg.Length, arg); } byte[] c = Encoding.UTF8.GetBytes(sb.ToString()); try { Connect(); socket.Send(c); socket.Receive(ReceiveBuffer); if (!isPipeline) { Close(); } return ReadData(); } catch (SocketException e) { Close(); } return null; } public string SetByPipeline(string key, string value, int second) { this.CreatePipeline(); this.EnqueueCommand(RedisCommand.SET, key, value); this.EnqueueCommand(RedisCommand.EXPIRE, key, second.ToString()); return this.FlushPipeline(); }

复制代码

调用:

private void button4_Click(object sender, EventArgs e) { RedisBaseClient redis = new RedisBaseClient(); richTextBox1.Text = redis.SetByPipeline("cnblogs", "mushroom", 1000); }

输出:

*2 表示2条回复。

+2 表示命令执行OK。

:1 表示命令执行的结果

总结

本文只是简单的实现,有兴趣的同学,可以继续下去。

客户端实现这块,Socket连接池管理相较复杂些。

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • jsonP格式接口实现

    jsonP格式接口实现

    2017-08-01 11:00

  • php获取post中的json数据的实现方法

    php获取post中的json数据的实现方法

    2017-07-25 18:03

  • JSON解析器--实现代码

    JSON解析器--实现代码

    2017-07-15 16:00

  • 树形结构JSON的实现方法

    树形结构JSON的实现方法

    2017-07-10 14:00

网友点评
i