feign--重点笔记
feign现在断更了,现在就是使用的openfeign
原理是使用的动态代理。
步骤
1)引入依赖
<!‐‐ openfeign 远程调用 ‐‐> 2 <dependency> 3 <groupId>org.springframework.cloud</groupId> 4 <artifactId>spring‐cloud‐starter‐openfeign</artifactId> 5 </dependency>
2)编写调用接口+@FeignClient注解 + spingmvc的注解@RequestMapping
@FeignClient(value = "mall‐order",path = "/order") 2 public interface OrderFeignService { 3 4 @RequestMapping("/findOrderByUserId/{userId}") 5 public R findOrderByUserId(@PathVariable("userId") Integer userId); 6 }
3)调用端在启动类上添加@EnableFeignClients注解
1 @SpringBootApplication 2 @EnableFeignClients 3 public class MallUserFeignDemoApplication { 4 public static void main(String[] args) { 5 SpringApplication.run(MallUserFeignDemoApplication.class, args); 6 } 7 }
4)发起调用,像调用本地方式一样调用远程服务
@RestController 2 @RequestMapping("/user") 3 public class UserController { 4 5 @Autowired 6 OrderFeignService orderFeignService; 7 8 @RequestMapping(value = "/findOrderByUserId/{id}") 9 public R findOrderByUserId(@PathVariable("id") Integer id) { 10 //feign调用 11 R result = orderFeignService.findOrderByUserId(id); 12 return result; 13 } 14 }
配置
1,日志配置
2,契约配置
3,自定义拦截器实现认证逻辑 实现RequestInterceptor接口,重写apply方法。
feign: 2 client: 3 config: 4 mall‐order: #对应微服务 5 requestInterceptors[0]: #配置拦截器 6 com.tuling.mall.feigndemo.interceptor.FeignAuthRequestInterceptor
4,超时时间配置
feign: 2 client: 3 config: 4 mall‐order: #对应微服务 5 # 连接超时时间,默认2s 6 connectTimeout: 5000 7 # 请求处理超时时间,默认5s 8 readTimeout: 10000
5,客户端组件配置
feign: 2 #feign 使用 okhttp 3 httpclient: 4 enabled: false 5 okhttp: 6 enabled: true
6,压缩配置
feign: 2 # 配置 GZIP 来压缩数据 3 compression: 4 request: 5 enabled: true 6 # 配置压缩的类型 7 mime‐types: text/xml,application/xml,application/json 8 # 最小压缩值 9 min‐request‐size: 2048 10 response: 11 enabled: true 注意:只有当 Feign 的 H
开启压缩可以有效节约网络资源,提升接口性能,我们可以配置 GZIP 来压缩数据:

浙公网安备 33010602011771号