美文网首页Java 杂谈
自己动手写一个Redis客户端

自己动手写一个Redis客户端

作者: 我是杨正 | 来源:发表于2018-12-28 10:17 被阅读1次

    原文链接:https://www.dubby.cn/detail.html?id=9121

    使用JavaFX,不依赖任何其他依赖,实现的一个简单的Redis客户端,编写的初衷是觉得Redis Desktop Manager太难用,并且Redis的RESP比较简单,所以这里就尝试着写了下

    RESP

    REdis Serialization Protocol,这里给出官方的文档链接。为啥Redis要自己搞一套序列化协议,因为他们希望有这么一个协议:

    • 实现起来很简单
    • 转换起来很快
    • 人类容易阅读的

    一句话概括——简单

    RESP主要有这么几种类型:

    • 简单字符串,开头是 "+"
    • 错误信息,开头是 "-"
    • 数字,开头是 ":"
    • 大字符串(一般是二进制),开头是 "$"
    • 数组,开头是 "*"

    实现Redis客户端

    把command解析成Redis认识的byte[]:

    public class RedisCommandParser {
    
        private static final Charset charset = Charset.forName("UTF-8");
    
        public static byte[] parse(String inputCommand) throws IOException {
            if (StringUtil.isEmpty(inputCommand)) {
                inputCommand = RedisCommandConstant.PING;
            }
    
            inputCommand = inputCommand.trim();
    
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            stream.write(RESPConstant.ASTERISK_BYTE);
    
            String[] cmdSplit = inputCommand.split(" ");
            int length = 0;
            for (String str : cmdSplit) {
                if (!StringUtil.isEmpty(str)) {
                    length++;
                }
            }
            stream.write(intToByte(length));
            stream.write('\r');
            stream.write('\n');
    
            for (String str : cmdSplit) {
                if (StringUtil.isEmpty(str)) {
                    continue;
                }
                stream.write(RESPConstant.DOLLAR_BYTE);
                stream.write(intToByte(str.getBytes(charset).length));
                stream.write('\r');
                stream.write('\n');
                stream.write(str.getBytes(charset));
                stream.write('\r');
                stream.write('\n');
            }
    
            return stream.toByteArray();
        }
    
    
        private final static byte[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    
    
        private static byte[] intToByte(int i) {
            if (i <= 0) {
                return new byte[0];
            }
            if (i < 10) {
                byte[] bytes = new byte[1];
                bytes[0] = Digit[i];
                return bytes;
            }
            if (i < 100) {
                byte[] bytes = new byte[2];
                bytes[0] = Digit[i / 10];
                bytes[1] = Digit[i % 10];
                return bytes;
            }
            throw new InvalidParameterException("redis command too long");
        }
    
    }
    

    发送逻辑:

    Socket socket = new Socket();
    socket.setReuseAddress(true);
    socket.setKeepAlive(true);
    socket.setTcpNoDelay(true);
    socket.setSoLinger(true, 0);
    socket.connect(new InetSocketAddress(host, port), 10 * 1000);
    socket.setSoTimeout(10 * 1000);
    OutputStream outputStream = socket.getOutputStream();
    InputStream inputStream = socket.getInputStream();
    //AUTH password
    String authCmd = "AUTH " + password;
    byte[] authCmdBytes = RedisCommandParser.parse(authCmd);
    outputStream.write(authCmdBytes);
    outputStream.flush();
    byte[] bytes = new byte[102400];
    int length = inputStream.read(bytes);
    String authResult = new String(bytes, 0, length, charset);
    logger.info(authResult);
    //SELECT dbIndex
    String selectCmd = "SELECT " + dbIndex;
    byte[] selectCmdBytes = RedisCommandParser.parse(selectCmd);
    outputStream.write(selectCmdBytes);
    outputStream.flush();
    bytes = new byte[102400];
    length = inputStream.read(bytes);
    String selectResult = new String(bytes, 0, length, charset);
    logger.info(selectResult);
    //COMMAND
    byte[] commandBytes = RedisCommandParser.parse(command);
    outputStream.write(commandBytes);
    outputStream.flush();
    bytes = new byte[102400];
    length = inputStream.read(bytes);
    String result = new String(bytes, 0, length, charset);
    logger.info(String.format("\ncommand:\n%s\nresult:\n%s", new String(commandBytes, charset), result));
    

    考虑到这个主要用途是本地使用,所以没有使用长连接,因为我本人经常是打开Client就一直开着,但一般很少会用到,所以每次query都会新建一个socket连接

    最终效果

    image image image image image image

    源代码地址:https://github.com/dubby1994/redis-client

    相关文章

      网友评论

        本文标题:自己动手写一个Redis客户端

        本文链接:https://www.haomeiwen.com/subject/alqslqtx.html