概述
OpenFeign使用步骤
-
接口+注解:微服务调用接口+@FeignClient
-
新建cloud-consumer-feign-order80
-
POM
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
-
YML
server: port: 80 eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
-
主启动:
@EnableFeignClients
package com.atguigu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableFeignClients public class OrderFeignMain80 { public static void main(String[] args) { SpringApplication.run(OrderFeignMain80.class,args); } }
-
业务类
-
业务逻辑接口+@FeignClient配置调用provider服务
-
新建PaymentFeignService接口并新增注解@FeignClient
@Component @FeignClient(value = "CLOUD-PAYMENT-SERVICE") public interface PaymentFeignService { @GetMapping(value = "/payment/get/{id}") public CommonResult getPaymentById(@PathVariable("id") Long id); }
-
控制层Controller
@RestController public class OrderFeignController { @Resource private PaymentFeignService paymentFeignService; @GetMapping(value = "/consumer/payment/get/{id}") public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){ return paymentFeignService.getPaymentById(id); } }
-
OpenFeign超时控制
-
OpenFeign默认等待一秒钟,超过后报错
-
YML文件里需要开启OpenFeign客户端超时控制
ribbon: ReadTimeout: 5000 ConnectTimeout: 5000
OpenFeign日志打印功能
-
基本概念
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IlfaMz8c-1655077941249)(F:\1111yjs\笔记\image-20220613014637151.png)]
-
日志级别
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Z9yyWkgb-1655077941250)(F:\1111yjs\笔记\SpringCloud.assets\image-20220613014739593.png)]
-
配置日志bean
package com.atguigu.springcloud.config; import feign.Logger; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FeignConfig { @Bean Logger.Level feignLoggerLevel(){ return Logger.Level.FULL; } }
-
YML文件里需要开启日志的Feign客户端
logging: level: com.atguigu.springcloud.service.PaymentFeignService: debug
-
后台日志查看