描述:Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可。
使用:
1、 微服务调用接口+@FeignClient
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE") //CLOUD-PAYMENT-SERVICE是服务提供者注册到eureka的服务名称
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}") //服务提供者的请求路径
CommonResult getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/timeout")
CommonResult timeOut();
}
2、引入依赖(需要把ribbon排除掉)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.2</version>
<exclusions>
<exclusion>
<artifactId>spring-cloud-netflix-ribbon</artifactId>
<groupId>org.springframework.cloud</groupId>
</exclusion>
</exclusions>
</dependency>
3、yml配置eureka(不需要注入eureka服务)
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
4、主启动类要加@EnableFeignClients注解
5、controller层
@RestController
@RequestMapping("/payment")
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
@GetMapping("/timeout")
public CommonResult getPaymentById(){
return paymentFeignService.timeOut();
}
}
小总结:Feign自带负载均衡配置项
服务接口调用超时配置(在yml里面进行配置):
feign:
client:
config:
default:
# 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
ConnectTimeOut: 5000 #默认是十秒
# 指的是建立连接后从服务器读取可用资源所用的时间
ReadTimeOut: 5000 #默认是60秒
日志打印:
日志级别:
NONE:默认的,不显示任何日志;
BASIC:仅记录请求方法、URL、响应状态码及执行时间;
HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息;
FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据
日志级别设置:
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLogger(){
return Logger.Level.FULL;
}
}
logging:
level:
com.openfeign.cloud.service.PaymentFeignService: debug