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

时间:2022-01-06 02:54:34

获取服务地址

  使用的EurekaClient : getNextServerFromEureka()

   使用的DiscoveryClient: getInstances()

 

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

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

  Load Balancer Client 的简单使用

  pom文件的引入

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

/**dependencyManagement 引入springCloud Dependency*/
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>

 

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<Info>> 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<MyRequest> request = RequestEntity
                .post(UriComponentsBuilder.fromUriString("服务地址").build().toUri())
                .body(orderRequest);

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

 

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