Search in sources :

Example 41 with CaseInsensitiveHeaders

use of io.vertx.core.http.CaseInsensitiveHeaders in project VX-API-Gateway by EliMirren.

the class VxApiRouteHandlerHttpServiceImpl method handle.

@Override
public void handle(RoutingContext rct) {
    // 看有没有可用的服务连接
    if (policy.isHaveService()) {
        // 有可用连接
        // 后台服务连接信息
        VxApiServerURLInfo urlInfo;
        if (serOptions.getBalanceType() == LoadBalanceEnum.IP_HASH) {
            String ip = rct.request().remoteAddress().host();
            urlInfo = policy.getUrl(ip);
        } else {
            urlInfo = policy.getUrl();
        }
        // 执行监控
        VxApiTrackInfos trackInfo = new VxApiTrackInfos(appName, api.getApiName());
        // 统计请求内容长度
        String resLen = rct.request().getHeader("Content-Length");
        trackInfo.setRequestBufferLen(resLen == null ? 0 : StrUtil.getintTry(resLen));
        // 获得请求连接与进行请求
        String requestPath = urlInfo.getUrl();
        MultiMap headers = new CaseInsensitiveHeaders();
        if (serOptions.getParams() != null) {
            // 路径参数
            QueryStringEncoder queryParam = new QueryStringEncoder("");
            for (VxApiParamOptions p : serOptions.getParams()) {
                String param = null;
                if (p.getType() == 0 || p.getType() == 2) {
                    if (p.getApiParamPosition() == ParamPositionEnum.HEADER) {
                        param = rct.request().getHeader(p.getApiParamName());
                    } else {
                        param = rct.request().getParam(p.getApiParamName());
                    }
                } else if (p.getType() == 1) {
                    if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_HOST) {
                        param = rct.request().remoteAddress().host();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_PORT) {
                        param = Integer.toString(rct.request().remoteAddress().port());
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_PATH) {
                        param = rct.request().path() == null ? "" : rct.request().path();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_SESSION_ID) {
                        param = rct.session().id();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_ABSOLUTE_URI) {
                        param = rct.request().absoluteURI();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.CLIENT_REQUEST_SCHEMA) {
                        param = rct.request().scheme();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.SERVER_API_NAME) {
                        param = api.getApiName();
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.SERVER_UNIX_TIME) {
                        param = Long.toString(System.currentTimeMillis());
                    } else if (p.getSysParamType() == ParamSystemVarTypeEnum.SERVER_USER_AGENT) {
                        param = VxApiGatewayAttribute.VX_API_USER_AGENT;
                    }
                } else if (p.getType() == 9) {
                    param = p.getParamValue().toString();
                } else {
                    continue;
                }
                if (p.getSerParamPosition() == ParamPositionEnum.HEADER) {
                    headers.add(p.getSerParamName(), param);
                } else if (p.getSerParamPosition() == ParamPositionEnum.PATH) {
                    requestPath = requestPath.replace(":" + p.getSerParamName(), param);
                } else {
                    queryParam.addParam(p.getSerParamName(), param);
                }
            }
            requestPath += queryParam.toString();
        }
        HttpClientRequest request = httpClient.requestAbs(serOptions.getMethod(), requestPath).setTimeout(serOptions.getTimeOut());
        request.handler(resp -> {
            // 设置请求响应时间
            trackInfo.setResponseTime(Instant.now());
            HttpServerResponse response = rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType()).setChunked(true);
            Pump.pump(resp, response).start();
            resp.endHandler(end -> {
                // 透传header
                Set<String> tranHeaders = api.getResult().getTranHeaders();
                if (tranHeaders != null && tranHeaders.size() > 0) {
                    tranHeaders.forEach(h -> {
                        rct.response().putHeader(h, resp.getHeader(h) == null ? "" : resp.getHeader(h));
                    });
                }
                if (isNext) {
                    // 告诉后置处理器当前操作成功执行
                    rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));
                    rct.next();
                } else {
                    rct.response().end();
                }
                // 统计响应长度
                String repLen = resp.getHeader("Content-Length");
                trackInfo.setResponseBufferLen(repLen == null ? 0 : StrUtil.getintTry(repLen));
                trackInfo.setEndTime(Instant.now());
                rct.vertx().eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_TRACK_INFO, trackInfo.toJson());
            });
        });
        // 异常处理
        request.exceptionHandler(e -> {
            if (isNext) {
                // 告诉后置处理器当前操作成功执行
                rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>failedFuture(e));
                rct.next();
            } else {
                HttpServerResponse response = rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType());
                // 如果是连接异常返回无法连接的错误信息,其他异常返回相应的异常
                if (e instanceof ConnectException || e instanceof TimeoutException) {
                    response.setStatusCode(api.getResult().getCantConnServerStatus()).end(api.getResult().getCantConnServerExample());
                } else {
                    response.setStatusCode(api.getResult().getFailureStatus()).end(api.getResult().getFailureExample());
                }
            }
            // 提交连接请求失败
            policy.reportBadService(urlInfo.getIndex());
            trackInfo.setEndTime(Instant.now());
            // 记录与后台交互发生错误
            trackInfo.setSuccessful(false);
            trackInfo.setErrMsg(e.getMessage());
            trackInfo.setErrStackTrace(e.getStackTrace());
            rct.vertx().eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_TRACK_INFO, trackInfo.toJson());
        });
        // 设置请求时间
        trackInfo.setRequestTime(Instant.now());
        if (headers != null && headers.size() > 0) {
            request.headers().addAll(headers);
        }
        // 设置User-Agent
        String agnet = request.headers().get("User-Agent");
        if (agnet == null) {
            agnet = VxApiGatewayAttribute.VX_API_USER_AGENT;
        } else {
            agnet += " " + VxApiGatewayAttribute.VX_API_USER_AGENT;
        }
        request.putHeader("User-Agent", agnet);
        request.end();
        // 判断是否有坏的连接
        if (policy.isHaveBadService()) {
            if (!policy.isCheckWaiting()) {
                if (webClient == null) {
                    WebClient.create(rct.vertx());
                }
                policy.setCheckWaiting(true);
                rct.vertx().setTimer(serOptions.getRetryTime(), testConn -> {
                    List<VxApiServerURLInfo> service = policy.getBadService();
                    for (VxApiServerURLInfo urlinfo : service) {
                        webClient.requestAbs(serOptions.getMethod(), urlinfo.getUrl()).timeout(serOptions.getTimeOut()).send(res -> {
                            if (res.succeeded()) {
                                policy.reportGreatService(urlinfo.getIndex());
                            }
                        });
                    }
                    policy.setCheckWaiting(false);
                });
            }
        }
    } else {
        // 无可用连接时,结束当前处理器并尝试重新尝试连接是否可用
        if (isNext) {
            // 告诉后置处理器当前操作执行结果
            rct.put(VxApiAfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>failedFuture(new ConnectException("无法连接上后台交互的服务器")));
            rct.next();
        } else {
            rct.response().putHeader(VxApiRouteConstant.SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(VxApiRouteConstant.CONTENT_TYPE, api.getContentType()).setStatusCode(api.getResult().getCantConnServerStatus()).end(api.getResult().getCantConnServerExample());
        }
        if (!policy.isCheckWaiting()) {
            policy.setCheckWaiting(true);
            rct.vertx().setTimer(serOptions.getRetryTime(), testConn -> {
                List<VxApiServerURLInfo> service = policy.getBadService();
                for (VxApiServerURLInfo urlinfo : service) {
                    webClient.requestAbs(serOptions.getMethod(), urlinfo.getUrl()).timeout(serOptions.getTimeOut()).send(res -> {
                        if (res.succeeded()) {
                            policy.reportGreatService(urlinfo.getIndex());
                        }
                    });
                }
                policy.setCheckWaiting(false);
            });
        }
    }
}
Also used : VxApiTrackInfos(com.szmirren.vxApi.core.entity.VxApiTrackInfos) VxApiParamOptions(com.szmirren.vxApi.core.options.VxApiParamOptions) MultiMap(io.vertx.core.MultiMap) HttpClientRequest(io.vertx.core.http.HttpClientRequest) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) VxApiServerURLInfo(com.szmirren.vxApi.core.entity.VxApiServerURLInfo) QueryStringEncoder(io.netty.handler.codec.http.QueryStringEncoder) ConnectException(java.net.ConnectException) TimeoutException(java.util.concurrent.TimeoutException)

Example 42 with CaseInsensitiveHeaders

use of io.vertx.core.http.CaseInsensitiveHeaders in project vert.x by eclipse.

the class CaseInsensitiveHeadersTest method testGetAllHashColl.

@Test
public void testGetAllHashColl() {
    MultiMap mm = new CaseInsensitiveHeaders();
    String name1 = "AZ";
    String name2 = "€Y";
    assertTrue("hash error", hash(name1) == hash(name2));
    mm.add(name1, "value1");
    mm.add(name2, "value2");
    assertEquals(2, mm.size());
    assertEquals("[value1]", mm.getAll(name1).toString());
    assertEquals("[value2]", mm.getAll(name2).toString());
    mm = new CaseInsensitiveHeaders();
    name1 = "A";
    name2 = "R";
    assertTrue("hash error", index(hash(name1)) == index(hash(name2)));
    mm.add(name1, "value1");
    mm.add(name2, "value2");
    assertEquals(2, mm.size());
    assertEquals("[value1]", mm.getAll(name1).toString());
    assertEquals("[value2]", mm.getAll(name2).toString());
}
Also used : MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) Test(org.junit.Test)

Example 43 with CaseInsensitiveHeaders

use of io.vertx.core.http.CaseInsensitiveHeaders in project vert.x by eclipse.

the class CaseInsensitiveHeadersTest method testAddTest2.

@Test
public void testAddTest2() throws Exception {
    MultiMap mmap = new CaseInsensitiveHeaders();
    HashMap<String, String> map = new HashMap<String, String>();
    map.put("a", "b");
    map.put("c", "d");
    assertEquals("a: b\nc: d\n", mmap.addAll(map).toString());
}
Also used : MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 44 with CaseInsensitiveHeaders

use of io.vertx.core.http.CaseInsensitiveHeaders in project vert.x by eclipse.

the class CaseInsensitiveHeadersTest method testAddIterable.

@Test
public void testAddIterable() throws Exception {
    MultiMap mmap = new CaseInsensitiveHeaders();
    String name = "name";
    List<String> values = new ArrayList<String>();
    values.add("value1");
    values.add("value2");
    MultiMap result = mmap.add(name, values);
    assertEquals(1, result.size());
    assertEquals("name: value1\nname: value2\n", result.toString());
}
Also used : MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 45 with CaseInsensitiveHeaders

use of io.vertx.core.http.CaseInsensitiveHeaders in project vert.x by eclipse.

the class CaseInsensitiveHeadersTest method testSetTest14.

@Test
public void testSetTest14() throws Exception {
    MultiMap mmap = new CaseInsensitiveHeaders();
    String name = "";
    String strVal = "bbb";
    MultiMap result = mmap.set(name, strVal);
    assertNotNull(result);
    assertFalse(result.isEmpty());
    assertEquals(1, result.size());
    assertEquals(": bbb\n", result.toString());
}
Also used : MultiMap(io.vertx.core.MultiMap) CaseInsensitiveHeaders(io.vertx.core.http.CaseInsensitiveHeaders) Test(org.junit.Test)

Aggregations

CaseInsensitiveHeaders (io.vertx.core.http.CaseInsensitiveHeaders)69 MultiMap (io.vertx.core.MultiMap)65 Test (org.junit.Test)64 ArrayList (java.util.ArrayList)10 HashMap (java.util.HashMap)10 Buffer (io.vertx.core.buffer.Buffer)3 VxApiServerURLInfo (com.szmirren.vxApi.core.entity.VxApiServerURLInfo)2 VxApiTrackInfos (com.szmirren.vxApi.core.entity.VxApiTrackInfos)2 VxApiParamOptions (com.szmirren.vxApi.core.options.VxApiParamOptions)2 HttpClientRequest (io.vertx.core.http.HttpClientRequest)2 HttpServerResponse (io.vertx.core.http.HttpServerResponse)2 JsonObject (io.vertx.core.json.JsonObject)2 ConnectException (java.net.ConnectException)2 Map (java.util.Map)2 TimeoutException (java.util.concurrent.TimeoutException)2 QueryStringDecoder (io.netty.handler.codec.http.QueryStringDecoder)1 QueryStringEncoder (io.netty.handler.codec.http.QueryStringEncoder)1 WebSocket (io.vertx.core.http.WebSocket)1 WebSocketFrame (io.vertx.core.http.WebSocketFrame)1 FrameType (io.vertx.core.http.impl.FrameType)1