Skip to content

Commit dbd14b1

Browse files
committed
add netty demo
1 parent 9a30cc5 commit dbd14b1

File tree

7 files changed

+160
-7
lines changed

7 files changed

+160
-7
lines changed

02nio/nio01/pom.xml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,13 @@
2020
</plugins>
2121
</build>
2222

23+
<dependencies>
24+
<dependency>
25+
<groupId>io.netty</groupId>
26+
<artifactId>netty-all</artifactId>
27+
<version>4.1.51.Final</version>
28+
</dependency>
29+
</dependencies>
30+
2331

2432
</project>

02nio/nio01/src/main/java/java0/nio01/HttpServer01.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.net.ServerSocket;
66
import java.net.Socket;
77

8+
// 单线程的socket程序
89
public class HttpServer01 {
910
public static void main(String[] args) throws IOException{
1011
ServerSocket serverSocket = new ServerSocket(8801);
@@ -20,7 +21,7 @@ public static void main(String[] args) throws IOException{
2021

2122
private static void service(Socket socket) {
2223
try {
23-
Thread.sleep(20);
24+
// Thread.sleep(5);
2425
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2526
printWriter.println("HTTP/1.1 200 OK");
2627
printWriter.println("Content-Type:text/html;charset=utf-8");
@@ -30,7 +31,7 @@ private static void service(Socket socket) {
3031
printWriter.write(body);
3132
printWriter.close();
3233
socket.close();
33-
} catch (IOException | InterruptedException e) {
34+
} catch (IOException e) { // | InterruptedException e) {
3435
e.printStackTrace();
3536
}
3637
}

02nio/nio01/src/main/java/java0/nio01/HttpServer02.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.net.ServerSocket;
66
import java.net.Socket;
77

8+
// 每个请求一个线程
89
public class HttpServer02 {
910
public static void main(String[] args) throws IOException{
1011
ServerSocket serverSocket = new ServerSocket(8802);
@@ -22,7 +23,7 @@ public static void main(String[] args) throws IOException{
2223

2324
private static void service(Socket socket) {
2425
try {
25-
Thread.sleep(20);
26+
// Thread.sleep(5);
2627
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2728
printWriter.println("HTTP/1.1 200 OK");
2829
printWriter.println("Content-Type:text/html;charset=utf-8");
@@ -32,7 +33,7 @@ private static void service(Socket socket) {
3233
printWriter.write(body);
3334
printWriter.close();
3435
socket.close();
35-
} catch (IOException | InterruptedException e) {
36+
} catch (IOException e) { // | InterruptedException e) {
3637
e.printStackTrace();
3738
}
3839
}

02nio/nio01/src/main/java/java0/nio01/HttpServer03.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@
77
import java.util.concurrent.ExecutorService;
88
import java.util.concurrent.Executors;
99

10+
// 创建了一个固定大小的线程池处理请求
1011
public class HttpServer03 {
1112
public static void main(String[] args) throws IOException{
12-
ExecutorService executorService = Executors.newFixedThreadPool(40);
13+
14+
ExecutorService executorService = Executors.newFixedThreadPool(
15+
Runtime.getRuntime().availableProcessors() + 2);
1316
final ServerSocket serverSocket = new ServerSocket(8803);
1417
while (true) {
1518
try {
@@ -23,7 +26,7 @@ public static void main(String[] args) throws IOException{
2326

2427
private static void service(Socket socket) {
2528
try {
26-
Thread.sleep(20);
29+
// Thread.sleep(5);
2730
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
2831
printWriter.println("HTTP/1.1 200 OK");
2932
printWriter.println("Content-Type:text/html;charset=utf-8");
@@ -33,7 +36,7 @@ private static void service(Socket socket) {
3336
printWriter.write(body);
3437
printWriter.close();
3538
socket.close();
36-
} catch (IOException | InterruptedException e) {
39+
} catch (IOException e) { // | InterruptedException e) {
3740
e.printStackTrace();
3841
}
3942
}
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package java0.nio01.netty;
2+
3+
import io.netty.buffer.Unpooled;
4+
import io.netty.channel.ChannelFutureListener;
5+
import io.netty.channel.ChannelHandlerContext;
6+
import io.netty.channel.ChannelInboundHandlerAdapter;
7+
import io.netty.handler.codec.http.DefaultFullHttpResponse;
8+
import io.netty.handler.codec.http.FullHttpRequest;
9+
import io.netty.handler.codec.http.FullHttpResponse;
10+
import io.netty.handler.codec.http.HttpUtil;
11+
import io.netty.util.ReferenceCountUtil;
12+
13+
import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
14+
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
15+
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
16+
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
17+
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
18+
19+
public class HttpHandler extends ChannelInboundHandlerAdapter {
20+
21+
@Override
22+
public void channelReadComplete(ChannelHandlerContext ctx) {
23+
ctx.flush();
24+
}
25+
26+
@Override
27+
public void channelRead(ChannelHandlerContext ctx, Object msg) {
28+
try {
29+
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
30+
FullHttpRequest fullRequest = (FullHttpRequest) msg;
31+
String uri = fullRequest.uri();
32+
//logger.info("接收到的请求url为{}", uri);
33+
if (uri.contains("/test")) {
34+
handlerTest(fullRequest, ctx);
35+
}
36+
37+
} catch(Exception e) {
38+
e.printStackTrace();
39+
} finally {
40+
ReferenceCountUtil.release(msg);
41+
}
42+
}
43+
44+
private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
45+
FullHttpResponse response = null;
46+
try {
47+
String value = "hello,kimmking";
48+
response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
49+
response.headers().set("Content-Type", "application/json");
50+
response.headers().setInt("Content-Length", response.content().readableBytes());
51+
52+
} catch (Exception e) {
53+
System.out.println("处理出错:"+e.getMessage());
54+
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
55+
} finally {
56+
if (fullRequest != null) {
57+
if (!HttpUtil.isKeepAlive(fullRequest)) {
58+
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
59+
} else {
60+
response.headers().set(CONNECTION, KEEP_ALIVE);
61+
ctx.write(response);
62+
}
63+
}
64+
}
65+
}
66+
67+
@Override
68+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
69+
cause.printStackTrace();
70+
ctx.close();
71+
}
72+
73+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package java0.nio01.netty;
2+
3+
import io.netty.channel.ChannelInitializer;
4+
import io.netty.channel.ChannelPipeline;
5+
import io.netty.channel.socket.SocketChannel;
6+
import io.netty.handler.codec.http.HttpObjectAggregator;
7+
import io.netty.handler.codec.http.HttpServerCodec;
8+
9+
public class HttpInitializer extends ChannelInitializer<SocketChannel> {
10+
11+
@Override
12+
public void initChannel(SocketChannel ch) {
13+
ChannelPipeline p = ch.pipeline();
14+
p.addLast(new HttpServerCodec());
15+
//p.addLast(new HttpServerExpectContinueHandler());
16+
p.addLast(new HttpObjectAggregator(1024 * 1024));
17+
p.addLast(new HttpHandler());
18+
}
19+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package java0.nio01.netty;
2+
3+
import io.netty.bootstrap.ServerBootstrap;
4+
import io.netty.buffer.PooledByteBufAllocator;
5+
import io.netty.channel.Channel;
6+
import io.netty.channel.ChannelOption;
7+
import io.netty.channel.EventLoopGroup;
8+
import io.netty.channel.epoll.EpollChannelOption;
9+
import io.netty.channel.nio.NioEventLoopGroup;
10+
import io.netty.channel.socket.nio.NioServerSocketChannel;
11+
import io.netty.handler.logging.LogLevel;
12+
import io.netty.handler.logging.LoggingHandler;
13+
14+
public class NettyHttpServer {
15+
public static void main(String[] args) throws InterruptedException {
16+
17+
int port = 8808;
18+
19+
EventLoopGroup bossGroup = new NioEventLoopGroup(2);
20+
EventLoopGroup workerGroup = new NioEventLoopGroup(16);
21+
22+
try {
23+
ServerBootstrap b = new ServerBootstrap();
24+
b.option(ChannelOption.SO_BACKLOG, 128)
25+
.option(ChannelOption.TCP_NODELAY, true)
26+
.option(ChannelOption.SO_KEEPALIVE, true)
27+
.option(ChannelOption.SO_REUSEADDR, true)
28+
.option(ChannelOption.SO_RCVBUF, 32 * 1024)
29+
.option(ChannelOption.SO_SNDBUF, 32 * 1024)
30+
.option(EpollChannelOption.SO_REUSEPORT, true)
31+
.childOption(ChannelOption.SO_KEEPALIVE, true)
32+
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
33+
34+
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
35+
.handler(new LoggingHandler(LogLevel.INFO))
36+
.childHandler(new HttpInitializer());
37+
38+
Channel ch = b.bind(port).sync().channel();
39+
System.out.println("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/');
40+
ch.closeFuture().sync();
41+
} finally {
42+
bossGroup.shutdownGracefully();
43+
workerGroup.shutdownGracefully();
44+
}
45+
46+
47+
}
48+
}

0 commit comments

Comments
 (0)