Spring Cloud 使用Spring Cloud Loadbalancer访问服务地址

获取服务地址

  使用的EurekaClient : getNextServerFromEureka()

   使用的DiscoveryClient: getInstances()

 

Load Balancer Client  (负载均衡客户端)

  加上@LoadBalaced: 为RestTemplate 或WebClient增加负载均衡的支持。

  Load Balancer Client 的简单使用

  pom文件的引入

/**指定spring-cloud.version**/
    
        1.8
        Greenwich.SR1
    
/**在注册的时候提供信息*/
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        

/**dependencyManagement 引入springCloud Dependency*/
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        

 

bootstarp.properties文件的简单配置

#声明服务名称
spring.application.name=my-customer-service

application.properties声明端口号

#随机端口
server.port=0

显示声明开启DiscoveryClient

在Application启动类上添加 ,@EnableDiscoveryClient注解

定义requestFactory

   @Bean
    public HttpComponentsClientHttpRequestFactory requestFactory() {
        PoolingHttpClientConnectionManager connectionManager =
                new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);
        connectionManager.setMaxTotal(200);
        connectionManager.setDefaultMaxPerRoute(20);

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .evictIdleConnections(30, TimeUnit.SECONDS)
                .disableAutomaticRetries()
                // 有 Keep-Alive 认里面的值,没有的话永久有效
                //.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
                // 换成自定义的
                .setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy())
                .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                new HttpComponentsClientHttpRequestFactory(httpClient);

        return requestFactory;
    }
CustomConnectionKeepAliveStrategy
public class CustomConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
    private final long DEFAULT_SECONDS = 30;

    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
        return Arrays.asList(response.getHeaders(HTTP.CONN_KEEP_ALIVE))
                .stream()
                .filter(h -> StringUtils.equalsIgnoreCase(h.getName(), "timeout")
                        && StringUtils.isNumeric(h.getValue()))
                .findFirst()
                .map(h -> NumberUtils.toLong(h.getValue(), DEFAULT_SECONDS))
                .orElse(DEFAULT_SECONDS) * 1000;
    }
}

注入RestTemplate

  @LoadBalanced
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder
                .setConnectTimeout(Duration.ofMillis(100))
                .setReadTimeout(Duration.ofMillis(500))
                .requestFactory(this::requestFactory)
                .build();
    }

 

RestTemplate的使用

 
  
@Autowired
    private RestTemplate restTemplate;

// 请求列表数据
        ResponseEntity> list = restTemplate
                .exchange("请求的服务地址", HttpMethod.GET, null, ptr);
list.getBody().forEach(c -> log.info("info": {}", c));

// 插入数据
        MyRequest orderRequest = MyRequest.builder()
                .param("value1")
                // 集合数据
                .param(Arrays.asList("value2"))
                .build();

        RequestEntity request = RequestEntity
                .post(UriComponentsBuilder.fromUriString("服务地址").build().toUri())
                .body(orderRequest);

ResponseEntity response = restTemplate.exchange(request, Order.class);
 
  

 

Order order = restTemplate
                .getForObject("http://waiter-service/order/{id}", Order.class, id);

  

 
 

 

你可能感兴趣的:(Spring Cloud 使用Spring Cloud Loadbalancer访问服务地址)