package cn.edu.tju;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.Charset;
public class MyRedisClientHandler extends ChannelInboundHandlerAdapter {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
/* String command = "";
command += "*3\r\n";
command += "$3\r\n";
command += "set\r\n";
command += "$3\r\n";
command += "age\r\n";
command += "$3\r\n";
command += "100\r\n";
System.out.println(command);*/
String cmd = buildRedisCommand("set","age","88");
//ByteBuf myCommand = Unpooled.copiedBuffer(command.getBytes());
//ctx.channel().writeAndFlush(myCommand);
ctx.channel().writeAndFlush(cmd);
//ctx.channel().close();
System.out.println("finished......");
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println("got response......");
ByteBuf buf = (ByteBuf) msg;
String s = buf.toString(Charset.defaultCharset());
System.out.println(s);
}
public String buildRedisCommand(String... stringArray){
String command = "";
String newLine = "\r\n";
command += "*";
command += stringArray.length;
command += newLine;
for (int i = 0; i < stringArray.length; i++) {
command += "$";
command += stringArray[i].length();
command += newLine;
command += stringArray[i];
command += newLine;
}
return command;
}
}
package cn.edu.tju;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
public class MyRedisClient {
//redis host
private static String host = "139.**.**.**";
private static int port = 6379;
public static void main(String[] args) throws Exception {
EventLoopGroup eventLoopGroup = new NioEventLoopGroup(1);
Bootstrap bootStrap = new Bootstrap();
bootStrap.group(eventLoopGroup).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new MyRedisClientHandler());
pipeline.addLast(new StringEncoder());
}
});
bootStrap.connect(new InetSocketAddress(host, port)).sync();
}
}