一. Feign快速入门


备注:以下操作在consumer中进行。

1.1 导入相关feign坐标

  1. <!--feign-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-starter-openfeign</artifactId>
  5. </dependency>

1.2 启动类中开启feign

  1. @EnableDiscoveryClient // 激活DiscoveryClient
  2. @EnableEurekaClient
  3. @SpringBootApplication
  4. @EnableFeignClients //开启Feign的功能
  5. public class ConsumerApp {
  6. public static void main(String[] args) {
  7. SpringApplication.run(ConsumerApp.class,args);
  8. }
  9. }

1.3 建立声明式接口,发起远程调用

  1. /**
  2. * feign声明式接口。发起远程调用的。
  3. *
  4. String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
  5. Goods goods = restTemplate.getForObject(url, Goods.class);
  6. *
  7. * 1. 定义接口
  8. * 2. 接口上添加注解 @FeignClient,设置value属性为 服务提供者的 应用名称
  9. * 3. 编写调用接口,接口的声明规则 和 提供方接口保持一致。
  10. * 4. 注入该接口对象,调用接口方法完成远程调用
  11. */
  12. @FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class)
  13. public interface GoodsFeignClient {
  14. @GetMapping("/goods/findOne/{id}")
  15. public Goods findGoodsById(@PathVariable("id") int id);
  16. }

1.4 调用

注入,直接调用!

  1. @RestController
  2. @RequestMapping("/order")
  3. public class OrderController {
  4. @Autowired
  5. private RestTemplate restTemplate;
  6. @Autowired
  7. private GoodsFeignClient goodsFeignClient;
  8. @GetMapping("/goods/{id}")
  9. public Goods findGoodsById(@PathVariable("id") int id){
  10. Goods goods = goodsFeignClient.findGoodsById(id);
  11. return goods;
  12. }
  13. }

二. Feign超时配置


feign底层依赖ribbon实现负载均衡和远程调用。所以:

  1. # 设置Ribbon的超时时间
  2. ribbon:
  3. ConnectTimeout: 1000 # 连接超时时间 默认1s
  4. ReadTimeout: 3000 # 逻辑处理的超时时间 默认1s

三. Feign日志记录


3.1 配置yml文件

  1. # 设置当前的日志级别 debug,feign只支持记录debug级别的日志
  2. logging:
  3. level:
  4. com.itheima: debug

feign只支持记录debug级别的日志。
**

3.2 config包中建立bean

  1. @Configuration
  2. public class FeignLogConfig {
  3. /*
  4. NONE,不记录
  5. BASIC,记录基本的请求行,响应状态码数据
  6. HEADERS,记录基本的请求行,响应状态码数据,记录响应头信息
  7. FULL;记录完成的请求 响应数据
  8. */
  9. @Bean
  10. public Logger.Level level(){
  11. return Logger.Level.FULL;
  12. }
  13. }

3.3 改造接口

  1. /**
  2. *
  3. * feign声明式接口。发起远程调用的。
  4. *
  5. String url = "http://FEIGN-PROVIDER/goods/findOne/"+id;
  6. Goods goods = restTemplate.getForObject(url, Goods.class);
  7. *
  8. * 1. 定义接口
  9. * 2. 接口上添加注解 @FeignClient,设置value属性为 服务提供者的 应用名称
  10. * 3. 编写调用接口,接口的声明规则 和 提供方接口保持一致。
  11. * 4. 注入该接口对象,调用接口方法完成远程调用
  12. *
  13. */
  14. @FeignClient(value = "FEIGN-PROVIDER",configuration = FeignLogConfig.class)
  15. public interface GoodsFeignClient {
  16. @GetMapping("/goods/findOne/{id}")
  17. public Goods findGoodsById(@PathVariable("id") int id);
  18. }

configuration = FeignLogConfig.class