平常使用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连接池管理相较复杂些。