Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions 02nio/nio01/src/main/java/java0/nio01/HttpClinet01.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package java0.nio01;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class HttpClinet01 {
public static void main(String[] args) throws IOException{
Socket clientSocket = new Socket("127.0.0.1",8801);
client(clientSocket);
}

private static void client(Socket socket) {
try {
// 获取服务端消息
InputStream socketData = socket.getInputStream();
//读取流数据 (socket返回的数据)
byte[] buf = new byte[1024];
int len = 0;
while ((len = socketData.read(buf)) != -1) {
System.out.println(new String(buf, 0, len));
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
80 changes: 80 additions & 0 deletions 02nio/nio02/src/main/java/io/github/tn/week03_1/HttpClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package io.github.tn.week03_1;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
*
* 周四作业:整合你上次作业的httpclient/okhttp
* @author tn
* @version 1
* @ClassName HttpClient
* @description 访问http
* @date 2020/10/27 21:25
*/
public class HttpClient {


//server
public static void main(String[] args) throws IOException {
ExecutorService executorService = Executors.newFixedThreadPool(40);
final ServerSocket serverSocket = new ServerSocket(1212);
while (true) {
try {
final Socket socket = serverSocket.accept();
executorService.execute(() -> service(socket));
} catch (IOException e) {
e.printStackTrace();
}
}
}

//service
private static void service(Socket socket) {
try {
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 = requset();
printWriter.println("Content-Length:" + body.getBytes().length);
printWriter.println();
printWriter.write(body);
printWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}


// invoking
private static String requset(){
HttpGet httpGet = new HttpGet("http://localhost:8801/test");
try(CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse resp = httpClient.execute(httpGet) ) {
if(resp.getStatusLine().getStatusCode()==200){
HttpEntity body = resp.getEntity();
//使用工具类EntityUtils,从响应中取出实体表示的内容并转换成字符串
String data = EntityUtils.toString(body, "utf-8");
return data;
}
}catch (Exception e){
System.err.println("接口调用失败");
}
return "接口调用失败";
}



}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package io.github.tn.week03_2;


import io.github.tn.week03_2.inbound.HttpInboundServer;

/**
* gateway 启动类
*/
public class TNettyServerApplication {

//项目名
public final static String GATEWAY_NAME = "NIOGateway";
//版本
public final static String GATEWAY_VERSION = "1.0.0";

public static void main(String[] args) {
String proxyServer = System.getProperty("proxyServer","http://localhost:8801/test");
String proxyPort = System.getProperty("proxyPort","8888");

// http://localhost:8888/api/hello ==> gateway API
// http://localhost:8088/api/hello ==> backend service

int port = Integer.parseInt(proxyPort);
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting...");
// netty 启动
HttpInboundServer server = new HttpInboundServer(port, proxyServer);
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer);
try {
server.run();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package io.github.tn.week03_2.inbound;

import io.github.tn.week03_2.outbound.HttpOutboundHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpInboundHandler extends ChannelInboundHandlerAdapter {

private static Logger logger = LoggerFactory.getLogger(HttpInboundHandler.class);
private final String proxyServer;
private HttpOutboundHandler handler;

public HttpInboundHandler(String proxyServer) {
this.proxyServer = proxyServer;
handler = new HttpOutboundHandler(this.proxyServer);
}

@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;
handler.requset(fullRequest, ctx);
} catch(Exception e) {
e.printStackTrace();
} finally {
ReferenceCountUtil.release(msg);
}
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package io.github.tn.week03_2.inbound;

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 HttpInboundInitializer extends ChannelInitializer<SocketChannel> {

private String proxyServer;

public HttpInboundInitializer(String proxyServer) {
this.proxyServer = proxyServer;
}

@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpServerCodec());
p.addLast(new HttpObjectAggregator(1024 * 1024));
p.addLast(new HttpInboundHandler(this.proxyServer));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package io.github.tn.week03_2.inbound;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpInboundServer {
private static Logger logger = LoggerFactory.getLogger(HttpInboundServer.class);

private int port;

private String proxyServer;

public HttpInboundServer(int port, String proxyServer) {
this.port=port;
this.proxyServer = proxyServer;
}

public void run() throws Exception {

EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup(16);

try {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 128)
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.SO_REUSEADDR, true)
.option(ChannelOption.SO_RCVBUF, 32 * 1024)
.option(ChannelOption.SO_SNDBUF, 32 * 1024)
.option(EpollChannelOption.SO_REUSEPORT, true)
.childOption(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO)).childHandler(new HttpInboundInitializer(this.proxyServer));

Channel ch = b.bind(port).sync().channel();
logger.info("开启netty http服务器,监听地址和端口为 http://127.0.0.1:" + port + '/');
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package io.github.tn.week03_2.outbound;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
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 org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

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;

/**
* @author tn
* @version 1
* @ClassName HttpOutboundHandler
* @description httpClient
* @date 2020/10/31 14:59
*/
public class HttpOutboundHandler {
private String backendUrl;

public HttpOutboundHandler(String backendUrl) {
this.backendUrl = backendUrl;
}

// invoking
public void requset(FullHttpRequest fullRequest, ChannelHandlerContext ctx){
final String url = this.backendUrl + fullRequest.uri();
invoking(fullRequest, ctx, url);
}


// invoking
private String invoking(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url){
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
try(CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse resp = httpClient.execute(httpGet) ) {
handleResponse(inbound, ctx, resp);
}catch (Exception e){
System.err.println("接口调用失败");
}
return "接口调用失败";
}


// Response
private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception {
FullHttpResponse response = null;
try {

byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity());

response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body));
response.headers().set("Content-Type", "application/json");
response.headers().setInt("Content-Length", Integer.parseInt(endpointResponse.getFirstHeader("Content-Length").getValue()));

} catch (Exception e) {
e.printStackTrace();
response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT);
exceptionCaught(ctx, e);
} finally {
if (fullRequest != null) {
if (!HttpUtil.isKeepAlive(fullRequest)) {
ctx.write(response).addListener(ChannelFutureListener.CLOSE);
} else {
ctx.write(response);
}
}
ctx.flush();
}

}

// 关流
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package io.github.tn.week03_3;


import io.github.tn.week03_3.inbound.HttpInboundServer;

public class NettyServerApplication {

public final static String GATEWAY_NAME = "NIOGateway";
public final static String GATEWAY_VERSION = "1.0.0";

public static void main(String[] args) {
String proxyServer = System.getProperty("proxyServer","http://localhost:8801");
String proxyPort = System.getProperty("proxyPort","8888");

// http://localhost:8888/api/hello ==> gateway API
// http://localhost:8088/api/hello ==> backend service

int port = Integer.parseInt(proxyPort);
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" starting...");
HttpInboundServer server = new HttpInboundServer(port, proxyServer);
System.out.println(GATEWAY_NAME + " " + GATEWAY_VERSION +" started at http://localhost:" + port + " for server:" + proxyServer);
try {
server.run();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
Loading