c#實現redis客戶端(一)

蘑菇先生發表於2015-01-12

  最近專案使用中要改造redis客戶端,看了下文件,總結分享一下。

閱讀目錄:

  1. 協議規範
  2. 基礎通訊
  3. 狀態命令
  4. set、get命令
  5. 管道、事務
  6. 總結

協議規範

redis允許客戶端以TCP方式連線,預設6379埠。傳輸資料都以\r\n結尾。

請求格式

*<number of arguments>\r\n$<number of bytes of argument 1>\r\n<argument data>\r\n

例:*1\r\n$4\r\nINFO\r\n

響應格式

1:簡單字串,非二進位制安全字串,一般是狀態回覆。  +開頭,例:+OK\r\n 

2: 錯誤資訊。          -開頭, 例:-ERR unknown command 'mush'\r\n

3: 整型數字。                            :開頭, 例::1\r\n

4:大塊回覆值,最大512M。           $開頭+資料長度。 例:$4\r\mush\r\n

5:多條回覆。                           *開頭, 例:*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n

基礎通訊

定義配置類:

public class Configuration
    {
        public string Host { get; set; }
        public int Port { get; set; }
        /// <summary>
        /// Socket 是否正在使用 Nagle 演算法。
        /// </summary>
        public bool NoDelaySocket { get; set; }

        public Configuration()
        {
            Host = "localhost";
            Port = 6379;
            NoDelaySocket = false;
        }
    }

實現socket連線:

 public class RedisBaseClient
    {
        //配置檔案
        private Configuration configuration;
        //通訊socket
        private Socket socket;
        //接收位元組陣列
        private byte[] ReceiveBuffer = new byte[100000];

        public RedisBaseClient(Configuration config)
        {
            configuration = config;
        }

        public RedisBaseClient()
            : this(new Configuration())
        {
        }

        public void Connect()
        {
            if (socket != null && socket.Connected)
                return;
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = configuration.NoDelaySocket
            };
            socket.Connect(configuration.Host, configuration.Port);
            if (socket.Connected)
                return;
            Close();
        }

        /// <summary>
        /// 關閉client
        /// </summary>
        public void Close()
        {
            socket.Disconnect(false);
            socket.Close();
        }
    }

呼叫:

RedisBaseClient redis = new RedisBaseClient();
redis.Connect();

服務端成功響應:

  

狀態命令

定義Redis命令列舉:

public enum RedisCommand
    {
        GET, //獲取一個key的值
        INFO, //Redis資訊。  
        SET, //新增一個值
        EXPIRE, //設定過期時間
        MULTI, //標記一個事務塊開始
        EXEC, //執行所有 MULTI 之後發的命令
    }

傳送命令構建:

  public string SendCommand(RedisCommand command, params string[] args)
        {
            //請求頭部格式, *<number of arguments>\r\n
            const string headstr = "*{0}\r\n";
            //引數資訊       $<number of bytes of argument N>\r\n<argument data>\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);
                Close();
                return ReadData();
            }
            catch (SocketException e)
            {
                Close();
            }
            return null;
        }
   private string ReadData()
        {
            var data = Encoding.UTF8.GetString(ReceiveBuffer);
            char c = data[0];
            //錯誤訊息檢查。
            if (c == '-') //異常處理。
                throw new Exception(data);
            //狀態回覆。
            if (c == '+')
                return data;
            return data;
        }

 呼叫:

 private void button1_Click(object sender, EventArgs e)
        {
            RedisBaseClient redis = new RedisBaseClient();
            var result = redis.SendCommand(RedisCommand.INFO);
            richTextBox1.Text = result;
        }

輸出響應,其$937是資料包的長度。

 

set、get命令

呼叫:

   private void button2_Click(object sender, EventArgs e)
        {
            RedisBaseClient redis = new RedisBaseClient();
            var result = redis.SendCommand(RedisCommand.SET, "msg", "testvalue");
            richTextBox1.Text = result.ToString();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            RedisBaseClient redis = new RedisBaseClient();
            var result = redis.SendCommand(RedisCommand.GET, "msg");
            richTextBox1.Text = result.ToString();
        }

輸出

管道、事務

 二者都是走MULTI,EXEC命令,原子操作。管道就是傳送命令(無需等上次命令回覆),進入命令佇列,然後多條命令一次執行,並返回客戶端結果。 

 平常使用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)
        {
            //請求頭部格式, *<number of arguments>\r\n
            const string headstr = "*{0}\r\n";
            //引數資訊       $<number of bytes of argument N>\r\n<argument data>\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連線池管理相較複雜些。

參考資源:

http://redis.io/topics/protocol

https://github.com/ServiceStack/ServiceStack.Redis

相關文章