10分钟就理解Redis序列化协议,你也能编写redis客户端( 七 )

{ @Override public String decode(ByteBuf buffer) { int lineEndIndex = CodecUtils.X.findLineEndIndex(buffer); if (-1 == lineEndIndex) { return null; } Long length = (Long) DefaultRespCodec.DECODERS.get(ReplyType.INTEGER).decode(buffer); if (null == length) { return null; } // Bulk Null String if (RespConstants.NEGATIVE_ONE.equals(length)) { return null; } // Bulk Empty String if (RespConstants.ZERO.equals(length)) { return RespConstants.EMPTY_STRING; } // 真实字节内容的长度 int readLength = (int) length.longValue(); if (buffer.readableBytes() > readLength) { byte[] bytes = new byte[readLength]; buffer.readBytes(bytes); // 重置读游标为rn之后的第一个字节 buffer.readerIndex(buffer.readerIndex() + 2); return new String(bytes, RespConstants.UTF_8); } return null; }}public class RespArrayDecoder implements RespDecoder { @Override public Object decode(ByteBuf buffer) { int lineEndIndex = CodecUtils.X.findLineEndIndex(buffer); if (-1 == lineEndIndex) { return null; } // 解析元素个数 Long length = (Long) DefaultRespCodec.DECODERS.get(ReplyType.INTEGER).decode(buffer); if (null == length) { return null; } // Null Array if (RespConstants.NEGATIVE_ONE.equals(length)) { return null; } // Array Empty List if (RespConstants.ZERO.equals(length)) { return Lists.newArrayList(); } List result = Lists.newArrayListWithCapacity((int) length.longValue()); // 递归 for (int i = 0; i < length; i++) { result.add(DefaultRespCodec.X.decode(buffer)); } return result; }}
作者:Throwable
链接:https://juejin.im/post/5d9dec2b6fb9a04e0a37edd5




推荐阅读