Feign是Netfix开发的声明书、模板化的HTTP客户端,它可以防伪码更加简洁、优雅地调用HTTP API。
SpringCloud OpenFeign对Feign进行了增强,使其支持Spring MVC注解,另外还整合了Ribbon和Nacos,从而使得Feign的使用更加方便。
它可以实现远程调用服务就像调用本地方法一样,就像Dubbo一样。
快速使用
-
引入依赖
openfeign是属于SpringCloud的,我们需要现在父maven项目中添加SpringCloud的版本管理器,然后在子项目中引入依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
编写一个Feign接口,并使用
@FeignClient
注解package com.hs.springcloud.feign; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; /** * @Description: 调用stock订单服务 Feign * @Author 胡尚 * @Date: 2022/6/9 19:44 * @Version 1.0 * name是指定服务提供方的服务名,path是指定uri的路径,接口中的所有方法都会拼接这一个前缀 */ @FeignClient(name = "stock-service", path = "/stock") public interface StockFeignService { // 这里就和服务提供方 controller层中rest接口一样的写法就行。 @RequestMapping("/reduce") String reduce(); }
如果服务提供方使用了RestFul接口的写法,就需要注意在Feign接口中
@PathVariable
的注解不可用省略括号中的值@FeignClient(name = "stock-service", path = "/stock") public interface StockFeignService { // 如果服务提供方使用了RestFul的写法,我们就需要在@PathVariable注解中指定value的值 @RequestMapping("/delete/{id}") String delete(@PathVariable("id") Integer id); //就算服务提供方可以省略,像下面的写法直接写一个@PathVariable,在Feign的接口中我们也必须@PathVariable("id"),不然会报错 @RequestMapping