Write Redis client by yourself (C # implementation) 2,
The general form of the Redis request protocol:
* <Parameter quantity> cr lf $ <parameter 1 byte quantity> cr lf <parameter 1 DATA> cr lf... $ <number of bytes of parameter N> cr lf <data of parameter N> CR LF
Note: CR indicates \ r; LF indicates \ n
The following is an example:
*3$3SET$5mykey$7myvalue
Redis reply
The Redis command returns multiple types of replies.
By checking the first byte of the data sent back by the server, you can determine the type of the response:
- The first byte of status reply is
"+"
- The first byte of error reply is
"-"
- The first byte of integer reply (integer reply) is
":"
- The first byte of bulk reply is
"$"
- The first byte of multiple bulk reply is
"*"
Implementation Code (C #)
1. Connect to Redis through Socket:
// Connect redisSocket s = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp); s. Connect ("127.0.0.1", 6379) through Socket );
2. send commands
String key = "SetKeyTest"; // set the keystring value = "Set value"; // set the value StringBuilder sbSend = new StringBuilder (); sbSend. append ("* 3 \ r \ n"); // number of parameters 3 string cmd = "SET"; sbSend. append ("$" + Encoding. UTF8.GetBytes (cmd ). length + "\ r \ n"); // The Length of parameter 1 sbSend. append (cmd + "\ r \ n"); // parameter 1 (SET command) sbSend. append ("$" + Encoding. UTF8.GetBytes (key ). length + "\ r \ n"); // The Length of parameter 2 sbSend. append ("" + key + "\ r \ n"); // parameter 2 (Set Value) sbSend. append ("$" + Encoding. UTF8.GetBytes (value ). length + "\ r \ n"); // The Length of parameter 3 sbSend. append ("" + value + "\ r \ n"); // parameter 3 (Set Value) Console. writeLine ("sent command:"); Console. write (sbSend. toString (); byte [] data = Encoding. UTF8.GetBytes (sbSend. toString (); // converts a request to a byte array
3. receive replies
Byte [] result = new byte [1024]; int resultLength = s. receive (result); // receives a response // reassembles a result byte [] newResult = new byte [resultLength] based on the received data length; for (int I = 0; I <resultLength; I ++) {newResult [I] = result [I];} string strResult = Encoding. UTF8.GetString (newResult); // convert the result to stringConsole. write (strResult); Console. write (strResult. trim () = "+ OK "? "Set successfully! ":" Setting failed! "); // Determines whether the setting is successful.
Execution result