openFeign服务调用

简介

Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单。它的使用方法是定义一个服务接口然后在上面添加注解。
Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。

一句话:定义微服务的接口,加入Feign相关注解就能实现微服务之间的调用。

使用

  1. 加入依赖:
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. 在主启动类上加入@EnableFeignClients
  2. 定义服务接口
    这里表明getPaymentById会调用"CLOUD-PAYMENT-SERVICE"服务上的"/payment/get/{id}"接口。
    等价于之前的http://CLOUD-PAYMENT-SERVICE/payment/get/id
@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);//与服务方controller中方法名保持一致
}

注意:@PathVariable 中一定要写"id",因为feign向前兼容JDK1.5之前需要写。

  1. controller层注入调用
	@Resource
    private PaymentFeignService paymentFeignService;
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable Long id){
        return paymentFeignService.getPaymentById(id);
    }

特性

内置ribbon提供负载均衡
超时控制,消费断1s内没有接收到响应则报错。
日志增强。

设置超时时间:

application.yml

feign:
  client:
    config:
      default:
        connect-timeout: 5000
        read-timeout: 5000
日志增强:

配置类:

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feiginLoggerLever(){
        return Logger.Level.FULL;
    }
}

在application.yml中添加日志需要记录的接口:

logging:
  level:
    org.example.springcloud.service.PaymentFeignService: debug

再次运行,调用接口时会出现下面的日志情况。
在这里插入图片描述

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值