[Netty ]自己实现一个redis客户端难吗?

x33g5p2x  于2022-04-21 转载在 Redis  
字(3.5k)|赞(0)|评价(0)|浏览(750)

Netty:模拟Redis的客户端

因为redis是部署在服务器上的 我们只需要模拟客户端发送请求即可所以只需要编写客户端的代码就可以了
前置知识

编写前我们需要知道 redis的请求规范

Redis 的通信 是需要遵循 RESP 协议的
例子:

  1. set hello 123
  2. *3\r\n $3 \r\n set \r\n hello \r\n 123

建立 channel 通道后 发送命令给服务端 此时是写数据【输出】 在出战handler里增加逻辑 当接受响应后 此时数据需要【输入】 存入栈 handler 中 在入栈handler 里增加逻辑

Netty中 Redis 命令对应的类型

  • 单行
  • 错误
  • 整形数字
  • 批量回复
  • 多个批量回复

客户端

我们只需要编写客户端。请求搭建redis的服务器接受和传输数据即可就可以了

客户端还是常见的写法

  1. public class RedisClient {
  2. private static final String HOST = "xxxxxxxxx";
  3. private static final int PORT = 6379;
  4. public static void main(String[] args) {
  5. NioEventLoopGroup bossGroup = new NioEventLoopGroup();
  6. Bootstrap bootstrap = new Bootstrap();
  7. bootstrap.group(bossGroup)
  8. .channel(NioSocketChannel.class)
  9. .handler(new ChannelInitializer<SocketChannel>() {
  10. @Override
  11. protected void initChannel(SocketChannel socketChannel) throws Exception {
  12. // 调用netty 提供的支持netty 协议的编解码器
  13. // RedisBulkStringAggregator 和 RedisarrayAggregator 是协议中两种特殊格式的聚合器
  14. ChannelPipeline pipeline = socketChannel.pipeline();
  15. pipeline.addLast(new RedisDecoder());
  16. pipeline.addLast(new RedisBulkStringAggregator());
  17. pipeline.addLast(new RedisArrayAggregator());
  18. pipeline.addLast(new RedisEncoder());
  19. // 我们自己的处理器
  20. pipeline.addLast(new RedisClientHandler());
  21. }
  22. });
  23. try {
  24. ChannelFuture syncFuture = bootstrap.connect(HOST, PORT).sync();
  25. System.out.println("enter redis commands");
  26. BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
  27. for (; ; ) {
  28. String input = bufferedReader.readLine();
  29. //退出任务
  30. if ("quit".equals(input)) {
  31. syncFuture.channel().close().sync();
  32. break;
  33. }
  34. syncFuture.channel().writeAndFlush(input).sync();
  35. }
  36. syncFuture.channel().closeFuture().sync();
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. } finally {
  40. bossGroup.shutdownGracefully();
  41. }
  42. }
  43. }
处理器

因为要读取和写入 所以我们需要集成混合处理器类 : ChannelDuplexHandler

我们需要判断五种请求类型 所以先封装一个类别输出的方法

RedisMessage Netty提供的redis的信息对象,以下五种类型都来自于它

  1. private void printRedisResponse(RedisMessage msg) {
  2. if (msg instanceof SimpleStringRedisMessage) {
  3. SimpleStringRedisMessage tmpMsg = (SimpleStringRedisMessage) msg;
  4. System.out.println(tmpMsg.content());
  5. } else if (msg instanceof ErrorRedisMessage) {
  6. ErrorRedisMessage tmpMsg = (ErrorRedisMessage) msg;
  7. System.out.println(tmpMsg.content());
  8. } else if (msg instanceof IntegerRedisMessage) {
  9. IntegerRedisMessage tmpMsg = (IntegerRedisMessage) msg;
  10. System.out.println(tmpMsg.value());
  11. } else if (msg instanceof FullBulkStringRedisMessage) {
  12. FullBulkStringRedisMessage tmpMsg = (FullBulkStringRedisMessage) msg;
  13. if (tmpMsg.isNull()) {
  14. return;
  15. }
  16. System.out.println(tmpMsg.content().toString(CharsetUtil.UTF_8));
  17. } else if (msg instanceof ArrayRedisMessage) {
  18. ArrayRedisMessage tmpMsg = (ArrayRedisMessage) msg;
  19. for (RedisMessage child : tmpMsg.children()) {
  20. printRedisResponse(child);
  21. }
  22. }
  23. // 如果都是不是应该抛出异常
  24. }

写命令

  1. // 写
  2. // 出栈handler 的常用方法
  3. //需要处理redis 命令
  4. @Override
  5. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
  6. // 键盘传入的字符串 如 : keys *
  7. String commandStr = (String) msg;
  8. // 通过空格来分离出命令
  9. String[] commandArr = commandStr.split("\\s+");
  10. // 接受redis 命令的列表 RedisMessag保存命令的内容
  11. List<RedisMessage> redisMessageList = new ArrayList<>(commandArr.length);
  12. for (String cmdStr : commandArr) {
  13. FullBulkStringRedisMessage message = new FullBulkStringRedisMessage(
  14. ByteBufUtil.writeUtf8(ctx.alloc(), cmdStr));
  15. redisMessageList.add(message);
  16. }
  17. //将分离的命令 合并成一个完整的命令
  18. RedisMessage request = new ArrayRedisMessage(redisMessageList);
  19. //写入通道
  20. ctx.write(request, promise);
  21. }

读取命令

  1. // 读取
  2. @Override
  3. public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  4. // 此时接受的时候这个值 就是我们存储redismessage 的对象
  5. RedisMessage redisMessage = (RedisMessage) msg;
  6. // 返回的结果是不同类型 分开进行处理
  7. printRedisResponse(redisMessage);
  8. // 内存管理使用了 引用计数的方式 所以我们需要释放资源
  9. ReferenceCountUtil.release(redisMessage);
  10. }

演示效果

新人创作打卡挑战赛

发博客就能抽奖!定制产品红包拿不停!

相关文章

最新文章

更多