Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…into main
  • Loading branch information
xuehui-Z committed Feb 1, 2021
2 parents 8787914 + 68af61f commit 02ecd8a
Show file tree
Hide file tree
Showing 74 changed files with 3,301 additions and 84 deletions.
26 changes: 26 additions & 0 deletions 01jvm/TestAddUrl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package io.kimmking.kmq;

import lombok.SneakyThrows;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class TestAddUrl {

@SneakyThrows
public static void main(String[] args) {
URLClassLoader classLoader = (URLClassLoader) TestAddUrl.class.getClassLoader();
String dir = "/Users/kimmking/Downloads/Hello";
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(classLoader, new File(dir).toURL());

Class klass = Class.forName("Hello",true, classLoader);
Object obj = klass.newInstance();
Method hello = klass.getDeclaredMethod("hello");
hello.invoke(obj);
}

}
45 changes: 45 additions & 0 deletions 02nio/nio01/dependency-reduced-pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?xml version="1.0" encoding="UTF-8"?>
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>java0.nio01</groupId>
<artifactId>nio01</artifactId>
<version>1.0</version>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${maven.compile.source}</source>
<target>${maven.compile.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer>
<manifestEntries>
<Main-Class>${app.main.class}</Main-Class>
<X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
<X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<app.main.class>Main</app.main.class>
<maven.compile.source>8</maven.compile.source>
<maven.compile.target>8</maven.compile.target>
</properties>
</project>
45 changes: 43 additions & 2 deletions 02nio/nio01/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,59 @@
<groupId>java0.nio01</groupId>
<artifactId>nio01</artifactId>
<version>1.0</version>

<properties>
<app.main.class>Main</app.main.class>
<maven.compile.source>8</maven.compile.source>
<maven.compile.target>8</maven.compile.target>
</properties>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
<source>${maven.compile.source}</source>
<target>${maven.compile.target}</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<manifestEntries>
<Main-Class>${app.main.class}</Main-Class>
<X-Compile-Source-JDK>${maven.compile.source}</X-Compile-Source-JDK>
<X-Compile-Target-JDK>${maven.compile.target}</X-Compile-Target-JDK>
</manifestEntries>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>



<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.51.Final</version>
</dependency>
</dependencies>


</project>
34 changes: 34 additions & 0 deletions 02nio/nio01/src/main/java/Main.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import java0.nio01.HttpServer01;
import java0.nio01.HttpServer02;
import java0.nio01.HttpServer03;
import java0.nio01.netty.NettyHttpServer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Main {

public static void main(String[] args) {
Map<String, Class> map = new HashMap<>();
map.put("1", HttpServer01.class);
map.put("2", HttpServer02.class);
map.put("3", HttpServer03.class);
map.put("8", NettyHttpServer.class);

String id = (null == args || args.length == 0) ? "1" : args[0];
Class clazz = map.get(id);
if( null == clazz ) {
System.out.println("No class for id: " + id);
}

try {
Method method = clazz.getDeclaredMethod("main", new Class[]{String[].class});
method.invoke(null, new Object[]{new String[]{}});
} catch (Exception e) {
e.printStackTrace();
}

}

}
7 changes: 4 additions & 3 deletions 02nio/nio01/src/main/java/java0/nio01/HttpServer01.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.net.ServerSocket;
import java.net.Socket;

// 单线程的socket程序
public class HttpServer01 {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = new ServerSocket(8801);
Expand All @@ -20,17 +21,17 @@ public static void main(String[] args) throws IOException{

private static void service(Socket socket) {
try {
Thread.sleep(20);
// Thread.sleep(5);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type:text/html;charset=utf-8");
String body = "hello,nio";
String body = "hello,nio1";
printWriter.println("Content-Length:" + body.getBytes().length);
printWriter.println();
printWriter.write(body);
printWriter.close();
socket.close();
} catch (IOException | InterruptedException e) {
} catch (IOException e) { // | InterruptedException e) {
e.printStackTrace();
}
}
Expand Down
7 changes: 4 additions & 3 deletions 02nio/nio01/src/main/java/java0/nio01/HttpServer02.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.net.ServerSocket;
import java.net.Socket;

// 每个请求一个线程
public class HttpServer02 {
public static void main(String[] args) throws IOException{
ServerSocket serverSocket = new ServerSocket(8802);
Expand All @@ -22,17 +23,17 @@ public static void main(String[] args) throws IOException{

private static void service(Socket socket) {
try {
Thread.sleep(20);
// Thread.sleep(5);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type:text/html;charset=utf-8");
String body = "hello,nio";
String body = "hello,nio2";
printWriter.println("Content-Length:" + body.getBytes().length);
printWriter.println();
printWriter.write(body);
printWriter.close();
socket.close();
} catch (IOException | InterruptedException e) {
} catch (IOException e) { // | InterruptedException e) {
e.printStackTrace();
}
}
Expand Down
9 changes: 6 additions & 3 deletions 02nio/nio01/src/main/java/java0/nio01/HttpServer03.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

// 创建了一个固定大小的线程池处理请求
public class HttpServer03 {
public static void main(String[] args) throws IOException{
ExecutorService executorService = Executors.newFixedThreadPool(40);

ExecutorService executorService = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors() + 2);
final ServerSocket serverSocket = new ServerSocket(8803);
while (true) {
try {
Expand All @@ -23,7 +26,7 @@ public static void main(String[] args) throws IOException{

private static void service(Socket socket) {
try {
Thread.sleep(20);
// Thread.sleep(5);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type:text/html;charset=utf-8");
Expand All @@ -33,7 +36,7 @@ private static void service(Socket socket) {
printWriter.write(body);
printWriter.close();
socket.close();
} catch (IOException | InterruptedException e) {
} catch (IOException e) { // | InterruptedException e) {
e.printStackTrace();
}
}
Expand Down
78 changes: 78 additions & 0 deletions 02nio/nio01/src/main/java/java0/nio01/netty/HttpHandler.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package java0.nio01.netty;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.util.ReferenceCountUtil;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderValues.KEEP_ALIVE;
import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpHandler extends ChannelInboundHandlerAdapter {

@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
//logger.info("channelRead流量接口请求开始,时间为{}", startTime);
FullHttpRequest fullRequest = (FullHttpRequest) msg;
String uri = fullRequest.uri();
//logger.info("接收到的请求url为{}", uri);
if (uri.contains("/test")) {
handlerTest(fullRequest, ctx);
}

} catch(Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}

private void handlerTest(FullHttpRequest fullRequest, ChannelHandlerContext ctx) {
FullHttpResponse response = null;
try {
String value = null; // "hello,kimmking"; // 对接上次作业的httpclient或者okhttp请求另一个url的响应数据

// httpGet ... http://localhost:8801
// 返回的响应,"hello,nio";
// value = reponse....

response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
response.headers().set("Content-Type", "application/json");
response.headers().setInt("Content-Length", response.content().readableBytes());

} catch (Exception e) {
System.out.println("处理出错:"+e.getMessage());
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
} finally {
if (fullRequest != null) {
if (!HttpUtil.isKeepAlive(fullRequest)) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
response.headers().set(CONNECTION, KEEP_ALIVE);
ctx.write(response);
}
}
}
}

@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}

}
19 changes: 19 additions & 0 deletions 02nio/nio01/src/main/java/java0/nio01/netty/HttpInitializer.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package java0.nio01.netty;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;

public class HttpInitializer extends ChannelInitializer<SocketChannel> {

@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
//p.addLast(new HttpServerExpectContinueHandler());
p.addLast(new HttpObjectAggregator(1024 * 1024));
p.addLast(new HttpHandler());
}
}
Loading

0 comments on commit 02ecd8a

Please sign in to comment.