Search in sources :

Example 1 with Invocation

use of io.servicecomb.core.Invocation in project java-chassis by ServiceComb.

the class ClientVerticle method send.

protected void send(Long event) {
    User user = new User();
    TestRequest request = new TestRequest();
    request.setUser(user);
    request.setIndex(idx);
    request.setData(PojoClient.buffer);
    SchemaMeta schemaMeta = config.getMicroserviceMeta().ensureFindSchemaMeta("server");
    Object[] args = new Object[] { request };
    Invocation invocation = InvocationFactory.forConsumer(config, schemaMeta, "wrapParam", args);
    InvokerUtils.reactiveInvoke(invocation, ar -> {
        if (ar.isSuccessed()) {
            User result = ar.getResult();
            if (result.getIndex() != idx) {
                System.out.printf("error result:%s, expect idx %d\n", result, idx);
            }
        } else {
            CommonExceptionData data = (CommonExceptionData) ((InvocationException) ar.getResult()).getErrorData();
            System.out.println(data.getMessage());
        }
        send(null);
    });
}
Also used : User(io.servicecomb.demo.server.User) Invocation(io.servicecomb.core.Invocation) SchemaMeta(io.servicecomb.core.definition.SchemaMeta) CommonExceptionData(io.servicecomb.core.exception.CommonExceptionData) TestRequest(io.servicecomb.demo.server.TestRequest)

Example 2 with Invocation

use of io.servicecomb.core.Invocation in project java-chassis by ServiceComb.

the class TestShutdownHookHandler method testShutdownHookHandlerReject.

@Test
public void testShutdownHookHandlerReject() throws Exception {
    Deencapsulation.setField(ShutdownHookHandler.INSTANCE, "shuttingDown", true);
    Holder<InvocationType> typeHolder = new Holder<>(InvocationType.PRODUCER);
    Invocation invocation = new MockUp<Invocation>() {

        @Mock
        public InvocationType getInvocationType() {
            return typeHolder.value;
        }
    }.getMockInstance();
    ShutdownHookHandler handler = ShutdownHookHandler.INSTANCE;
    handler.handle(invocation, asyncResp -> {
        InvocationException e = asyncResp.getResult();
        Assert.assertEquals(((CommonExceptionData) e.getErrorData()).getMessage(), "shutting down in progress");
        Assert.assertEquals(e.getStatusCode(), 590);
    });
    typeHolder.value = InvocationType.CONSUMER;
    handler.handle(invocation, asyncResp -> {
        InvocationException e = asyncResp.getResult();
        Assert.assertEquals(((CommonExceptionData) e.getErrorData()).getMessage(), "shutting down in progress");
        Assert.assertEquals(e.getStatusCode(), 490);
    });
}
Also used : Invocation(io.servicecomb.core.Invocation) InvocationException(io.servicecomb.core.exception.InvocationException) Holder(javax.xml.ws.Holder) InvocationType(io.servicecomb.core.invocation.InvocationType) Mock(mockit.Mock) Test(org.junit.Test)

Example 3 with Invocation

use of io.servicecomb.core.Invocation in project java-chassis by ServiceComb.

the class TestInvokerUtils method testInvoke.

@Test
public void testInvoke() {
    Object[] objectArray = new Object[2];
    Invocation invocation = Mockito.mock(Invocation.class);
    OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
    Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta);
    Mockito.when(operationMeta.isSync()).thenReturn(false);
    Mockito.when(invocation.getArgs()).thenReturn(objectArray);
    Object obj = InvokerUtils.invoke(invocation);
    Assert.assertNull(obj);
}
Also used : Invocation(io.servicecomb.core.Invocation) OperationMeta(io.servicecomb.core.definition.OperationMeta) Test(org.junit.Test)

Example 4 with Invocation

use of io.servicecomb.core.Invocation in project java-chassis by ServiceComb.

the class TestInvokerUtils method testSyncInvokeInvocationWithException.

@Test
public void testSyncInvokeInvocationWithException() throws InterruptedException {
    Invocation invocation = Mockito.mock(Invocation.class);
    Response response = Mockito.mock(Response.class);
    new MockUp<SyncResponseExecutor>() {

        @Mock
        public Response waitResponse() throws InterruptedException {
            return Mockito.mock(Response.class);
        }
    };
    Mockito.when(response.isSuccessed()).thenReturn(true);
    OperationMeta operationMeta = Mockito.mock(OperationMeta.class);
    Mockito.when(invocation.getOperationMeta()).thenReturn(operationMeta);
    Mockito.when(operationMeta.getMicroserviceQualifiedName()).thenReturn("test");
    try {
        InvokerUtils.syncInvoke(invocation);
    } catch (InvocationException e) {
        Assert.assertEquals(490, e.getStatusCode());
    }
}
Also used : Response(io.servicecomb.core.Response) AsyncResponse(io.servicecomb.core.AsyncResponse) Invocation(io.servicecomb.core.Invocation) InvocationException(io.servicecomb.core.exception.InvocationException) MockUp(mockit.MockUp) OperationMeta(io.servicecomb.core.definition.OperationMeta) Test(org.junit.Test)

Example 5 with Invocation

use of io.servicecomb.core.Invocation in project java-chassis by ServiceComb.

the class LoadbalanceHandler method sendWithRetry.

private void sendWithRetry(Invocation invocation, AsyncResponse asyncResp, final LoadBalancer choosenLB) throws Exception {
    long time = System.currentTimeMillis();
    // retry in loadbalance, 2.0 feature
    final int currentHandler = invocation.getHandlerIndex();
    final SyncResponseExecutor orginExecutor;
    final Executor newExecutor;
    if (invocation.getResponseExecutor() instanceof SyncResponseExecutor) {
        orginExecutor = (SyncResponseExecutor) invocation.getResponseExecutor();
        newExecutor = new Executor() {

            @Override
            public void execute(Runnable command) {
                // retry的场景,对于同步调用, 需要在网络线程中进行。同步调用的主线程已经被挂起,无法再主线程中进行重试。
                command.run();
            }
        };
        invocation.setResponseExecutor(newExecutor);
    } else {
        orginExecutor = null;
        newExecutor = null;
    }
    ExecutionListener<Invocation, Response> listener = new ExecutionListener<Invocation, Response>() {

        @Override
        public void onExecutionStart(ExecutionContext<Invocation> context) throws AbortExecutionException {
        }

        @Override
        public void onStartWithServer(ExecutionContext<Invocation> context, ExecutionInfo info) throws AbortExecutionException {
        }

        @Override
        public void onExceptionWithServer(ExecutionContext<Invocation> context, Throwable exception, ExecutionInfo info) {
            LOGGER.error("onExceptionWithServer msg {}; server {}", exception.getMessage(), context.getRequest().getEndpoint());
        }

        @Override
        public void onExecutionSuccess(ExecutionContext<Invocation> context, Response response, ExecutionInfo info) {
            if (orginExecutor != null) {
                orginExecutor.execute(() -> {
                    asyncResp.complete(response);
                });
            } else {
                asyncResp.complete(response);
            }
        }

        @Override
        public void onExecutionFailed(ExecutionContext<Invocation> context, Throwable finalException, ExecutionInfo info) {
            if (orginExecutor != null) {
                orginExecutor.execute(() -> {
                    asyncResp.consumerFail(finalException);
                });
            } else {
                asyncResp.consumerFail(finalException);
            }
        }
    };
    List<ExecutionListener<Invocation, Response>> listeners = new ArrayList<>(0);
    listeners.add(listener);
    ExecutionContext<Invocation> context = new ExecutionContext<>(invocation, null, null, null);
    LoadBalancerCommand<Response> command = LoadBalancerCommand.<Response>builder().withLoadBalancer(choosenLB).withServerLocator(invocation).withRetryHandler(new DefaultLoadBalancerRetryHandler(Configuration.INSTANCE.getRetryOnSame(invocation.getMicroserviceName()), Configuration.INSTANCE.getRetryOnNext(invocation.getMicroserviceName()), true)).withListeners(listeners).withExecutionContext(context).build();
    Observable<Response> observable = command.submit(new ServerOperation<Response>() {

        public Observable<Response> call(Server s) {
            return Observable.create(f -> {
                try {
                    ((CseServer) s).setLastVisitTime(time);
                    choosenLB.getLoadBalancerStats().incrementNumRequests(s);
                    invocation.setHandlerIndex(currentHandler);
                    invocation.setEndpoint(((CseServer) s).getEndpoint());
                    invocation.next(resp -> {
                        if (resp.isFailed()) {
                            LOGGER.error("service call error, msg is {}, server is {} ", ((Throwable) resp.getResult()).getMessage(), s);
                            choosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(s);
                            f.onError(resp.getResult());
                        } else {
                            choosenLB.getLoadBalancerStats().incrementActiveRequestsCount(s);
                            choosenLB.getLoadBalancerStats().noteResponseTime(s, (System.currentTimeMillis() - time));
                            f.onNext(resp);
                            f.onCompleted();
                        }
                    });
                } catch (Exception e) {
                    LOGGER.error("execution error, msg is " + e.getMessage());
                    f.onError(e);
                }
            });
        }
    });
    observable.subscribe(response -> {
    }, error -> {
    }, () -> {
    });
}
Also used : DefaultLoadBalancerRetryHandler(com.netflix.client.DefaultLoadBalancerRetryHandler) RoundRobinRule(com.netflix.loadbalancer.RoundRobinRule) LoggerFactory(org.slf4j.LoggerFactory) ExceptionUtils(io.servicecomb.core.exception.ExceptionUtils) SyncResponseExecutor(io.servicecomb.core.provider.consumer.SyncResponseExecutor) ArrayList(java.util.ArrayList) Observable(rx.Observable) IsolationServerListFilter(io.servicecomb.loadbalance.filter.IsolationServerListFilter) Map(java.util.Map) AbstractHandler(io.servicecomb.core.handler.impl.AbstractHandler) LoadBalancerCommand(com.netflix.loadbalancer.reactive.LoadBalancerCommand) Logger(org.slf4j.Logger) ExecutionListener(com.netflix.loadbalancer.reactive.ExecutionListener) Executor(java.util.concurrent.Executor) Server(com.netflix.loadbalancer.Server) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AsyncResponse(io.servicecomb.core.AsyncResponse) TransactionControlFilter(io.servicecomb.loadbalance.filter.TransactionControlFilter) ExecutionContext(com.netflix.loadbalancer.reactive.ExecutionContext) List(java.util.List) IRule(com.netflix.loadbalancer.IRule) ExecutionInfo(com.netflix.loadbalancer.reactive.ExecutionInfo) Response(io.servicecomb.core.Response) ServerOperation(com.netflix.loadbalancer.reactive.ServerOperation) Invocation(io.servicecomb.core.Invocation) Invocation(io.servicecomb.core.Invocation) Server(com.netflix.loadbalancer.Server) SyncResponseExecutor(io.servicecomb.core.provider.consumer.SyncResponseExecutor) ArrayList(java.util.ArrayList) ExecutionInfo(com.netflix.loadbalancer.reactive.ExecutionInfo) ExecutionListener(com.netflix.loadbalancer.reactive.ExecutionListener) SyncResponseExecutor(io.servicecomb.core.provider.consumer.SyncResponseExecutor) Executor(java.util.concurrent.Executor) DefaultLoadBalancerRetryHandler(com.netflix.client.DefaultLoadBalancerRetryHandler) Observable(rx.Observable) AsyncResponse(io.servicecomb.core.AsyncResponse) Response(io.servicecomb.core.Response) ExecutionContext(com.netflix.loadbalancer.reactive.ExecutionContext)

Aggregations

Invocation (io.servicecomb.core.Invocation)70 Test (org.junit.Test)55 OperationMeta (io.servicecomb.core.definition.OperationMeta)29 Response (io.servicecomb.core.Response)20 AsyncResponse (io.servicecomb.core.AsyncResponse)19 RestOperationMeta (io.servicecomb.common.rest.definition.RestOperationMeta)10 HystrixCommandProperties (com.netflix.hystrix.HystrixCommandProperties)9 OperationProtobuf (io.servicecomb.codec.protobuf.definition.OperationProtobuf)9 WrapSchema (io.servicecomb.codec.protobuf.utils.WrapSchema)9 MockUp (mockit.MockUp)9 InvocationException (io.servicecomb.core.exception.InvocationException)8 Endpoint (io.servicecomb.core.Endpoint)7 IpPort (io.servicecomb.foundation.common.net.IpPort)6 HttpClientRequest (io.vertx.core.http.HttpClientRequest)6 HttpClientResponse (io.vertx.core.http.HttpClientResponse)6 URLPathBuilder (io.servicecomb.common.rest.definition.path.URLPathBuilder)5 Buffer (io.vertx.core.buffer.Buffer)5 HttpClient (io.vertx.core.http.HttpClient)4 ArrayList (java.util.ArrayList)4 ProduceProcessor (io.servicecomb.common.rest.codec.produce.ProduceProcessor)3