基础使用
- 引入依赖:
1 2 3 4 5
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
|
- 启动类加注解 @EnableFeignClients(value = “com.xxx.feign”)
- 编写FeignClient接口,远程调用方法直接将调用地方的controller方法粘贴过来即可
1 2 3 4 5
| @FeignClient(value = "service-product") public interface ProductFeignClient { @GetMapping(value = "/productId/{id}") public Product getProductById(@PathVariable("id") Long productId); }
|
- 调用FeignClient接口
1 2 3 4 5 6 7
| @Autowired ProductFeignClient productFeignClient;
public void test(){ Product product = productFeignClient.getProductById(productId); System.out.println(product); }
|
OpenFeign 是一个声明式远程调用客户端,要注意和restTemplate是编程式远程调用的区别。
远程调用第三方API
1 2 3 4 5 6 7
| @FeignClient(value = "weather-client", url = "http://aliv18.data.moji.com") public interface WeatherFeignClient { @PostMapping("/whapi/json/alicityweather/condition") String getWeather(@RequestHeader("Authorization") String auth, @RequestParam("token") String token, @RequestParam("cityId") String cityId); }
|
日志控制
- application.yml中开启日志:
1 2 3
| logging: level: com.atguigu.order.feign: debug
|
说明: 这行配置是 Spring Boot 的日志配置,用于设置 com.atguigu.order.feign 这个包下的 日志级别 为 DEBUG。
- 在OrderConfig中设置日志信息
1 2 3 4
| @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; }
|
超时控制
- 在application.yml引入application-feign.yml
1 2 3 4 5 6
| spring: application: name: 你的服务名 profiles: active: @spring.profile@ include: feign
|
- 添加application-feign.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| spring: cloud: openfeign: client: config: default: logger-level: full connect-timeout: 1000 read-timeout: 2000
service-product: logger-level: full connect-timeout: 3000 read-timeout: 5000
|
重试机制
在OrderConfig中加入重试机制
1 2 3 4
| @Bean Retryer retryer() { return new Retryer.Default(); }
|
默认重试5次,初始间隔100毫秒,后续每次乘1.5,最多间隔1秒
拦截器
全局拦截器
创建拦截器:
1 2 3 4 5 6 7
| @Component public class XTokenRequestIntercepter implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { requestTemplate.header("X-Token", UUID.randomUUID().toString()); } }
|
拦截所有远程调用请求,响应拦截器用的不多,请求拦截器多。
局部拦截器
放在yml文件中的spring.cloud.openfeign.client.config.service-product.request-interceptors:XTokenRequestIntercepter,要注意XTokenRequestIntercepter是个类。
兜底返回
这部分内容放在sentinel中