|
1 | 1 | package io.github.kimmking.gateway.outbound.okhttp; |
2 | 2 |
|
| 3 | +import io.github.kimmking.gateway.filter.HttpRequestFilter; |
| 4 | +import io.github.kimmking.gateway.outbound.httpclient4.NamedThreadFactory; |
| 5 | +import io.github.kimmking.gateway.router.HttpEndpointRouter; |
| 6 | +import io.github.kimmking.gateway.router.RandHttpEndPointRouter; |
| 7 | +import io.netty.buffer.Unpooled; |
| 8 | +import io.netty.channel.ChannelFutureListener; |
| 9 | +import io.netty.channel.ChannelHandlerContext; |
| 10 | +import io.netty.handler.codec.http.DefaultFullHttpResponse; |
| 11 | +import io.netty.handler.codec.http.FullHttpRequest; |
| 12 | +import io.netty.handler.codec.http.FullHttpResponse; |
| 13 | +import io.netty.handler.codec.http.HttpUtil; |
| 14 | +import okhttp3.*; |
| 15 | + |
| 16 | +import java.io.IOException; |
| 17 | +import java.util.List; |
| 18 | +import java.util.concurrent.*; |
| 19 | + |
| 20 | +import static io.netty.handler.codec.http.HttpResponseStatus.NO_CONTENT; |
| 21 | +import static io.netty.handler.codec.http.HttpResponseStatus.OK; |
| 22 | +import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; |
| 23 | + |
3 | 24 | public class OkhttpOutboundHandler { |
| 25 | + |
| 26 | + private OkHttpClient client; |
| 27 | + private ExecutorService proxyService; |
| 28 | + private List<String> backendUrls; |
| 29 | + private HttpEndpointRouter router; |
| 30 | + |
| 31 | + public OkhttpOutboundHandler(List<String> backendUrls) { |
| 32 | + this.backendUrls = backendUrls; |
| 33 | + |
| 34 | + ConnectionPool pool = new ConnectionPool(5, 10, TimeUnit.MINUTES); |
| 35 | + client = new OkHttpClient().newBuilder().readTimeout(2000, TimeUnit.MILLISECONDS) |
| 36 | + .connectionPool(pool).retryOnConnectionFailure(false).followRedirects(true).build(); |
| 37 | + |
| 38 | + int cores = Runtime.getRuntime().availableProcessors() * 2; |
| 39 | + long keepAliveTime = 1000; |
| 40 | + int queueSize = 2048; |
| 41 | + RejectedExecutionHandler handler = new ThreadPoolExecutor.CallerRunsPolicy(); |
| 42 | + proxyService = new ThreadPoolExecutor(cores, cores, |
| 43 | + keepAliveTime, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(queueSize), |
| 44 | + new NamedThreadFactory("proxyService"), handler); |
| 45 | + |
| 46 | + router = new RandHttpEndPointRouter(); |
| 47 | + } |
| 48 | + |
| 49 | + private String formatUrl(String backend) { |
| 50 | + return backend.endsWith("/") ? backend.substring(0, backend.length() - 1) : backend; |
| 51 | + } |
| 52 | + |
| 53 | + |
| 54 | + public void handle(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, HttpRequestFilter filter) |
| 55 | + throws Exception { |
| 56 | + |
| 57 | + String backendUrl = router.route(this.backendUrls); |
| 58 | + final String url = backendUrl + fullRequest.uri(); |
| 59 | + |
| 60 | + if (filter.filter2(fullRequest, ctx)) { |
| 61 | + |
| 62 | + proxyService.submit(() -> fetchGet(fullRequest, ctx, url)); |
| 63 | + } else { |
| 64 | + limited(ctx); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private void fetchGet(final FullHttpRequest inbound, final ChannelHandlerContext ctx, final String url) { |
| 69 | + try { |
| 70 | + |
| 71 | + final Request request = new Request.Builder().url(url).get().build(); |
| 72 | + final Call call = client.newCall(request); |
| 73 | + call.enqueue(new Callback() { |
| 74 | + @Override |
| 75 | + public void onFailure(Call call, IOException e) { |
| 76 | + e.printStackTrace(); |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + public void onResponse(Call call, Response response) throws IOException { |
| 81 | + try { |
| 82 | + handleResponse(inbound, ctx, response); |
| 83 | + } catch (Exception e) { |
| 84 | + e.printStackTrace(); |
| 85 | + } |
| 86 | + } |
| 87 | + }); |
| 88 | + }catch (Exception e){ |
| 89 | + e.printStackTrace(); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + private void limited(final ChannelHandlerContext ctx) { |
| 94 | + byte[] bytes = "被限流...".getBytes(); |
| 95 | + FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bytes)); |
| 96 | + |
| 97 | + response.headers().set("Content-Type", "application/json"); |
| 98 | + response.headers().setInt("Content-Length", bytes.length); |
| 99 | + |
| 100 | + ctx.write(response); |
| 101 | + ctx.flush(); |
| 102 | + } |
| 103 | + |
| 104 | + private void handleResponse(final FullHttpRequest fullRequest, final ChannelHandlerContext ctx, final Response endpointResponse) throws Exception { |
| 105 | + FullHttpResponse response = null; |
| 106 | + try { |
| 107 | + String body = endpointResponse.body().string(); |
| 108 | + System.out.println(body); |
| 109 | + byte[] bodys = body.getBytes(); |
| 110 | + |
| 111 | + response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(bodys)); |
| 112 | + |
| 113 | + response.headers().set("Content-Type", "application/json"); |
| 114 | + response.headers().setInt("Content-Length", Integer.parseInt(endpointResponse.header("Content-Length"))); |
| 115 | + |
| 116 | + |
| 117 | + } catch (Exception e) { |
| 118 | + e.printStackTrace(); |
| 119 | + response = new DefaultFullHttpResponse(HTTP_1_1, NO_CONTENT); |
| 120 | + ctx.close(); |
| 121 | + } finally { |
| 122 | + if (fullRequest != null) { |
| 123 | + if (!HttpUtil.isKeepAlive(fullRequest)) { |
| 124 | + ctx.write(response).addListener(ChannelFutureListener.CLOSE); |
| 125 | + } else { |
| 126 | + ctx.write(response); |
| 127 | + } |
| 128 | + } |
| 129 | + ctx.flush(); |
| 130 | + } |
| 131 | + } |
4 | 132 | } |
0 commit comments