Feign简介:
声明式的Rest WEB 服务的客户端, https://github.com/OpenFeign/feign。Spring Cloud 提供了Spring-cloud-starter-openfeign的支持
Feign的简单使用
pom文件
<!--引入版本号-->
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR1</spring-cloud.version>
</properties>
<!--dependency引入-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<!--eureka的支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--dependencyManagement 引入spring cloud 的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>
开启Feign的支持
@EnableFeignClients
@SpringBootApplication @Slf4j @EnableFeignClients // 开启Feign支持 public class CustomerServiceApplication {}
注入CloseableHttpClient
@Bean public CloseableHttpClient httpClient() { return HttpClients.custom() .setConnectionTimeToLive(30, TimeUnit.SECONDS) .evictIdleConnections(30, TimeUnit.SECONDS) .setMaxConnTotal(200) .setMaxConnPerRoute(20) .disableAutomaticRetries() // 存活策略 .setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy()) .build(); } //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; } }
定义Feign接口
@FeignClient(name = "my-service", contextId = "order") public interface OrderService { @GetMapping("/order/{id}") Order getOrder(@PathVariable("id") Long id); @PostMapping(path = "/order/", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) Order create(@RequestBody NewOrderRequest newOrder); }
使用Feign
/**注入刚刚定义的OrderService*/ @Autowired private OrderService orderService; // 使用 List<Coffee> coffees = coffeeService.getAll(); // 传对象参数 NewOrderRequest orderRequest = NewOrderRequest.builder() .customer("Li Lei") .items(Arrays.asList("capuccino")) .build(); Order order = orderService.create(orderRequest); // 单个参数 Order order = orderService.getOrder(id);
原文:https://www.cnblogs.com/shar-wang/p/11628921.html