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