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.bootstrap.Bootstrap;
19 import io.netty.channel.Channel;
20 import io.netty.channel.ChannelFuture;
21 import io.netty.channel.ChannelInitializer;
22 import io.netty.channel.ChannelPipeline;
23 import io.netty.channel.EventLoopGroup;
24 import io.netty.channel.MultiThreadIoEventLoopGroup;
25 import io.netty.channel.nio.NioIoHandler;
26 import io.netty.channel.socket.SocketChannel;
27 import io.netty.channel.socket.nio.NioSocketChannel;
28 import io.netty.handler.codec.memcache.binary.BinaryMemcacheClientCodec;
29 import io.netty.handler.codec.memcache.binary.BinaryMemcacheObjectAggregator;
30 import io.netty.handler.ssl.SslContext;
31 import io.netty.handler.ssl.SslContextBuilder;
32 import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
33
34 import java.io.BufferedReader;
35 import java.io.InputStreamReader;
36
37
38
39
40 public final class MemcacheClient {
41
42 static final boolean SSL = System.getProperty("ssl") != null;
43 static final String HOST = System.getProperty("host", "127.0.0.1");
44 static final int PORT = Integer.parseInt(System.getProperty("port", "11211"));
45
46 public static void main(String[] args) throws Exception {
47
48 final SslContext sslCtx;
49 if (SSL) {
50 sslCtx = SslContextBuilder.forClient()
51 .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
52 } else {
53 sslCtx = null;
54 }
55
56 EventLoopGroup group = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory());
57 try {
58 Bootstrap b = new Bootstrap();
59 b.group(group)
60 .channel(NioSocketChannel.class)
61 .handler(new ChannelInitializer<SocketChannel>() {
62 @Override
63 protected void initChannel(SocketChannel ch) throws Exception {
64 ChannelPipeline p = ch.pipeline();
65 if (sslCtx != null) {
66 p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
67 }
68 p.addLast(new BinaryMemcacheClientCodec());
69 p.addLast(new BinaryMemcacheObjectAggregator(Integer.MAX_VALUE));
70 p.addLast(new MemcacheClientHandler());
71 }
72 });
73
74
75 Channel ch = b.connect(HOST, PORT).sync().channel();
76
77
78 System.out.println("Enter commands (quit to end)");
79 System.out.println("get <key>");
80 System.out.println("set <key> <value>");
81 ChannelFuture lastWriteFuture = null;
82 BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
83 for (;;) {
84 String line = in.readLine();
85 if (line == null) {
86 break;
87 }
88 if ("quit".equals(line.toLowerCase())) {
89 ch.close().sync();
90 break;
91 }
92
93 lastWriteFuture = ch.writeAndFlush(line);
94 }
95
96
97 if (lastWriteFuture != null) {
98 lastWriteFuture.sync();
99 }
100 } finally {
101 group.shutdownGracefully();
102 }
103 }
104 }