Search in sources :

Example 1 with HttpClientWithContext

use of io.servicecomb.foundation.vertx.client.http.HttpClientWithContext in project java-chassis by ServiceComb.

the class TestClient method testHttpClientVerticle.

@Test
public void testHttpClientVerticle() throws Exception {
    HttpClientVerticle oVerticle = new HttpClientVerticle();
    oVerticle.init(Vertx.vertx(), null);
    Assert.assertEquals("clientMgr", HttpClientVerticle.CLIENT_MGR);
    Assert.assertEquals("poolCount", HttpClientVerticle.POOL_COUNT);
    Assert.assertEquals("clientOptions", HttpClientVerticle.CLIENT_OPTIONS);
    HttpClientWithContext oContextClient = new HttpClientWithContext(null, null);
    Assert.assertEquals(null, oContextClient.getHttpClient());
}
Also used : HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) HttpClientVerticle(io.servicecomb.foundation.vertx.client.http.HttpClientVerticle) Test(org.junit.Test)

Example 2 with HttpClientWithContext

use of io.servicecomb.foundation.vertx.client.http.HttpClientWithContext in project java-chassis by ServiceComb.

the class GrpcTransport method send.

@Override
public void send(Invocation invocation, AsyncResponse asyncResp) throws Exception {
    HttpClientWithContext httpClientWithContext = clientMgr.findThreadBindClientPool();
    OperationMeta operationMeta = invocation.getOperationMeta();
    OperationProtobuf operationProtobuf = ProtobufManager.getOrCreateOperation(operationMeta);
    String cseContext = JsonUtils.writeValueAsString(invocation.getContext());
    // 在verticle之外的线程调用
    IpPort ipPort = (IpPort) invocation.getEndpoint().getAddress();
    Buffer requestBuf = GrpcCodec.encodeRequest(invocation, operationProtobuf);
    String url = "/" + invocation.getSchemaId() + "/" + operationMeta.getOperationId();
    Handler<HttpClientResponse> responseHandler = httpResponse -> {
        httpResponse.bodyHandler(responseBuf -> {
            invocation.getResponseExecutor().execute(() -> {
                try {
                    Response response = GrpcCodec.decodeResponse(invocation, operationProtobuf, httpResponse, responseBuf);
                    ResponseMeta responseMeta = operationMeta.findResponseMeta(response.getStatusCode());
                    for (String headerName : responseMeta.getHeaders().keySet()) {
                        for (String value : httpResponse.headers().getAll(headerName)) {
                            response.getHeaders().addHeader(headerName, value);
                        }
                    }
                    asyncResp.complete(response);
                } catch (Exception e) {
                    asyncResp.fail(invocation.getInvocationType(), e);
                }
            });
        });
    };
    // 从业务线程转移到网络线程中去发送
    httpClientWithContext.runOnContext(httpClient -> {
        HttpClientRequest httpClientRequest = httpClient.post(ipPort.getPort(), ipPort.getHostOrIp(), url, responseHandler);
        httpClientRequest.exceptionHandler(e -> {
            asyncResp.fail(invocation.getInvocationType(), e);
        });
        httpClientRequest.setTimeout(AbstractTransport.getRequestTimeout());
        httpClientRequest.putHeader(HEADER_CONTENT_TYPE, "application/grpc").putHeader(HEADER_TE, "trailers").putHeader(HEADER_USER_AGENT, "cse-client/1.0.0").putHeader(Const.CSE_CONTEXT, cseContext).putHeader(Const.DEST_MICROSERVICE, invocation.getMicroserviceName()).end(requestBuf);
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) JsonUtils(io.servicecomb.foundation.common.utils.JsonUtils) OperationMeta(io.servicecomb.core.definition.OperationMeta) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) IpPort(io.servicecomb.foundation.common.net.IpPort) ResponseMeta(io.servicecomb.swagger.invocation.response.ResponseMeta) ProtobufManager(io.servicecomb.codec.protobuf.definition.ProtobufManager) JksOptions(io.vertx.core.net.JksOptions) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) AsyncResponse(io.servicecomb.core.AsyncResponse) Const(io.servicecomb.core.Const) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Component(org.springframework.stereotype.Component) VertxUtils(io.servicecomb.foundation.vertx.VertxUtils) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpVersion(io.vertx.core.http.HttpVersion) AbstractTransport(io.servicecomb.core.transport.AbstractTransport) Response(io.servicecomb.core.Response) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Handler(io.vertx.core.Handler) ClientPoolManager(io.servicecomb.foundation.vertx.client.ClientPoolManager) Invocation(io.servicecomb.core.Invocation) IpPort(io.servicecomb.foundation.common.net.IpPort) AsyncResponse(io.servicecomb.core.AsyncResponse) HttpClientResponse(io.vertx.core.http.HttpClientResponse) Response(io.servicecomb.core.Response) HttpClientRequest(io.vertx.core.http.HttpClientRequest) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) ResponseMeta(io.servicecomb.swagger.invocation.response.ResponseMeta) HttpClientResponse(io.vertx.core.http.HttpClientResponse) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) OperationMeta(io.servicecomb.core.definition.OperationMeta)

Example 3 with HttpClientWithContext

use of io.servicecomb.foundation.vertx.client.http.HttpClientWithContext in project java-chassis by ServiceComb.

the class TestVertxHttpMethod method testDoMethod.

@Test
public void testDoMethod(@Mocked HttpClient httpClient) throws Exception {
    Context context = new MockUp<Context>() {

        @Mock
        public void runOnContext(Handler<Void> action) {
            action.handle(null);
        }
    }.getMockInstance();
    HttpClientWithContext httpClientWithContext = new HttpClientWithContext(httpClient, context);
    Invocation invocation = Mockito.mock(Invocation.class);
    AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class);
    OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
    RestOperationMeta swaggerRestOperation = Mockito.mock(RestOperationMeta.class);
    Endpoint endpoint = Mockito.mock(Endpoint.class);
    Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta);
    URLPathBuilder urlPathBuilder = Mockito.mock(URLPathBuilder.class);
    Mockito.when(swaggerRestOperation.getPathBuilder()).thenReturn(urlPathBuilder);
    operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
    Mockito.when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation);
    Mockito.when(invocation.getEndpoint()).thenReturn(endpoint);
    Mockito.when(request.exceptionHandler(Mockito.any())).then(answer -> null);
    this.doMethod(httpClientWithContext, invocation, asyncResp);
    Assert.assertTrue(true);
}
Also used : HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) Context(io.vertx.core.Context) Invocation(io.servicecomb.core.Invocation) Endpoint(io.servicecomb.core.Endpoint) RestOperationMeta(io.servicecomb.common.rest.definition.RestOperationMeta) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) URLPathBuilder(io.servicecomb.common.rest.definition.path.URLPathBuilder) OperationMeta(io.servicecomb.core.definition.OperationMeta) RestOperationMeta(io.servicecomb.common.rest.definition.RestOperationMeta) AsyncResponse(io.servicecomb.core.AsyncResponse) Mock(mockit.Mock) Test(org.junit.Test)

Example 4 with HttpClientWithContext

use of io.servicecomb.foundation.vertx.client.http.HttpClientWithContext in project java-chassis by ServiceComb.

the class TestGrpcTransport method testSend.

@Test
public void testSend() {
    boolean status = false;
    Invocation invocation = Mockito.mock(Invocation.class);
    AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class);
    OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
    Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta);
    OperationProtobuf operationProtobuf = Mockito.mock(OperationProtobuf.class);
    Mockito.when(operationMeta.getExtData("protobuf")).thenReturn(operationProtobuf);
    Endpoint lEndpoint = Mockito.mock(Endpoint.class);
    Mockito.when(invocation.getEndpoint()).thenReturn(lEndpoint);
    WrapSchema lWrapSchema = Mockito.mock(WrapSchema.class);
    Mockito.when(operationProtobuf.getRequestSchema()).thenReturn(lWrapSchema);
    IpPort ipPort = Mockito.mock(IpPort.class);
    Mockito.when(lEndpoint.getAddress()).thenReturn(ipPort);
    Mockito.when(ipPort.getHostOrIp()).thenReturn("127.0.0.1");
    Mockito.when(ipPort.getPort()).thenReturn(80);
    new MockUp<ClientPoolManager<HttpClientWithContext>>() {

        @Mock
        public HttpClientWithContext findThreadBindClientPool() {
            return Mockito.mock(HttpClientWithContext.class);
        }
    };
    try {
        transport.send(invocation, asyncResp);
    } catch (Exception e) {
        status = true;
    }
    Assert.assertFalse(status);
}
Also used : Invocation(io.servicecomb.core.Invocation) Endpoint(io.servicecomb.core.Endpoint) OperationProtobuf(io.servicecomb.codec.protobuf.definition.OperationProtobuf) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) IpPort(io.servicecomb.foundation.common.net.IpPort) MockUp(mockit.MockUp) OperationMeta(io.servicecomb.core.definition.OperationMeta) WrapSchema(io.servicecomb.codec.protobuf.utils.WrapSchema) AsyncResponse(io.servicecomb.core.AsyncResponse) Test(org.junit.Test)

Example 5 with HttpClientWithContext

use of io.servicecomb.foundation.vertx.client.http.HttpClientWithContext in project java-chassis by ServiceComb.

the class RestUtils method httpDo.

public static void httpDo(RequestContext requestContext, Handler<RestResponse> responseHandler) {
    HttpClientWithContext vertxHttpClient = HttpClientPool.INSTANCE.getClient();
    vertxHttpClient.runOnContext(httpClient -> {
        IpPort ipPort = requestContext.getIpPort();
        HttpMethod httpMethod = requestContext.getMethod();
        RequestParam requestParam = requestContext.getParams();
        if (ipPort == null) {
            LOGGER.error("request address is null");
            responseHandler.handle(new RestResponse(requestContext, null));
            return;
        }
        StringBuilder url = new StringBuilder(requestContext.getUri());
        String queryParams = requestParam.getQueryParams();
        if (!queryParams.isEmpty()) {
            url.append(url.lastIndexOf("?") > 0 ? "&" : "?").append(queryParams);
        }
        HttpClientRequest httpClientRequest = httpClient.request(httpMethod, ipPort.getPort(), ipPort.getHostOrIp(), url.toString(), response -> {
            responseHandler.handle(new RestResponse(requestContext, response));
        });
        httpClientRequest.setTimeout(ServiceRegistryConfig.INSTANCE.getRequestTimeout()).exceptionHandler(e -> {
            LOGGER.error("{} {} fail, endpoint is {}:{}, message: {}", httpMethod, url.toString(), ipPort.getHostOrIp(), ipPort.getPort(), e.getMessage());
            responseHandler.handle(new RestResponse(requestContext, null));
        });
        addDefaultHeaders(httpClientRequest);
        if (requestParam.getHeaders() != null && requestParam.getHeaders().size() > 0) {
            for (Map.Entry<String, String> header : requestParam.getHeaders().entrySet()) {
                httpClientRequest.putHeader(header.getKey(), header.getValue());
            }
        }
        if (requestParam.getCookies() != null && requestParam.getCookies().size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (Map.Entry<String, String> cookie : requestParam.getCookies().entrySet()) {
                stringBuilder.append(cookie.getKey()).append("=").append(cookie.getValue()).append("; ");
            }
            httpClientRequest.putHeader("Cookie", stringBuilder.toString());
        }
        if (httpMethod != HttpMethod.GET && requestParam.getBody() != null && requestParam.getBody().length > 0) {
            httpClientRequest.end(Buffer.buffer(requestParam.getBody()));
        } else {
            httpClientRequest.end();
        }
    });
}
Also used : HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientWithContext(io.servicecomb.foundation.vertx.client.http.HttpClientWithContext) IpPort(io.servicecomb.foundation.common.net.IpPort) MultiMap(io.vertx.core.MultiMap) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.vertx.core.http.HttpMethod)

Aggregations

HttpClientWithContext (io.servicecomb.foundation.vertx.client.http.HttpClientWithContext)8 OperationMeta (io.servicecomb.core.definition.OperationMeta)4 Test (org.junit.Test)4 AsyncResponse (io.servicecomb.core.AsyncResponse)3 Invocation (io.servicecomb.core.Invocation)3 IpPort (io.servicecomb.foundation.common.net.IpPort)3 OperationProtobuf (io.servicecomb.codec.protobuf.definition.OperationProtobuf)2 RestOperationMeta (io.servicecomb.common.rest.definition.RestOperationMeta)2 Endpoint (io.servicecomb.core.Endpoint)2 HttpClientRequest (io.vertx.core.http.HttpClientRequest)2 ProtobufManager (io.servicecomb.codec.protobuf.definition.ProtobufManager)1 WrapSchema (io.servicecomb.codec.protobuf.utils.WrapSchema)1 URLPathBuilder (io.servicecomb.common.rest.definition.path.URLPathBuilder)1 Const (io.servicecomb.core.Const)1 Response (io.servicecomb.core.Response)1 AbstractTransport (io.servicecomb.core.transport.AbstractTransport)1 JsonUtils (io.servicecomb.foundation.common.utils.JsonUtils)1 VertxUtils (io.servicecomb.foundation.vertx.VertxUtils)1 ClientPoolManager (io.servicecomb.foundation.vertx.client.ClientPoolManager)1 HttpClientVerticle (io.servicecomb.foundation.vertx.client.http.HttpClientVerticle)1