Search in sources :

Example 1 with Server

use of com.netflix.loadbalancer.Server 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)

Example 2 with Server

use of com.netflix.loadbalancer.Server in project java-chassis by ServiceComb.

the class TestSimpleTransactionControlFilter method testGetFilteredListOfServers.

@Test
public void testGetFilteredListOfServers() {
    Invocation invocation = Mockito.mock(Invocation.class);
    filter.setInvocation(invocation);
    List<Server> servers = new ArrayList<>();
    servers.add(server);
    List<Server> filteredServers = filter.getFilteredListOfServers(servers);
    Assert.assertEquals(1, filteredServers.size());
}
Also used : Invocation(io.servicecomb.core.Invocation) Server(com.netflix.loadbalancer.Server) CseServer(io.servicecomb.loadbalance.CseServer) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 3 with Server

use of com.netflix.loadbalancer.Server in project java-chassis by ServiceComb.

the class TestLoadBalancer method testGetAllServers.

@Test
public void testGetAllServers() {
    List<Server> servers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);
    servers.add(server);
    Mockito.when(serverList.getInitialListOfServers()).thenReturn(servers);
    TransactionControlFilter filter = Mockito.mock(TransactionControlFilter.class);
    Mockito.when(filter.getFilteredListOfServers(servers)).thenReturn(servers);
    Assert.assertEquals(servers, loadBalancer.getAllServers());
}
Also used : Server(com.netflix.loadbalancer.Server) ArrayList(java.util.ArrayList) TransactionControlFilter(io.servicecomb.loadbalance.filter.TransactionControlFilter) SimpleTransactionControlFilter(io.servicecomb.loadbalance.filter.SimpleTransactionControlFilter) Test(org.junit.Test)

Example 4 with Server

use of com.netflix.loadbalancer.Server in project java-chassis by ServiceComb.

the class TestLoadBalancer method testLoadBalancerFullOperationWithoutException.

@Test
public void testLoadBalancerFullOperationWithoutException() {
    List<Server> newServers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);
    newServers.add(server);
    loadBalancer.chooseServer();
    Object key = Mockito.mock(Object.class);
    loadBalancer.chooseServer(key);
    loadBalancer.getAllServers();
    loadBalancer.getLoadBalancerStats();
    loadBalancer.getReachableServers();
    assertNotNull(loadBalancer.getAllServers());
}
Also used : Server(com.netflix.loadbalancer.Server) ArrayList(java.util.ArrayList) Test(org.junit.Test)

Example 5 with Server

use of com.netflix.loadbalancer.Server in project java-chassis by ServiceComb.

the class TestSessionSticknessRule method testServerWithoutTimeoutAndThreshold.

@Test
public void testServerWithoutTimeoutAndThreshold() {
    boolean status = true;
    SessionStickinessRule ss = new SessionStickinessRule();
    Object key = new Object();
    Server s = new Server("test");
    Deencapsulation.setField(ss, "lastServer", s);
    new MockUp<SessionStickinessRule>() {

        @Mock
        private boolean isTimeOut() {
            return false;
        }
    };
    new MockUp<SessionStickinessRule>() {

        @Mock
        private boolean isErrorThresholdMet() {
            return false;
        }
    };
    try {
        ss.choose(key);
    } catch (Exception e) {
        status = false;
    }
    Assert.assertTrue(status);
}
Also used : Server(com.netflix.loadbalancer.Server) MockUp(mockit.MockUp) Test(org.junit.Test)

Aggregations

Server (com.netflix.loadbalancer.Server)133 Test (org.junit.Test)98 ArrayList (java.util.ArrayList)40 ByteBuf (io.netty.buffer.ByteBuf)26 MockWebServer (com.google.mockwebserver.MockWebServer)25 BaseLoadBalancer (com.netflix.loadbalancer.BaseLoadBalancer)25 IClientConfig (com.netflix.client.config.IClientConfig)23 AvailabilityFilteringRule (com.netflix.loadbalancer.AvailabilityFilteringRule)20 DummyPing (com.netflix.loadbalancer.DummyPing)18 HttpServer (com.sun.net.httpserver.HttpServer)18 URI (java.net.URI)15 Invocation (org.apache.servicecomb.core.Invocation)14 DynamicServerListLoadBalancer (com.netflix.loadbalancer.DynamicServerListLoadBalancer)12 ServerStats (com.netflix.loadbalancer.ServerStats)12 Person (com.netflix.ribbon.test.resources.EmbeddedResources.Person)12 MockUp (mockit.MockUp)12 ClientException (com.netflix.client.ClientException)11 DefaultClientConfigImpl (com.netflix.client.config.DefaultClientConfigImpl)10 ExecutionListener (com.netflix.loadbalancer.reactive.ExecutionListener)9 HttpClientResponse (io.reactivex.netty.protocol.http.client.HttpClientResponse)9