How to write an entry-level redis client

Overview

Redis is an open source, in-memory data structure storage system that can be used as a database, cache, and message broker. Redis supports many kinds of data structures, and has built-in rich functions such as redundancy, scripting, transaction, persistence, etc. It is deeply loved by the industry and is widely used by various business systems. For ease of use, the Redis official website recommends a variety of clients for various programming languages, supporting mainstream programming languages ​​such as java, c#, python, and c++. So people will ask, since the Redis client is so rich, why try to write the client yourself? My opinion is that knowing yourself and the enemy and trying to make a Redis client yourself can not only deepen your understanding of Redis, but also understand the principles of Redis client, and be fully prepared for better use of Redis in the future, and even customization and transformation of Redis.

Knowledge preparation

To develop the Redis client by yourself, you need the following knowledge:
1. Network programming foundation
2. Familiar with the Redis protocol
3. Understand the basic operation of Redis
In addition , the examples in this article will be written in java, so it is best to have basic java programming knowledge.

object oriented

Redis Protocal

The Redis protocol is called: RESP (REdis Serialization Protocol), and the client connects to the client's port 6379 (default port) through the TCP protocol.
The RESP protocol was introduced in Redis 1.2, but it is now the standard protocol in Redis 2.0. So you should implement this protocol in your Redis client.

RESP description

RESP is actually a serialization protocol that supports simple strings, errors, integers, whole strings, and arrays. The data type depends on the header text, which are represented as follows:
the header text of a simple string is "+"
, the header text of an error is "-"
, the header text of an integer is ":"
The header text of a whole string is the head of
an array of "$" The text is "*"

The usage of RESP in the request-response model

- The client sends a command to the Redis server, the format of the command is an array consisting of only RESP whole strings. .
- The server selects an appropriate RESP type to return according to the result of the command

Simple Strings
Simple strings start with a half-width plus sign, followed by a string without CRLF, and then ended with a CRLF.
For example: +OK\r\nSimple
strings are not binary safe, if you need binary security, you can use "full string".

Errors
Errors are similar to simple strings, but the header is replaced with a half-width minus sign. The text that follows can be regarded as the content of the error message.
An example is as follows:

-ERR unknown command 'foobar'
-WRONGTYPE Operation against a key holding the wrong kind of value

Integers
Integers are similar to simple strings, with a colon as the header.
An example is as follows:

:0\r\n
:1000\r\n

Block strings
Block strings can be used to denote binary-safe strings up to 512MB in length. It starts with a $ sign, followed by the actual string length, ends with a carriage return line feed, followed by the actual string, and finally ends with a carriage return line feed.
An example is as follows:

$6\r\nfoobar\r\n
空字符串表现形式如下:$0\r\n\r\n
nil表现形式如下:$-1\r\n\r\n

Arrays
Arrays start with an asterisk, followed by the number of elements in the array, then end with a carriage return and line feed, followed by each element.
An example is as follows:

空数组:*0\r\n
包含两个整块字符串的数组:*2\r\n$3\r\nfoo\r\n$3\r\nbar\r\n
包含三个整数的数组:*3\r\n:1\r\n:2\r\n:3\r\n

Redis client code implementation

To communicate with the Redis server, you first need to establish a TCP communication connection with the Redis server, and then use the above RESP protocol to send the Redis command you want to execute to the server, wait for the server to respond, and then receive the response. displayed to the user.

The following code implements a simple operation to get info.

public class App 
{
    public static void main( String[] args )
    {
        //定义redis服务端默认端口
        int port = 6379;

        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            //创建tcp连接
            socket = new Socket("localhost", port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);

            //传送info命令
            //客户端向Redis服务器发送命令,以RESP整块字符串数组的形式
            out.println("*1\r\n$4\r\ninfo\r\n");
            System.out.println("Redis command wat sent successfully.");

            //接收服务器的回复
            CharBuffer response = CharBuffer.allocate(1024);
            int readedLen = in.read(response);
            String responseBody = response.flip().toString();

            //输出服务器的回复
            System.out.println(responseBody);

        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            //最后关闭相关的流
            if (out != null){
                out.close();
                out = null;
            }

            if (in != null) {
                try {
                    in.close();
                }
                catch(IOException e){
                    e.printStackTrace();
                }

                in = null;
            }

            if (socket != null) {
                try {
                    socket.close();
                }
                catch(IOException e){
                    e.printStackTrace();
                }

                socket = null;
            }
        }
    }
}

After running, the system will output the execution result of info on the command line interface.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325774770&siteId=291194637