openFeign是一个声明式的web服务客户端,让编写web服务客户端变得非常容易,只需要创建一个接口并在接口上添加注解即可。
openFeign集成了Ribbon
使用openFeign步骤
**一、**建module。引入pom.xml中openFeign的依赖
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
**二、**yml常规配置即可
server:
port: 80
eureka:
client:
register-with-eureka: true
fetchRegistry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
**三、**主启动加入@EnableFeignClients //使用feign激活并开启
@SpringBootApplication
@EnableFeignClients //使用feign激活并开启
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class,args);
}
}
**四、**建接口用来调用payment接口上加入@FeignClient注解
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
public CommonResult getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();
}
其中@FeignClient(value = “CLOUD-PAYMENT-SERVICE”)
value是payment的spring:
application:
name:名称
eureka中的Application
五、控制层
@RestController
@Slf4j
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);
}
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout(){
//openfeign---ribbon,客户端一般默认等待一秒钟
return paymentFeignService.paymentFeignTimeout();
}
}
payment中
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout(){
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
启动即可调用/payment/feign/timeout 不出意外会报错因为openFeign默认等待1秒钟超过后报错,
解决办法:yml文件中加入
#设置feign客户端超时时间(openFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况是正常的情况,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接之后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
来更改openFeign默认等待时间
openFeign日志打印功能
feign提供了日志打印功能,可以通过配置来调整日志级别,从而了解Feign中HTTP请求的细节
日志级别有一下四个:
none:默认的,不显示任何日志
basic:仅记录请求方法,URL响应状态码,及执行时间
headers:除了basic中定义的信息之外还有请求和响应头信息
full:除了headers中定义的信息之外,还有请求和响应的正文及元数据
具体配置如下:
一、 新建配置类FeignConfig
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
二、yml文件
logging:
level:
#feogn日志以什么级别监视那个接口
com.zhutianlu.springcloud.service.PaymentFeignService: debug
其中com.zhutianlu.springcloud.service.PaymentFeignService为监控接口的全路径