1、OpenFeign介绍
- OpenFeign为了微服务之间的调用更简单。
- 相当于Ribbon + RestTemplate的封装
- 只需要定义服务绑定接口且以声明式的方法,实现服务调用
2、OpenFeign服务调用
已集成Ribbon
启动类
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class, args);
}
}
声明式接口调用微服务
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
Controller调用
@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);
}
}
总结
- 微服务调用接口+@Feign
- 自带负载均衡配置
3、OpenFeign超时控制
设置服务端响应时间3秒钟,利用openFeing调用会报错(默认等待1秒钟)
服务方微服务
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout() throws Exception {
TimeUnit.SECONDS.sleep(3);
return serverPort;
}
声明式接口调用微服务
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/feign/timeout")
String paymentFeignTimeout();
}
Controller调用
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout() {
//openFeign-ribbon,客户端一般默认等待1秒钟
return paymentFeignService.paymentFeignTimeout();
}
}
http://localhost/consumer/payment/feign/timeout
解决方式,修改yml
http://localhost/consumer/payment/feign/timeout
访问成功
4、OpenFeign日志增强
日志级别
- NONE:默认的,不显示任何日志
- BASIC:仅记录请求方法,URL,响应状态码及执行时间
- HEADERS:除了BASIC中定义之外,还有请求和响应的头信息
- FULL:除了HEADERS之外,还有请求和响应的正文及元数据
配置类
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
yml文件
访问地址查询后台