OpenFeign
基本使用
添加依赖
1 2 3 4
| <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
|
在启动类开启上添加@EnableFeignClients注解开启OpenFeign
1 2 3 4 5 6 7
| @SpringBootApplication @EnableFeignClients public class xxxApplication { public static void main(String[] args) { SpringApplication.run(xxxApplication.class,args); } }
|
通过@FeignClient注解声明FeignClient并绑定服务
1 2 3 4 5 6 7
| @Component @FeignClient(value = "serverName") public interface XxxService { @GetMapping("/helloworld") void helloworld();
}
|
服务调用
1 2 3
| @Resource XxxService xxxService; xxxService.helloworld();
|
设置客户端超时时间
OpenFeign整合了Ribbon,客户端的超时时间也由Ribbon控制
1 2 3 4 5
| ribbon: ReadTimeout: 5000 ConnectTimeout: 5000
|
开启调用日志
日志级别
- NONE:默认的,不显示任何日志;
- BASIC:仅记录请求方法、URL、相应状态码及执行时间
- HEADERS:除了BASIC中定义的信息之外,还有请求和响应头信息;
- FULL:除了HEADERS中定义的信息外,还有请求和响应的正文及元数据。
开启日志
1 2 3 4 5 6 7 8
| # 第一步,创建Feign配置类 @Configuration public class FeignLogConfiguration { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; } }
|
1 2 3 4 5
| logging: level: com.xxx.xxxFeign: debug
|
如果你不是在application.yml中配置的日志级别,而是使用logback-spring.xml,同理,在logback-spring.xml中做相应配置:
1 2 3 4
| # logback-spring.xml <logger name="com.xxx.xxx" level="DEBUG" additivity="false"> <appender-ref ref="Console"/> </logger>
|