Open Feign简介
- open feign 是什么
Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需 创建一个接口并在接口上添加注解即可 - open feign的作用
Feign旨在使编写Java Http客户端变得更容易。前面在使用Ribbon+ RestTemplate时,利用RestTemplate对http请求的封装处理,形成了一套模版化的调用方法。 但是在实际开发中,由于对服务依赖的调用可能不止一处, 往往一个接口会被多处调用, 所以通常都会针对每个微服务自行封装-些客户端类来包装这些依赖服务的调用。所以,Feign在此基础上做了进一步封装, 由他来帮助我们定义和实现依赖服务接口的定义。在Feign的实现下,我们只需创建一 个接口并使用注解的方式来配置它(以前是Dao接口上面标注Mapper注解,现在是一 个微服务接口上面标注一 个Feign注解即可),即可完成对服务提供方的接口绑定,简化了使用Spring cloud Rilbbon时,自动封装服务调用客户端的开发量。 - feign与open feign的区别
open feign的使用
- pom文件引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- yml文件编写配置
server:
port: 80
eureka:
client:
register-with-eureka: true
fetch-registry: true
# 注册进入的eureka server地址
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
- 启动类新增注解
@EnableFeignClients()
- 编写open fegin配置类
@FeignClient(value = "PROVIDER-PAYMENT") //远程调用的微服务名称
@Component
public interface PaymentOpenFeignServer {
@GetMapping("/payment/getPayment/{id}") //将要远程调用的接口配置
CommentResult getPayment(@PathVariable("id") Long id);
}
- 调用接口
@RestController
public class OpenFeignOrderController {
@Autowired
private PaymentOpenFeignServer server;
@GetMapping("/consumer/getPayment/{id}") //消费者调用的接口
CommentResult getPayment(@PathVariable("id") Long id) {
return server.getPayment(id); //调用open feign配置的接口
}
}
open feign超时控制
open feign每次请求默认了等待时间为1秒,当等待时间超过1秒的时候,open feign会直接返回time out报错信息,不再继续等待服务端请求。
修改超时配置:
ribbon:
# 指的是建立连接所用的时间,适用于网络状态正常的情况下,两端连接所用的时间
ReadTimeout: 5000
# 指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
open feign的日志管理
open feign的日志级别:
- NONE:默认的,不显示任何日志;
- BASIC:仅记录请求方法、URL、响应状态码及执行时间;
- HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息;
- FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。
open feign日志的使用方法
@Configuration
public class ApplicationContext {
@Bean
public Logger.Level toLog() {
return Logger.Level.FULL;
}
}
yml中配置日志打印信息
logging:
level:
# 配置设置的open feign接口
com.ct.consumer.server.PaymentOpenFeignServer : debug
查看控制台