标签:restTemplate SECONDS Spring RestTemplate Cloud Loadbalancer spring requestFactor
获取服务地址
使用的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);
标签:restTemplate,SECONDS,Spring,RestTemplate,Cloud,Loadbalancer,spring,requestFactor
来源: https://www.cnblogs.com/shar-wang/p/11628056.html
本站声明:
1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。