redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。
大家如果对使用netty搞这些http请求什么的感兴趣的,可以参观我自己创建的这个项目。
nanshaws/nettyWeb: 复习一下netty,并打算做一个web项目出来 (github.com)
Redis的基本命令包括:
SET key value:设置指定key的值。
GET key:获取指定key的值。
DEL key:删除指定key。
EXISTS key:检查指定key是否存在。
TTL key:获取指定key的过期时间。
KEYS pattern:查找所有符合指定模式的key。
INCR key:将指定key的值增加1。
DECR key:将指定key的值减少1。
LPUSH key value:将值添加到列表的左侧。
RPUSH key value:将值添加到列表的右侧。
LPOP key:移除并返回列表左侧的值。
RPOP key:移除并返回列表右侧的值。
SADD key member:将成员添加到集合中。
SMEMBERS key:获取集合中的所有成员。
ZADD key score member:将成员添加到有序集合中。
ZRANGE key start stop:按照分数从小到大的顺序获取有序集合中指定范围的成员。
HSET key field value:将哈希表中指定字段的值设置为指定值。
HGET key field:获取哈希表中指定字段的值。
HMGET key field1 [field2]:获取哈希表中指定字段的值列表。
PING:测试Redis服务器是否可用。
用netty操作redis
引入依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.tianfan</groupId>
<artifactId>nettyTestLearn</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-transport-native-epoll</artifactId>
<version>4.1.70.Final</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.86.Final</version>
</dependency>
<dependency>
<groupId>jakarta.activation</groupId>
<artifactId>jakarta.activation-api</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.angus</groupId>
<artifactId>angus-mail</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<!-- json-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
</dependencies>
</project>
完整代码:
package org.tianfan.example;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.concurrent.GenericFutureListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RedisClient {
String host; // 目标主机
int port; // 目标主机端口
public RedisClient(String host,int port){
this.host = host;
this.port = port;
}
public void start() throws Exception{
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(group)
.channel(NioSocketChannel.class)
.handler(new RedisClientInitializer());
Channel channel = bootstrap.connect(host, port).sync().channel();
System.out.println(" connected to host : " + host + ", port : " + port);
System.out.println(" type redis's command to communicate with redis-server or type 'quit' to shutdown ");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
ChannelFuture lastWriteFuture = null;
for (;;) {
String s = in.readLine();
if(s.equalsIgnoreCase("quit")) {
break;
}
System.out.print(">");
lastWriteFuture = channel.writeAndFlush(s);
lastWriteFuture.addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
System.err.print("write failed: ");
future.cause().printStackTrace(System.err);
}
}
});
}
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
System.out.println(" bye ");
}finally {
group.shutdownGracefully();
}
}
public static void main(String[] args) throws Exception{
RedisClient client = new RedisClient("192.168.56.10",6379);
client.start();
}
}
package org.tianfan.example;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.CodecException;
import io.netty.handler.codec.redis.*;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;
import java.util.ArrayList;
import java.util.List;
public class RedisClientHandler extends ChannelDuplexHandler {
// 发送 redis 命令
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
String[] commands = ((String) msg).split("\\s+");
List<RedisMessage> children = new ArrayList<>(commands.length);
for (String cmdString : commands) {
children.add(new FullBulkStringRedisMessage(ByteBufUtil.writeUtf8(ctx.alloc(), cmdString)));
}
RedisMessage request = new ArrayRedisMessage(children);
ctx.write(request, promise);
}
// 接收 redis 响应数据
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
RedisMessage redisMessage = (RedisMessage) msg;
// 打印响应消息
printAggregatedRedisResponse(redisMessage);
// 是否资源
ReferenceCountUtil.release(redisMessage);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
System.err.print("exceptionCaught: ");
cause.printStackTrace(System.err);
ctx.close();
}
private static void printAggregatedRedisResponse(RedisMessage msg) {
if (msg instanceof SimpleStringRedisMessage) {
System.out.println(((SimpleStringRedisMessage) msg).content());
} else if (msg instanceof ErrorRedisMessage) {
System.out.println(((ErrorRedisMessage) msg).content());
} else if (msg instanceof IntegerRedisMessage) {
System.out.println(((IntegerRedisMessage) msg).value());
} else if (msg instanceof FullBulkStringRedisMessage) {
System.out.println(getString((FullBulkStringRedisMessage) msg));
} else if (msg instanceof ArrayRedisMessage) {
for (RedisMessage child : ((ArrayRedisMessage) msg).children()) {
printAggregatedRedisResponse(child);
}
} else {
throw new CodecException("unknown message type: " + msg);
}
}
private static String getString(FullBulkStringRedisMessage msg) {
if (msg.isNull()) {
return "(null)";
}
return msg.content().toString(CharsetUtil.UTF_8);
}
}
package org.tianfan.example;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.redis.RedisArrayAggregator;
import io.netty.handler.codec.redis.RedisBulkStringAggregator;
import io.netty.handler.codec.redis.RedisDecoder;
import io.netty.handler.codec.redis.RedisEncoder;
public class RedisClientInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new RedisDecoder());
pipeline.addLast(new RedisBulkStringAggregator());
pipeline.addLast(new RedisArrayAggregator());
pipeline.addLast(new RedisEncoder());
pipeline.addLast(new RedisClientHandler());
}
}
结果图:

redis的基本命令,并用netty操作redis(不使用springboot或者spring框架)就单纯的用netty搞。的更多相关文章
- redis缓存数据库及Python操作redis
缓存数据库介绍 NoSQL(NoSQL = Not Only SQL ),意即“不仅仅是SQL”,泛指非关系型的数据库,随着互联网web2.0网站的兴起,传统的关系数据库在应付web2.0网站, 特 ...
- windows下Redis安装及利用java操作Redis
一.windows下Redis安装 1.Redis下载 下载地址:https://github.com/MicrosoftArchive/redis 打开下载地址后,选择版本 然后选择压缩包 下载 R ...
- 【redis,1】java操作redis: 将string、list、map、自己定义的对象保存到redis中
一.操作string .list .map 对象 1.引入jar: jedis-2.1.0.jar 2.代码 /** * @param args */ public s ...
- 直接在安装了redis的Linux机器上操作redis数据存储类型--对Sorted-Sets操作
一.概述: Sorted-Sets和Sets类型极为相似,它们都是字符串的集合,都不允许重复的成员出现在一个Set中.它们之间的主要差别是Sorted-Sets中的每一个成员都会有一个分数(score ...
- 直接在安装了redis的Linux机器上操作redis数据存储类型--对key的操作
一.概述: 前几篇博客中,主要讲述的是与Redis数据类型相关的命令,如String.List.Set.Hashes和Sorted-Set.这些命令都具有一个共同点,即所有的操作都是针对与Key关 ...
- 直接在安装了redis的Linux机器上操作redis数据存储类型--set类型
一.概述: 在Redis中,我们可以将Set类型看作为没有排序的字符集合,和List类型一样,我们也可以在该类型的数据值上执行添加.删除或判断某一元素是否存在等操作.需要说明的是,这些操作的时间复 ...
- 直接在安装了redis的Linux机器上操作redis数据存储类型--hash类型
一.概述: 我们可以将Redis中的Hashes类型看成具有String Key和String Value的map容器.所以该类型非常适合于存储值对象的信息.如Username.Password和 ...
- 直接在安装了redis的Linux机器上操作redis数据存储类型--List类型
一.概述: 在Redis中,List类型是按照插入顺序排序的字符串链表.和数据结构中的普通链表一样,我们可以在其头部(left)和尾部(right)添加新的元素.在插入时,如果该键并不存在,Redis ...
- 直接在安装了redis的Linux机器上操作redis数据存储类型--String类型
一.概述: 字符串类型是Redis中最为基础的数据存储类型,它在Redis中是二进制安全的,这便意味着该类型可以接受任何格式的数据,如JPEG图像数据或Json对象描述信息等.在Redis中字符串类型 ...
- Redis(二)Jedis操作Redis
如果测试连接的时候,报下面这个异常,可以参考下面的博客进行处理: Exception in thread "main" redis.clients.jedis.exceptions ...
随机推荐
- 使用 docker 打包构建部署 Vue 项目,一劳永逸解决node-sass安装问题
文章源于 Jenkins 构建 Vue 项目失败,然后就把 node_modules 删了重新构建发现 node-sass 安装不上了,折腾一天终于可以稳定构建了. 犹记得从学 node 的第一天,就 ...
- QEMU tap数据接收流程
QEMU直接从tap/tun取数据 QEMU tap数据接收步骤: qemu从tun取数据包 qemu将数据包放入virtio硬件网卡. qemu触发中断. 虚拟机收到中断,从virtio读取数据. ...
- 小白python和pycharm安装大佬勿扰
编程语言发展和Python安装 计算机语言的发展 机器语言 1946年2月14日,世界上第一台计算机ENIAC诞生,使用的是最原始的穿孔卡片.这种卡片上使用的语言是只有专家才能理解的语言,与人类语言差 ...
- Confluence的Excel插件Elements Spreadsheet安装
背景 Confluence是现在广泛使用的团队协作文档系统.虽然自身带了一些表格编辑功能,但表格的整体功能较弱,比如不能通过Excel文件进行导入导出,表格在复制到Excel时格式会比较奇怪等等.对于 ...
- Vika and Her Friends
Smiling & Weeping ----早知道思念那么浓烈,不分手就好了 题目链接:Problem - A - Codeforces 题目大意:有n个Vika的朋友在一个n*m的方格中去捉 ...
- 【krpano】KRPano自动缩略图分组插件
该插件可以展示场景缩略图,并支持场景分组. 下载地址:http://pan.baidu.com/s/1dFj7v0l 使用说明: 插件共有两个文件,auto_thumbs.xml和tooltip.xm ...
- mysql触发器使用教程-六种触发器
参考:https://zhuanlan.zhihu.com/p/439273702 触发器(Trigger)是 MySQL 中非常实用的一个功能,它可以在操作者对表进行「增删改」 之前(或之后)被触发 ...
- 「tjoi 2018」智力竞赛
link. 这题数据应该蛮水的,直接把大于二分值的点去掉实际上应该是有问题的.然而题解区里都写的是这种做法,所以这里主要对如何处理大于二分值的点做分析. 注意这里大于二分值的点的意义是「可以走,但走了 ...
- Solution -「洛谷 P2000」拯救世界
Description Link. 概括什么好麻烦哦 w. Solution 生成函数裸题. 把所有情况罗列出来: kkk: 金: \(1+x^6+x^{12}+\dots=\frac{1}{1-x^ ...
- Solution Set -「CF 1485」
「CF 1485A」Add and Divide Link. 贪心.枚举 \([b,b+\log_{2}\text{range}]\) 然后取个 \(\min\). #include<cstdi ...