Skip to content

Commit 02ecd8a

Browse files
committed
Merge branch 'main' of https://github.com/JavaCourse00/JavaCourseCodes into main
2 parents 8787914 + 68af61f commit 02ecd8a

File tree

74 files changed

+3301
-84
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

74 files changed

+3301
-84
lines changed

01jvm/TestAddUrl.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package io.kimmking.kmq;
2+
3+
import lombok.SneakyThrows;
4+
5+
import java.io.File;
6+
import java.lang.reflect.Method;
7+
import java.net.URL;
8+
import java.net.URLClassLoader;
9+
10+
public class TestAddUrl {
11+
12+
@SneakyThrows
13+
public static void main(String[] args) {
14+
URLClassLoader classLoader = (URLClassLoader) TestAddUrl.class.getClassLoader();
15+
String dir = "/Users/kimmking/Downloads/Hello";
16+
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
17+
method.setAccessible(true);
18+
method.invoke(classLoader, new File(dir).toURL());
19+
20+
Class klass = Class.forName("Hello",true, classLoader);
21+
Object obj = klass.newInstance();
22+
Method hello = klass.getDeclaredMethod("hello");
23+
hello.invoke(obj);
24+
}
25+
26+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
3+
<modelVersion>4.0.0</modelVersion>
4+
<groupId>java0.nio01</groupId>
5+
<artifactId>nio01</artifactId>
6+
<version>1.0</version>
7+
<build>
8+
<plugins>
9+
<plugin>
10+
<artifactId>maven-compiler-plugin</artifactId>
11+
<configuration>
12+
<source>${maven.compile.source}</source>
13+
<target>${maven.compile.target}</target>
14+
</configuration>
15+
</plugin>
16+
<plugin>
17+
<artifactId>maven-shade-plugin</artifactId>
18+
<version>3.2.0</version>
19+
<executions>
20+
<execution>
21+
<goals>
22+
<goal>shade</goal>
23+
</goals>
24+
<configuration>
25+
<transformers>
26+
<transformer>
27+
<manifestEntries>
28+
<Main-Class>${app.main.class}</Main-Class>
29+
<X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
30+
<X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
31+
</manifestEntries>
32+
</transformer>
33+
</transformers>
34+
</configuration>
35+
</execution>
36+
</executions>
37+
</plugin>
38+
</plugins>
39+
</build>
40+
<properties>
41+
<app.main.class>Main</app.main.class>
42+
<maven.compile.source>8</maven.compile.source>
43+
<maven.compile.target>8</maven.compile.target>
44+
</properties>
45+
</project>

02nio/nio01/pom.xml

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,59 @@
77
<groupId>java0.nio01</groupId>
88
<artifactId>nio01</artifactId>
99
<version>1.0</version>
10+
11+
<properties>
12+
<app.main.class>Main</app.main.class>
13+
<maven.compile.source>8</maven.compile.source>
14+
<maven.compile.target>8</maven.compile.target>
15+
</properties>
16+
1017
<build>
1118
<plugins>
1219
<plugin>
1320
<groupId>org.apache.maven.plugins</groupId>
1421
<artifactId>maven-compiler-plugin</artifactId>
1522
<configuration>
16-
<source>8</source>
17-
<target>8</target>
23+
<source>${maven.compile.source}</source>
24+
<target>${maven.compile.target}</target>
1825
</configuration>
1926
</plugin>
27+
28+
<plugin>
29+
<groupId>org.apache.maven.plugins</groupId>
30+
<artifactId>maven-shade-plugin</artifactId>
31+
<version>3.2.0</version>
32+
<executions>
33+
<execution>
34+
<goals>
35+
<goal>shade</goal>
36+
</goals>
37+
<configuration>
38+
<transformers>
39+
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
40+
<manifestEntries>
41+
<Main-Class>${app.main.class}</Main-Class>
42+
<X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
43+
<X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
44+
</manifestEntries>
45+
</transformer>
46+
</transformers>
47+
</configuration>
48+
</execution>
49+
</executions>
50+
</plugin>
2051
</plugins>
2152
</build>
2253

2354

55+
56+
<dependencies>
57+
<dependency>
58+
<groupId>io.netty</groupId>
59+
<artifactId>netty-all</artifactId>
60+
<version>4.1.51.Final</version>
61+
</dependency>
62+
</dependencies>
63+
64+
2465
</project>

02nio/nio01/src/main/java/Main.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java0.nio01.HttpServer01;
2+
import java0.nio01.HttpServer02;
3+
import java0.nio01.HttpServer03;
4+
import java0.nio01.netty.NettyHttpServer;
5+
6+
import java.lang.reflect.Method;
7+
import java.util.HashMap;
8+
import java.util.Map;
9+
10+
public class Main {
11+
12+
public static void main(String[] args) {
13+
Map<String, Class> map = new HashMap<>();
14+
map.put("1", HttpServer01.class);
15+
map.put("2", HttpServer02.class);
16+
map.put("3", HttpServer03.class);
17+
map.put("8", NettyHttpServer.class);
18+
19+
String id = (null == args || args.length == 0) ? "1" : args[0];
20+
Class clazz = map.get(id);
21+
if( null == clazz ) {
22+
System.out.println("No class for id: " + id);
23+
}
24+
25+
try {
26+
Method method = clazz.getDeclaredMethod("main", new Class[]{String[].class});
27+
method.invoke(null, new Object[]{new String[]{}});
28+
} catch (Exception e) {
29+
e.printStackTrace();
30+
}
31+
32+
}
33+
34+
}

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

Lines changed: 4 additions & 3 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,17 +21,17 @@ 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");
27-
String body = "hello,nio";
28+
String body = "hello,nio1";
2829
printWriter.println("Content-Length:" + body.getBytes().length);
2930
printWriter.println();
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: 4 additions & 3 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,17 +23,17 @@ 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");
29-
String body = "hello,nio";
30+
String body = "hello,nio2";
3031
printWriter.println("Content-Length:" + body.getBytes().length);
3132
printWriter.println();
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: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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 = null; // "hello,kimmking"; // 对接上次作业的httpclient或者okhttp请求另一个url的响应数据
48+
49+
// httpGet ... http://localhost:8801
50+
// 返回的响应,"hello,nio";
51+
// value = reponse....
52+
53+
response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
54+
response.headers().set("Content-Type", "application/json");
55+
response.headers().setInt("Content-Length", response.content().readableBytes());
56+
57+
} catch (Exception e) {
58+
System.out.println("处理出错:"+e.getMessage());
59+
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
60+
} finally {
61+
if (fullRequest != null) {
62+
if (!HttpUtil.isKeepAlive(fullRequest)) {
63+
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
64+
} else {
65+
response.headers().set(CONNECTION, KEEP_ALIVE);
66+
ctx.write(response);
67+
}
68+
}
69+
}
70+
}
71+
72+
@Override
73+
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
74+
cause.printStackTrace();
75+
ctx.close();
76+
}
77+
78+
}
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+
}

0 commit comments

Comments
 (0)