Search in sources :

Example 26 with ServiceInstance

use of org.springframework.cloud.client.ServiceInstance in project spring-cloud-netflix by spring-cloud.

the class RetryableOkHttpLoadBalancingClient method execute.

@Override
public OkHttpRibbonResponse execute(final OkHttpRibbonRequest ribbonRequest, final IClientConfig configOverride) throws Exception {
    final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryFactory.createRetryPolicy(this.getClientName(), this);
    RetryCallback<OkHttpRibbonResponse, Exception> retryCallback = new RetryCallback<OkHttpRibbonResponse, Exception>() {

        @Override
        public OkHttpRibbonResponse doWithRetry(RetryContext context) throws Exception {
            // on retries the policy will choose the server and set it in the context
            // extract the server and update the request being made
            OkHttpRibbonRequest newRequest = ribbonRequest;
            if (context instanceof LoadBalancedRetryContext) {
                ServiceInstance service = ((LoadBalancedRetryContext) context).getServiceInstance();
                validateServiceInstance(service);
                // Reconstruct the request URI using the host and port set in the retry context
                newRequest = newRequest.withNewUri(new URI(service.getUri().getScheme(), newRequest.getURI().getUserInfo(), service.getHost(), service.getPort(), newRequest.getURI().getPath(), newRequest.getURI().getQuery(), newRequest.getURI().getFragment()));
            }
            if (isSecure(configOverride)) {
                final URI secureUri = UriComponentsBuilder.fromUri(newRequest.getUri()).scheme("https").build().toUri();
                newRequest = newRequest.withNewUri(secureUri);
            }
            OkHttpClient httpClient = getOkHttpClient(configOverride, secure);
            final Request request = newRequest.toRequest();
            Response response = httpClient.newCall(request).execute();
            if (retryPolicy.retryableStatusCode(response.code())) {
                ResponseBody responseBody = response.peekBody(Integer.MAX_VALUE);
                response.close();
                throw new OkHttpStatusCodeException(RetryableOkHttpLoadBalancingClient.this.clientName, response, responseBody, newRequest.getURI());
            }
            return new OkHttpRibbonResponse(response, newRequest.getUri());
        }
    };
    return this.executeWithRetry(ribbonRequest, retryPolicy, retryCallback, new LoadBalancedRecoveryCallback<OkHttpRibbonResponse, Response>() {

        @Override
        protected OkHttpRibbonResponse createResponse(Response response, URI uri) {
            return new OkHttpRibbonResponse(response, uri);
        }
    });
}
Also used : LoadBalancedRetryPolicy(org.springframework.cloud.client.loadbalancer.LoadBalancedRetryPolicy) OkHttpClient(okhttp3.OkHttpClient) LoadBalancedRetryContext(org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext) RetryContext(org.springframework.retry.RetryContext) HttpRequest(org.springframework.http.HttpRequest) Request(okhttp3.Request) ContextAwareRequest(org.springframework.cloud.netflix.ribbon.support.ContextAwareRequest) ServiceInstance(org.springframework.cloud.client.ServiceInstance) URI(java.net.URI) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) LoadBalancedRetryContext(org.springframework.cloud.client.loadbalancer.LoadBalancedRetryContext) RetryCallback(org.springframework.retry.RetryCallback)

Example 27 with ServiceInstance

use of org.springframework.cloud.client.ServiceInstance in project spring-cloud-netflix by spring-cloud.

the class RibbonLoadBalancedRetryPolicy method updateServerInstanceStats.

private void updateServerInstanceStats(LoadBalancedRetryContext context) {
    ServiceInstance serviceInstance = context.getServiceInstance();
    if (serviceInstance instanceof RibbonServer) {
        Server lbServer = ((RibbonServer) serviceInstance).getServer();
        ServerStats serverStats = lbContext.getServerStats(lbServer);
        serverStats.incrementSuccessiveConnectionFailureCount();
        serverStats.addToFailureCount();
        LOGGER.debug(lbServer.getHostPort() + " RetryCount: " + context.getRetryCount() + " Successive Failures: " + serverStats.getSuccessiveConnectionFailureCount() + " CircuitBreakerTripped:" + serverStats.isCircuitBreakerTripped());
    }
}
Also used : RibbonServer(org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer) Server(com.netflix.loadbalancer.Server) RibbonServer(org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer) ServerStats(com.netflix.loadbalancer.ServerStats) ServiceInstance(org.springframework.cloud.client.ServiceInstance)

Example 28 with ServiceInstance

use of org.springframework.cloud.client.ServiceInstance in project spring-cloud-netflix by spring-cloud.

the class EurekaDiscoveryClient method getInstances.

@Override
public List<ServiceInstance> getInstances(String serviceId) {
    List<InstanceInfo> infos = this.eurekaClient.getInstancesByVipAddress(serviceId, false);
    List<ServiceInstance> instances = new ArrayList<>();
    for (InstanceInfo info : infos) {
        instances.add(new EurekaServiceInstance(info));
    }
    return instances;
}
Also used : ArrayList(java.util.ArrayList) DefaultServiceInstance(org.springframework.cloud.client.DefaultServiceInstance) ServiceInstance(org.springframework.cloud.client.ServiceInstance) InstanceInfo(com.netflix.appinfo.InstanceInfo)

Example 29 with ServiceInstance

use of org.springframework.cloud.client.ServiceInstance in project spring-cloud-netflix by spring-cloud.

the class CommonsInstanceDiscovery method getInstancesForApp.

/**
 * helper that fetches the Instances for each application from DiscoveryClient.
 * @param serviceId
 * @return List<Instance>
 * @throws Exception
 */
protected List<Instance> getInstancesForApp(String serviceId) throws Exception {
    List<Instance> instances = new ArrayList<>();
    log.info("Fetching instances for app: " + serviceId);
    List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId);
    if (serviceInstances == null || serviceInstances.isEmpty()) {
        log.warn("DiscoveryClient returned null or empty for service: " + serviceId);
        return instances;
    }
    try {
        log.info("Received instance list for service: " + serviceId + ", size=" + serviceInstances.size());
        for (ServiceInstance serviceInstance : serviceInstances) {
            Instance instance = marshall(serviceInstance);
            if (instance != null) {
                instances.add(instance);
            }
        }
    } catch (Exception e) {
        log.warn("Failed to retrieve instances from DiscoveryClient", e);
    }
    return instances;
}
Also used : Instance(com.netflix.turbine.discovery.Instance) ServiceInstance(org.springframework.cloud.client.ServiceInstance) ArrayList(java.util.ArrayList) ServiceInstance(org.springframework.cloud.client.ServiceInstance)

Example 30 with ServiceInstance

use of org.springframework.cloud.client.ServiceInstance in project spring-cloud-gateway by spring-cloud.

the class LoadBalancerClientFilterTests method shouldFilter.

@Test
public void shouldFilter() {
    URI url = UriComponentsBuilder.fromUriString("lb://myservice").build().toUri();
    exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, url);
    ServiceInstance serviceInstance = new DefaultServiceInstance("myservice", "localhost", 8080, true);
    when(loadBalancerClient.choose("myservice")).thenReturn(serviceInstance);
    URI requestUrl = UriComponentsBuilder.fromUriString("https://localhost:8080").build().toUri();
    when(loadBalancerClient.reconstructURI(any(ServiceInstance.class), any(URI.class))).thenReturn(requestUrl);
    loadBalancerClientFilter.filter(exchange, chain);
    assertThat((LinkedHashSet<URI>) exchange.getAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR)).contains(url);
    verify(loadBalancerClient).choose("myservice");
    ArgumentCaptor<URI> urlArgumentCaptor = ArgumentCaptor.forClass(URI.class);
    verify(loadBalancerClient).reconstructURI(any(), urlArgumentCaptor.capture());
    URI uri = urlArgumentCaptor.getValue();
    assertThat(uri).isNotNull();
    assertThat(uri.toString()).isEqualTo("loadbalancerclient.org");
    verifyNoMoreInteractions(loadBalancerClient);
    assertThat((URI) exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR)).isEqualTo(requestUrl);
    verify(chain).filter(exchange);
    verifyNoMoreInteractions(chain);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) DefaultServiceInstance(org.springframework.cloud.client.DefaultServiceInstance) DefaultServiceInstance(org.springframework.cloud.client.DefaultServiceInstance) ServiceInstance(org.springframework.cloud.client.ServiceInstance) URI(java.net.URI) Test(org.junit.Test)

Aggregations

ServiceInstance (org.springframework.cloud.client.ServiceInstance)73 DefaultServiceInstance (org.springframework.cloud.client.DefaultServiceInstance)25 Test (org.junit.Test)24 HashMap (java.util.HashMap)12 URI (java.net.URI)11 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)11 Registration (de.codecentric.boot.admin.server.domain.values.Registration)10 ArrayList (java.util.ArrayList)10 Test (org.junit.jupiter.api.Test)10 Application (de.codecentric.boot.admin.model.Application)7 Map (java.util.Map)7 List (java.util.List)6 RibbonServer (org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient.RibbonServer)6 IClientConfig (com.netflix.client.config.IClientConfig)5 Random (java.util.Random)4 Collections (java.util.Collections)3 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)3 MonitorProperties (com.alibaba.druid.admin.config.MonitorProperties)2 ServiceNode (com.alibaba.druid.admin.model.ServiceNode)2 ConnectionResult (com.alibaba.druid.admin.model.dto.ConnectionResult)2