OpenFeign服务接口调用

官网: https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign

概述

Feign 是一个声明式WebService客户端.使用Feign能让编写WebService客户端更加简单.

它的使用方法是定义一个服务接口然后在上面添加注解.Feign也支持可拔插式的编码器和解码器,Spring Cloud对Feign进行了封装,使其支持了SpringMVC标准注解和HttpMessageConverters,Feign可以与Eureka和Ribbon组合使用以支持负载均衡.

GitHub: https://github.com/spring-cloud/spring-cloud-openfeign

Feign能干什么

Feign 旨在是编写Java Http客户端变得更容易
前面在使用Ribbon+RestTemplate时,利用RestTemplate对http请求的封装处理,形成了一套模板化的调用方法.
但是在实际开发中,由于对服务依赖的调用可能不止一处,往往一个接口会被多处调用,所以通常都会针对每个微服务自行封装一些客户端来包装这些依赖服务的调用.所以,Feign在此基础上做了进一步封装,由他来帮助我们定义和实现依赖服务接口的定义.
在Feign的实现下,我们只需创建一个接口并使用注解方式来配置它(以前是Dao接口上面标注Mapper注解,现在是在一个微服务接口上标注一个Feign注解即可),即可完成对服务提供方的接口绑定,简化了使用Spring cloud Ribbon时,自动封装服务调用客户端的开发量.
Feign集成了Ribbon
利用Ribbon维护了Payment的服务列表信息,并且通过轮询实现了客户端的负载均衡,而与Ribbon不同是,通过Feign只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务调用.

Feign 和OpenFeign两者之间的区别
FeignOpenFeign
Feign是SpringCloud组件中的一个轻量级RESTful的Http服务客户端Feign内置了Ribbon,用来做客户端负责均衡,去调用注册中心的服务.Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务OpenFeign是Spring Cloud在Feign的基础上支持了SpringMVC的注解,如@RequesMapping等等.OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务

OpenFeign的使用步骤

1.接口+ 注解

微服务调用接口+ @FeignClient

2.新建cloud-consumer-feign-order80
原则:

Feign在消费端使用
在这里插入图片描述

3.pom
  <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

4.yml
server:
  port: 80

spring:
  application:
    name: cloud-order-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource #当前数据源操作类型
    driver-class-name: org.gjt.mm.mysql.Driver   # mysql驱动包
    url: jdbc:mysql://127.0.0.1:3306/db2019?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
    username: root
    password: root


eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
    register-with-eureka: true # 表示是否将自己注册进EurekaServer 默认为TRUE
5.主启动

在主启动类上加上开启@feignClient注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients  // 开启fegin功能
public class OrderFeignApplication80 {

    public static void main(String[] args) {
        SpringApplication.run(OrderFeignApplication80.class,args);
    }
}
6.业务类
  1. 定义feign接口:
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")  // 微服务名称
public interface PaymentFeignService {

    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);

}
  1. 写controller类调用OpentFeign接口

@RestController
public class OrderFeignController {


    @Autowired
    private PaymentFeignService paymentFeignService;

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){

        CommonResult<Payment> paymentById = paymentFeignService.getPaymentById(id);
        System.out.println(paymentById);

        return paymentById;
        
    }
}

在这里插入图片描述

7.测试

测试路径:http://localhost/consumer/payment/get/1
在这里插入图片描述

8.总结

Feign调用流程
在这里插入图片描述

OpentFeign超时控制

通常业务在处理过程中,有些业务场景处理额能会导致超时。OpentFeign客户端等待时间超过了默认值,直接返回报错。为了避免这种情况,有时候我们需要设置Fegin客户端的超时控制。
OpentFeign底层就是Ribbon技术。Ribbon默认等待是1s.
超时配置

1.服务提供方模拟一个长时间服务:
    @GetMapping(value = "/payment/timeout")
    public String getTimeOut(){
        // 模拟运行时间超过3s
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;

    }
2. Feign接口调用
  @GetMapping(value = "/payment/timeout")
    public String getTimeOut();
3. 调用路径
@GetMapping(value = "/payment/timeout")
    public String getTimeOut(){
        return paymentFeignService.getTimeOut();
    }
测试

服务提供方直接测试:http://localhost:8001/payment/timeout
在这里插入图片描述
服务调用方测试
http://localhost/payment/timeout
在这里插入图片描述
解决方案:设置超时时间
在yml文件中开启配置

eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
    register-with-eureka: true # 表示是否将自己注册进EurekaServer 默认为TRUE
# 设置Feign客户端超时时间(OpenFeign默认支持Ribbon)。
ribbon:
  # 指的是建立连接所用的时间,适用于网络状态正常情况下,两端连接所用的时间
  ReadTimeout: 5000
  # 指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000

OpenFeign日志打印功能

1.日志打印功能

Feign提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解Feign中Http请求的细节。

2.是什么

也就是对Feign接口的调用情况进行监控和输出。

3.日志级别

NONE: 默认的,不显示任何日志
BASIC: 仅记录请求方法,URL,响应状态码及执行时间
HEADERS:除了BASIC中定义的信息外,还有请求和响应的头信息
FULL:除了HEADERS中定义的信息外还有请求和响应的正文及元数据

4.配置日志bean
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {

    @Bean
    Logger.Level feignLoggerLeve1(){

        return Logger.Level.FULL;
    }
}

5.yml文件里需要开启日志的Feign客户端
logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.atguigu.springcloud.feign.PaymentFeignService: debug
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值