使用Netty连接并操作运行在Linux虚拟机192.168.241.128的6379端口上的Redis,源代码如下:
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
@Slf4j
public class RedisTest {
public static void main(String[] args) {
NioEventLoopGroup group = new NioEventLoopGroup();
final byte[] LINE = {
'\r', '\n'};
try {
new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) {
ch.pipeline()
.addLast(new LoggingHandler(LogLevel.DEBUG))
.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ByteBuf buf = ctx.alloc().buffer();
buf.writeBytes("*3".getBytes())
.writeBytes(LINE)
.writeBytes("$3".getBytes())
.writeBytes(LINE)
.writeBytes("set".getBytes())
.writeBytes(LINE)
.writeBytes("$4".getBytes())
.writeBytes(LINE)
.writeBytes("name".getBytes())
.writeBytes(LINE)
.writeBytes("$3".getBytes())
.writeBytes(LINE)
.writeBytes("fun".getBytes())
.writeBytes(LINE);
ctx.writeAndFlush(buf);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ByteBuf buf = (ByteBuf) msg;