|
| 1 | +package io.github.kimmking.gateway.outbound.httpclient4; |
| 2 | + |
| 3 | + |
| 4 | +import io.netty.buffer.Unpooled; |
| 5 | +import io.netty.channel.ChannelFutureListener; |
| 6 | +import io.netty.channel.ChannelHandlerContext; |
| 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 org.apache.http.HttpResponse; |
| 12 | +import org.apache.http.client.methods.HttpGet; |
| 13 | +import org.apache.http.concurrent.FutureCallback; |
| 14 | +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; |
| 15 | +import org.apache.http.impl.nio.client.HttpAsyncClients; |
| 16 | +import org.apache.http.impl.nio.reactor.IOReactorConfig; |
| 17 | +import org.apache.http.protocol.HTTP; |
| 18 | +import org.apache.http.util.EntityUtils; |
| 19 | + |
| 20 | +import java.util.concurrent.*; |
| 21 | + |
| 22 | +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; |
| 23 | +import static io.netty.handler.codec.http.HttpResponseStatus.OK; |
| 24 | +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; |
| 25 | + |
| 26 | +public class HttpOutboundHandler { |
| 27 | + |
| 28 | + private CloseableHttpAsyncClient httpclient; |
| 29 | + private ExecutorService proxyService; |
| 30 | + private String backendUrl; |
| 31 | + |
| 32 | + public HttpOutboundHandler(String backendUrl){ |
| 33 | + this.backendUrl = backendUrl.endsWith("/")?backendUrl.substring(0,backendUrl.length()-1):backendUrl; |
| 34 | + int cores = Runtime.getRuntime().availableProcessors() * 2; |
| 35 | + long keepAliveTime = 1000; |
| 36 | + int queueSize = 2048; |
| 37 | + RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy();//.DiscardPolicy(); |
| 38 | + proxyService = new ThreadPoolExecutor(cores, cores, |
| 39 | + keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize), |
| 40 | + new NamedThreadFactory("proxyService"), handler); |
| 41 | + |
| 42 | + IOReactorConfig ioConfig = IOReactorConfig.custom() |
| 43 | + .setConnectTimeout(1000) |
| 44 | + .setSoTimeout(1000) |
| 45 | + .setIoThreadCount(cores) |
| 46 | + .setRcvBufSize(32 * 1024) |
| 47 | + .build(); |
| 48 | + |
| 49 | + httpclient = HttpAsyncClients.custom().setMaxConnTotal(40) |
| 50 | + .setMaxConnPerRoute(8) |
| 51 | + .setDefaultIOReactorConfig(ioConfig) |
| 52 | + .setKeepAliveStrategy((response,context) -> 6000) |
| 53 | + .build(); |
| 54 | + httpclient.start(); |
| 55 | + } |
| 56 | + |
| 57 | + public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx) { |
| 58 | + final String url = this.backendUrl + fullRequest.uri(); |
| 59 | + proxyService.submit(()->fetchGet(fullRequest, ctx, url)); |
| 60 | + } |
| 61 | + |
| 62 | + private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url) { |
| 63 | + final HttpGet httpGet = new HttpGet(url); |
| 64 | + //httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); |
| 65 | + httpGet.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); |
| 66 | + httpclient.execute(httpGet, new FutureCallback<HttpResponse>() { |
| 67 | + @Override |
| 68 | + public void completed(final HttpResponse endpointResponse) { |
| 69 | + try { |
| 70 | + handleResponse(inbound, ctx, endpointResponse); |
| 71 | + } catch (Exception e) { |
| 72 | + e.printStackTrace(); |
| 73 | + } finally { |
| 74 | + |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + @Override |
| 79 | + public void failed(final Exception ex) { |
| 80 | + httpGet.abort(); |
| 81 | + ex.printStackTrace(); |
| 82 | + } |
| 83 | + |
| 84 | + @Override |
| 85 | + public void cancelled() { |
| 86 | + httpGet.abort(); |
| 87 | + } |
| 88 | + }); |
| 89 | + } |
| 90 | + |
| 91 | + private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final HttpResponse endpointResponse) throws Exception { |
| 92 | + FullHttpResponse response = null; |
| 93 | + try { |
| 94 | +// String value = "hello,kimmking"; |
| 95 | +// response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8"))); |
| 96 | +// response.headers().set("Content-Type", "application/json"); |
| 97 | +// response.headers().setInt("Content-Length", response.content().readableBytes()); |
| 98 | + |
| 99 | + |
| 100 | + byte[] body = EntityUtils.toByteArray(endpointResponse.getEntity()); |
| 101 | +// System.out.println(new String(body)); |
| 102 | +// System.out.println(body.length); |
| 103 | + |
| 104 | + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(body)); |
| 105 | + response.headers().set("Content-Type", "application/json"); |
| 106 | + response.headers().setInt("Content-Length", Integer.parseInt(endpointResponse.getFirstHeader("Content-Length").getValue())); |
| 107 | + |
| 108 | +// for (Header e : endpointResponse.getAllHeaders()) { |
| 109 | +// //response.headers().set(e.getName(),e.getValue()); |
| 110 | +// System.out.println(e.getName() + " => " + e.getValue()); |
| 111 | +// } |
| 112 | + |
| 113 | + } catch (Exception e) { |
| 114 | + e.printStackTrace(); |
| 115 | + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); |
| 116 | + exceptionCaught(ctx, e); |
| 117 | + } finally { |
| 118 | + if (fullRequest != null) { |
| 119 | + if (!HttpUtil.isKeepAlive(fullRequest)) { |
| 120 | + ctx.write(response).addListener(ChannelFutureListener.CLOSE); |
| 121 | + } else { |
| 122 | + //response.headers().set(CONNECTION, KEEP_ALIVE); |
| 123 | + ctx.write(response); |
| 124 | + } |
| 125 | + } |
| 126 | + ctx.flush(); |
| 127 | + //ctx.close(); |
| 128 | + } |
| 129 | + |
| 130 | + } |
| 131 | + |
| 132 | + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { |
| 133 | + cause.printStackTrace(); |
| 134 | + ctx.close(); |
| 135 | + } |
| 136 | + |
| 137 | + |
| 138 | +} |
0 commit comments