• redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。


    大家如果对使用netty搞这些http请求什么的感兴趣的,可以参观我自己创建的这个项目。

    nanshaws/nettyWeb: 复习一下netty,并打算做一个web项目出来 (github.com)

    Redis的基本命令包括:

    1. SET key value:设置指定key的值。

    2. GET key:获取指定key的值。

    3. DEL key:删除指定key。

    4. EXISTS key:检查指定key是否存在。

    5. TTL key:获取指定key的过期时间。

    6. KEYS pattern:查找所有符合指定模式的key。

    7. INCR key:将指定key的值增加1。

    8. DECR key:将指定key的值减少1。

    9. LPUSH key value:将值添加到列表的左侧。

    10. RPUSH key value:将值添加到列表的右侧。

    11. LPOP key:移除并返回列表左侧的值。

    12. RPOP key:移除并返回列表右侧的值。

    13. SADD key member:将成员添加到集合中。

    14. SMEMBERS key:获取集合中的所有成员。

    15. ZADD key score member:将成员添加到有序集合中。

    16. ZRANGE key start stop:按照分数从小到大的顺序获取有序集合中指定范围的成员。

    17. HSET key field value:将哈希表中指定字段的值设置为指定值。

    18. HGET key field:获取哈希表中指定字段的值。

    19. HMGET key field1 [field2]:获取哈希表中指定字段的值列表。

    20. PING:测试Redis服务器是否可用。

    用netty操作redis

    引入依赖:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0</modelVersion>
    6. <groupId>org.tianfan</groupId>
    7. <artifactId>nettyTestLearn</artifactId>
    8. <version>1.0-SNAPSHOT</version>
    9. <properties>
    10. <maven.compiler.source>17</maven.compiler.source>
    11. <maven.compiler.target>17</maven.compiler.target>
    12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    13. </properties>
    14. <dependencies>
    15. <dependency>
    16. <groupId>io.netty</groupId>
    17. <artifactId>netty-transport-native-epoll</artifactId>
    18. <version>4.1.70.Final</version>
    19. </dependency>
    20. <dependency>
    21. <groupId>io.netty</groupId>
    22. <artifactId>netty-all</artifactId>
    23. <version>4.1.86.Final</version>
    24. </dependency>
    25. <dependency>
    26. <groupId>jakarta.activation</groupId>
    27. <artifactId>jakarta.activation-api</artifactId>
    28. <version>2.1.2</version>
    29. </dependency>
    30. <dependency>
    31. <groupId>org.eclipse.angus</groupId>
    32. <artifactId>angus-mail</artifactId>
    33. <version>1.0.0</version>
    34. </dependency>
    35. <dependency>
    36. <groupId>mysql</groupId>
    37. <artifactId>mysql-connector-java</artifactId>
    38. <version>8.0.33</version>
    39. </dependency>
    40. <dependency>
    41. <groupId>org.mybatis</groupId>
    42. <artifactId>mybatis</artifactId>
    43. <version>3.5.10</version>
    44. </dependency>
    45. <dependency>
    46. <groupId>org.projectlombok</groupId>
    47. <artifactId>lombok</artifactId>
    48. <version>1.18.30</version>
    49. </dependency>
    50. <!-- json-->
    51. <dependency>
    52. <groupId>com.google.code.gson</groupId>
    53. <artifactId>gson</artifactId>
    54. <version>2.8.9</version>
    55. </dependency>
    56. </dependencies>
    57. </project>

    完整代码:

    1. package org.tianfan.example;
    2. import io.netty.bootstrap.Bootstrap;
    3. import io.netty.channel.Channel;
    4. import io.netty.channel.ChannelFuture;
    5. import io.netty.channel.EventLoopGroup;
    6. import io.netty.channel.nio.NioEventLoopGroup;
    7. import io.netty.channel.socket.nio.NioSocketChannel;
    8. import io.netty.util.concurrent.GenericFutureListener;
    9. import java.io.BufferedReader;
    10. import java.io.InputStreamReader;
    11. public class RedisClient {
    12. String host; // 目标主机
    13. int port; // 目标主机端口
    14. public RedisClient(String host,int port){
    15. this.host = host;
    16. this.port = port;
    17. }
    18. public void start() throws Exception{
    19. EventLoopGroup group = new NioEventLoopGroup();
    20. try {
    21. Bootstrap bootstrap = new Bootstrap();
    22. bootstrap.group(group)
    23. .channel(NioSocketChannel.class)
    24. .handler(new RedisClientInitializer());
    25. Channel channel = bootstrap.connect(host, port).sync().channel();
    26. System.out.println(" connected to host : " + host + ", port : " + port);
    27. System.out.println(" type redis's command to communicate with redis-server or type 'quit' to shutdown ");
    28. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    29. ChannelFuture lastWriteFuture = null;
    30. for (;;) {
    31. String s = in.readLine();
    32. if(s.equalsIgnoreCase("quit")) {
    33. break;
    34. }
    35. System.out.print(">");
    36. lastWriteFuture = channel.writeAndFlush(s);
    37. lastWriteFuture.addListener(new GenericFutureListener() {
    38. @Override
    39. public void operationComplete(ChannelFuture future) throws Exception {
    40. if (!future.isSuccess()) {
    41. System.err.print("write failed: ");
    42. future.cause().printStackTrace(System.err);
    43. }
    44. }
    45. });
    46. }
    47. if (lastWriteFuture != null) {
    48. lastWriteFuture.sync();
    49. }
    50. System.out.println(" bye ");
    51. }finally {
    52. group.shutdownGracefully();
    53. }
    54. }
    55. public static void main(String[] args) throws Exception{
    56. RedisClient client = new RedisClient("192.168.56.10",6379);
    57. client.start();
    58. }
    59. }
    1. package org.tianfan.example;
    2. import io.netty.buffer.ByteBufUtil;
    3. import io.netty.channel.ChannelDuplexHandler;
    4. import io.netty.channel.ChannelHandlerContext;
    5. import io.netty.channel.ChannelPromise;
    6. import io.netty.handler.codec.CodecException;
    7. import io.netty.handler.codec.redis.*;
    8. import io.netty.util.CharsetUtil;
    9. import io.netty.util.ReferenceCountUtil;
    10. import java.util.ArrayList;
    11. import java.util.List;
    12. public class RedisClientHandler extends ChannelDuplexHandler {
    13. // 发送 redis 命令
    14. @Override
    15. public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
    16. String[] commands = ((String) msg).split("\\s+");
    17. List<RedisMessage> children = new ArrayList<>(commands.length);
    18. for (String cmdString : commands) {
    19. children.add(new FullBulkStringRedisMessage(ByteBufUtil.writeUtf8(ctx.alloc(), cmdString)));
    20. }
    21. RedisMessage request = new ArrayRedisMessage(children);
    22. ctx.write(request, promise);
    23. }
    24. // 接收 redis 响应数据
    25. @Override
    26. public void channelRead(ChannelHandlerContext ctx, Object msg) {
    27. RedisMessage redisMessage = (RedisMessage) msg;
    28. // 打印响应消息
    29. printAggregatedRedisResponse(redisMessage);
    30. // 是否资源
    31. ReferenceCountUtil.release(redisMessage);
    32. }
    33. @Override
    34. public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
    35. System.err.print("exceptionCaught: ");
    36. cause.printStackTrace(System.err);
    37. ctx.close();
    38. }
    39. private static void printAggregatedRedisResponse(RedisMessage msg) {
    40. if (msg instanceof SimpleStringRedisMessage) {
    41. System.out.println(((SimpleStringRedisMessage) msg).content());
    42. } else if (msg instanceof ErrorRedisMessage) {
    43. System.out.println(((ErrorRedisMessage) msg).content());
    44. } else if (msg instanceof IntegerRedisMessage) {
    45. System.out.println(((IntegerRedisMessage) msg).value());
    46. } else if (msg instanceof FullBulkStringRedisMessage) {
    47. System.out.println(getString((FullBulkStringRedisMessage) msg));
    48. } else if (msg instanceof ArrayRedisMessage) {
    49. for (RedisMessage child : ((ArrayRedisMessage) msg).children()) {
    50. printAggregatedRedisResponse(child);
    51. }
    52. } else {
    53. throw new CodecException("unknown message type: " + msg);
    54. }
    55. }
    56. private static String getString(FullBulkStringRedisMessage msg) {
    57. if (msg.isNull()) {
    58. return "(null)";
    59. }
    60. return msg.content().toString(CharsetUtil.UTF_8);
    61. }
    62. }
    1. package org.tianfan.example;
    2. import io.netty.channel.Channel;
    3. import io.netty.channel.ChannelInitializer;
    4. import io.netty.channel.ChannelPipeline;
    5. import io.netty.handler.codec.redis.RedisArrayAggregator;
    6. import io.netty.handler.codec.redis.RedisBulkStringAggregator;
    7. import io.netty.handler.codec.redis.RedisDecoder;
    8. import io.netty.handler.codec.redis.RedisEncoder;
    9. public class RedisClientInitializer extends ChannelInitializer {
    10. @Override
    11. protected void initChannel(Channel ch) throws Exception {
    12. ChannelPipeline pipeline = ch.pipeline();
    13. pipeline.addLast(new RedisDecoder());
    14. pipeline.addLast(new RedisBulkStringAggregator());
    15. pipeline.addLast(new RedisArrayAggregator());
    16. pipeline.addLast(new RedisEncoder());
    17. pipeline.addLast(new RedisClientHandler());
    18. }
    19. }

     结果图:

  • 相关阅读:
    18. 四数之和
    Kettle Spoon数据交换工具图文说明
    jenkins(pipeline)+k8s 实现CICD(提供源码和测试用例)
    CentOS 7 上安装 MySQL 8.0详细步骤
    11. IOC容器的加载过程
    【PyTorch】2-主要组成模块(数据读入、模型构建、损失函数、评价指标、训练和测试、优化器)
    二分答案复习
    【Excel函数】文本处理之Text函数
    Centos 安装 OpenLDAP
    STM32F4-ADC-常规通道-转换模式配置-总结
  • 原文地址:https://blog.csdn.net/m0_63251896/article/details/134360696