SpringCloud服务接口调用OpenFegin

2023-10-25 11:19:52 浏览数 (1)

概述

OpenFeign是什么

  • 官网解释

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

  • Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需创建一个接口并在接口上添加注解即可
  • GitHub源码地址

Fegin因何出现?

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

Fegin与OpenFegin的差异

Feign

OpenFeign

Feign是Spring Cloud组件中的一个轻量级RESTful的HTTP服务客户端Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务

OpenFeign是Spring Cloud 在Feign的基础上支持了SpringMVC的注解,如@RequesMapping等等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-feign</artifactId></dependency>

<dependency><groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId></dependency>

OpenFeign的使用

  • 核心思想——接口 注解
    • 微服务调用接口 @FeignClient

案例实现

环境搭建
  • 创建模块cloud-consumer-feign-order80
  • Feign在消费端使用

  • pom文件依赖引入
代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <parent>
    <artifactId>cloud2023</artifactId>
    <groupId>top.ljzstudy.springcloud</groupId>
    <version>1.0-SNAPSHOT</version>
  </parent>
  <modelVersion>4.0.0</modelVersion>

  <artifactId>cloud-consumer-feign-order80</artifactId>

  <dependencies>
    <!--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>
    <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
    <dependency>
      <groupId>top.ljzstudy.springcloud</groupId>
      <artifactId>cloud-api-commons</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>
    <!--web-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--一般基础通用配置-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>
  • 编写Application.yaml文件,配置文件
代码语言:javascript复制
server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  • 编写主启动类配置
代码语言:javascript复制
package top.ljzstudy.springcloud;

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

@SpringBootApplication
@EnableFeignClients//开启OpenFeginClient
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class,args);
    }
}
编写业务
  • 编写业务接口
    • 业务逻辑接口 @FeignClient配置调用provider服务
    • 新建PaymentFeignService接口并新增注解@FeignClient
代码语言:javascript复制
package top.ljzstudy.springcloud.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import top.ljzstudy.springcloud.entities.CommonResult;
import top.ljzstudy.springcloud.entities.PaymentEntity;

@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")//主启动类必须开启EnableFeginClients
public interface FeignPaymentService {
    @GetMapping("/payment/get/{id}")
    CommonResult<PaymentEntity> getPaymentEntityById(@PathVariable("id") Long id);
}
  • 编写Controller
代码语言:javascript复制
package top.ljzstudy.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import top.ljzstudy.springcloud.entities.CommonResult;
import top.ljzstudy.springcloud.entities.PaymentEntity;
import top.ljzstudy.springcloud.service.FeignPaymentService;

import javax.annotation.Resource;

@RestController
@Slf4j
public class FeignPaymentController {
    @Resource
    private FeignPaymentService feignPaymentService;

    @GetMapping("/consumer/payment/getEntity/{id}")
    public CommonResult<PaymentEntity> getPaymentEntity(@PathVariable("id") Long id){
        return feignPaymentService.getPaymentEntityById(id);
    }
}
测试
  • 先启动2个eureka集群7001/7002
  • 再启动2个微服务8001/8002
  • 启动OpenFeign启动
  • 访问http://localhost/consumer/payment/getEntity/1
代码语言:javascript复制
GET http://localhost:80/consumer/payment/getEntity/1

HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 14 Sep 2023 17:21:33 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{
  "code": 200,
  "message": "successful query data to id =1 from port number : 8001",
  "data": {
    "id": 1,
    "serial": "ljzTest01"
  }
}

Response code: 200; Time: 1031ms; Content length: 116 bytes
  • 短时间内重复多次访问,结果均在8001/8002间反复跳转

结论

  • Feign自带负载均衡配置项
  • 负载均衡策略默认轮询方式

OpenFeign超时控制

解决了什么问题?

场景模拟,服务端完成一个业务所需时间假定为3sec,客户端最多等待时间为2sec.必然产生矛盾

场景模拟
  • 超时设置,故意设置超时演示出错情况
  • 服务提供方8001故意写暂停程序
代码语言:javascript复制
package top.ljzstudy.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import top.ljzstudy.springcloud.entities.CommonResult;
import top.ljzstudy.springcloud.entities.PaymentEntity;
import top.ljzstudy.springcloud.service.PaymentService;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    ....
    
    /**
     * OpenFeigin超时控制
     *      业务场景-->服务提供者业务逻辑处理完成需要3min,客户端需求2min,存在时间差
     *      时间差导致超时调用报错,此处采用睡眠模拟延时
     */
    @GetMapping("/payment/feign/timeout")
    public String paymentFeignTimeout(){
        System.out.println("*****paymentFeignTimeOut from port: " serverPort);
        //暂停几秒钟线程
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
	......
}
  • 服务消费方80添加超时方法PaymentFeignService
代码语言:javascript复制
package top.ljzstudy.springcloud.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import top.ljzstudy.springcloud.entities.CommonResult;
import top.ljzstudy.springcloud.entities.PaymentEntity;

@Component
@FeignClient("CLOUD-PAYMENT-SERVICE")
public interface FeignPaymentService {
    //模拟业务场景接口
    @GetMapping("/payment/feign/timeout")
    String paymentFeignTimeout();
}
  • 服务消费方80添加超时方法OrderFeignController
代码语言:javascript复制
package top.ljzstudy.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import top.ljzstudy.springcloud.entities.CommonResult;
import top.ljzstudy.springcloud.entities.PaymentEntity;
import top.ljzstudy.springcloud.service.FeignPaymentService;

import javax.annotation.Resource;

@RestController
@Slf4j
public class FeignPaymentController {
    @Resource
    private FeignPaymentService feignPaymentService;

    //模拟业务方法
    @GetMapping("/consumer/payment/feign/timeout")
    public String paymentFeignTimeout(){
        //openfeign-ribbon 客户端一般默认等待1秒
        return feignPaymentService.paymentFeignTimeout();
    }
}
  • 测试
    • 访问http://localhost/consumer/payment/feign/timeout
代码语言:javascript复制
GET http://localhost/consumer/payment/feign/timeout

HTTP/1.1 500 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Thu, 14 Sep 2023 17:37:35 GMT
Connection: close

{
  "timestamp": "2023-09-14T17:37:35.924 0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "status 404 reading FeignPaymentService#paymentFeignTimeout()",
/*
* 提示:该行代码过长,系统自动注释不进行高亮。一键复制会移除系统注释 
* "trace": "feign.FeignException$NotFound: status 404 reading FeignPaymentService#paymentFeignTimeout()rntat feign.FeignException.clientErrorStatus(FeignException.java:165)rntat feign.FeignException.errorStatus(FeignException.java:141)rntat feign.FeignException.errorStatus(FeignException.java:133)rntat feign.codec.ErrorDecoder$Default.decode(ErrorDecoder.java:92)rntat feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:151)rntat feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:80)rntat feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)rntat com.sun.proxy.$Proxy149.paymentFeignTimeout(Unknown Source)rntat top.ljzstudy.springcloud.controller.FeignPaymentController.paymentFeignTimeout(FeignPaymentController.java:27)rntat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)rntat sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)rntat sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)rntat java.lang.reflect.Method.invoke(Method.java:498)rntat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)rntat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)rntat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)rntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)rntat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)rntat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)rntat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)rntat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)rntat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)rntat org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)rntat javax.servlet.http.HttpServlet.service(HttpServlet.java:634)rntat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)rntat javax.servlet.http.HttpServlet.service(HttpServlet.java:741)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)rntat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)rntat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)rntat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)rntat org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:108)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)rntat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)rntat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)rntat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)rntat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)rntat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)rntat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)rntat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526)rntat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)rntat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)rntat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)rntat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)rntat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)rntat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)rntat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)rntat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)rntat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)rntat java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)rntat java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)rntat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)rntat java.lang.Thread.run(Thread.java:748)rn",
*/
  "path": "/consumer/payment/feign/timeout"
}

Response code: 500; Time: 281ms; Content length: 6283 bytes
  • 现象解释
    • OpenFeign默认等待1秒钟,超过后报错

OpenFegin超时控制机制与自定义

  • 是什么

  • 默认Feign客户端只等待一秒钟,但是服务端处理需要超过1秒钟,
  • 导致Feign客户端不想等待了,直接返回报错。
  • 为了避免这样的情况,有时候我们需要设置Feign客户端的超时控制。
  • yml文件中开启配置
  • OpenFeign默认支持Ribbon
  • 在yaml中开启配置与自定义
代码语言:javascript复制
#设置feign客户端超时时间
feign:
  client:
    config:
      default:
        connect-timeout: 5000  #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
        read-timeout: 5000  #指的是建立连接后从服务器读取到可用资源所用的时间

OpenFeigin日志打印功能

是什么?

  • Feign 提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解 Feign 中 Http 请求的细节。
  • 说白了就是对Feign接口的调用情况进行监控和输出
  • 日志级别
    • NONE:默认的,不显示任何日志;
    • BASIC:仅记录请求方法、URL、响应状态码及执行时间;
    • HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息;
    • FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据。
  • 如何配置?
    • 编写配置类(配置日志bean)
代码语言:javascript复制
package top.ljzstudy.springcloud.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}
  • YML文件里需要开启日志的Feign客户端
代码语言:javascript复制
logging:
  level:
    # feign日志以什么级别监控哪个接口
    top.ljzstudy.springcloud.service.FeignPaymentService: debug
  • 后台日志查看

0 人点赞