# 介绍
原文地址(4.x版本) (opens new window)
从 Spring Cloud OpenFeign 4 开始,不再支持 Feign Apache HttpClient 4。我们建议改用 Apache HttpClient 5。
feign的远程调用底层实现技术默认采用的是JDK的URLConnection,同时还支持HttpClient与OkHttp。
由于JDK的URLConnection不支持连接池,通信效率很低,所以生产中是不会使用该默认实现的。所以在Spring Cloud OpenFeign中直接将默认实现变为了HttpClient,同时也支持OkHttp。
用户可根据业务需求选择要使用的远程调用底层实现技术。
前面消费者对于微服务的消费是通过RestTemplate完成的,这种方式的弊端是很明显的:消费者对提供者的调用无法与业务接口完全吻合例如,原本Service接口中的方法是 有返回值的,但经过RestTemplate相关API调用后没有了其返回值,最终执行是否成功用户并不清楚。
再例如RestTemplate的对数据的删除与修改操作方法都没有返回值。代码编写不方便,不直观。提供者原本是按照业务接口提供服务的,而经过RestTemplate一转手,变为了UL,使得程序员在编写消费者对提供者的调用代码时,变得不直接、不明了。没有直接通过业务接口调用方便、清晰。
# OpenFeign 和 Raibbon
OpenFeign具有负载均衡功能,其可以对指定的微服务采用负载均衡方式进行消费、访问。之前老版本Spring Cloud所集成的OpenFeign默认采用了Ribbon负载均衡器。但由于Netflix己不再维护Ribbon,所以从Spring Cloud2021.x开始集成的OpenFeign中己彻底丢弃
# 使用
- 依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 开启功能 在Spring Boot 工程启动类上增加注解 @EnableFeignClients
@SpringBootApplication
@EnableFeignClients
public class Consumer8080Application {
public static void main(String[] args) {
SpringApplication.run(Consumer8080Application.class, args);
}
}
- 提供 Feign 接口
//在老版中,可以使用 @FeignClient + @RequestMapping,在新版中如果这样写启动的时候会报错
//@FeignClient(value = "provider-80812")
//@RequestMapping("/depart")
@FeignClient(value = "provider-80812", path = "/depart")
public interface DepartFeignService {
@GetMapping("/{id}")
Depart getById(@PathVariable("id") Integer id);
}
- 调用接口
@RestController
@RequestMapping("/consumer")
@AllArgsConstructor
public class ConsumerController {
private final DepartFeignService departFeignService;
@GetMapping("feign")
public Depart feignDepart() {
Depart depart = departFeignService.getById(5);
return depart;
}
}