1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.example.memcache.binary;
17
18 import io.netty.buffer.ByteBuf;
19 import io.netty.buffer.Unpooled;
20 import io.netty.channel.ChannelDuplexHandler;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.channel.ChannelPromise;
23 import io.netty.handler.codec.memcache.binary.BinaryMemcacheOpcodes;
24 import io.netty.handler.codec.memcache.binary.BinaryMemcacheRequest;
25 import io.netty.handler.codec.memcache.binary.DefaultBinaryMemcacheRequest;
26 import io.netty.handler.codec.memcache.binary.DefaultFullBinaryMemcacheRequest;
27 import io.netty.handler.codec.memcache.binary.FullBinaryMemcacheResponse;
28 import io.netty.util.CharsetUtil;
29
30 public class MemcacheClientHandler extends ChannelDuplexHandler {
31
32
33
34
35 @Override
36 public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
37 String command = (String) msg;
38 if (command.startsWith("get ")) {
39 String keyString = command.substring("get ".length());
40 ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8));
41
42 BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest(key);
43 req.setOpcode(BinaryMemcacheOpcodes.GET);
44
45 ctx.write(req, promise);
46 } else if (command.startsWith("set ")) {
47 String[] parts = command.split(" ", 3);
48 if (parts.length < 3) {
49 throw new IllegalArgumentException("Malformed Command: " + command);
50 }
51 String keyString = parts[1];
52 String value = parts[2];
53
54 ByteBuf key = Unpooled.wrappedBuffer(keyString.getBytes(CharsetUtil.UTF_8));
55 ByteBuf content = Unpooled.wrappedBuffer(value.getBytes(CharsetUtil.UTF_8));
56 ByteBuf extras = ctx.alloc().buffer(8);
57 extras.writeZero(8);
58
59 BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest(key, extras, content);
60 req.setOpcode(BinaryMemcacheOpcodes.SET);
61
62 ctx.write(req, promise);
63 } else {
64 throw new IllegalStateException("Unknown Message: " + msg);
65 }
66 }
67
68 @Override
69 public void channelRead(ChannelHandlerContext ctx, Object msg) {
70 FullBinaryMemcacheResponse res = (FullBinaryMemcacheResponse) msg;
71 System.out.println(res.content().toString(CharsetUtil.UTF_8));
72 res.release();
73 }
74
75 @Override
76 public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
77 cause.printStackTrace();
78 ctx.close();
79 }
80 }