OpenFeign服务接口调用的过程详解

 更新时间:2022年10月8日 10:12  点击:189 作者:小钟要学习!!!

OpenFeign服务接口调用

1、概述

Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单。它的使用方法是定义一个服务接口然后在上面添加注解。

Feign也支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。

Feign可以与Eureka和Ribbon组合使用以支持负载均衡

源码地址: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是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>

2、OpenFeign使用步骤

1、创建接口和使用注解@FeignClient

2、新建模块cloud-consumer-feign-order80

3、修改pom.xml依赖文件

<?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>springcloud2022</artifactId>
        <groupId>com.zcl.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

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

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <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>com.zcl.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>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pA7pLsSP-1664844187557)(image/42、feign整合Ribbon.png)]

4、添加YAML配置文件

不将模块注册到Eureka服务中心

server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

5、创建启动类

既然使用的是OpenFeign那必须使用@EnableFeignClients注解进行开启

package com.zcl.springcloud;

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

/**
 * 描述:Feign项目启动类
 *
 * @author zhong
 * @date 2022-09-19 13:32
 */
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}

6、业务类

业务逻辑接口+@FeignClient注解完成服务调用,找指定微服务的实例和调用地址,访问的就是8001对外暴露的地址

主启动类上必须使用@EnableFeignClients注解进行激活开启

package com.zcl.springcloud.service;

import com.zcl.springcloud.entities.CommonResult;
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;

/**
 * 描述:Feign业务测试接口
 *
 * @author zhong
 * @date 2022-09-19 13:35
 */
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    /**
     * 根据id去调用
     * @param id
     * @return
     */
    @GetMapping("/payment/get/{id}")
    CommonResult getPaymentById(@PathVariable("id") Long id);
}

上面定义的接口其实就是服务提供者对外暴露的接口

7、创建控制器

package com.zcl.springcloud.controller;

import com.zcl.springcloud.entities.CommonResult;
import com.zcl.springcloud.entities.Payment;
import com.zcl.springcloud.service.PaymentFeignService;
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 javax.annotation.Resource;

/**
 * 描述:测试控制器
 *
 * @author zhong
 * @date 2022-09-19 14:11
 */
@Slf4j
@RestController
public class OrderFeignController {

    /**
     * 注入Feign业务接口
     */
    @Resource
    private PaymentFeignService paymentFeignService;

    /**
     * 测试调用服务接口
     * @param id
     * @return
     */
    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id) {
        // 调用服务接口
        return paymentFeignService.getPaymentById(id);
    }
}

8、启动项目测试

  • 先启动7001、7002Eureka集群
  • 再启动8001、8002两个微服务提供者
  • 启动OpenFeign项目80
  • 调用接口访问http://localhost/consumer/payment/get/1

多请求两回会发现一样的有轮询负载均衡的效果

Feign自带负载均衡配置项

{
  "code": 200,
  "message": "查询成功,当前提供者端口号为:8002",
  "data": {
    "id": 1,
    "serial": "1515154151515"
  }
}

3、OpenFeign超时控制

1、在8001提供者上添加一个新的控制器

/**
 * 测试Feign程序访问停止三秒
 * @return
 */
@GetMapping("/feign/timeout")
public String paymentFeignTimeOut(){
    try {
        // 程序停止三秒
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return serverPort;
}

2、在消费者Feign80上添加接口

package com.zcl.springcloud.service;

import com.zcl.springcloud.entities.CommonResult;
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;

/**
 * 描述:Feign业务测试接口
 *
 * @author zhong
 * @date 2022-09-19 13:35
 */
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {

    /**
     * 测试请求三秒不响应接口
     * @return
     */
    @GetMapping("/payment/feign/timeout")
    String paymentFeignTimeOut();
}

3、在FeignOrder80消费者控制器上添加接口访问

/**
 * 注入Feign业务接口
 */
@Resource
private PaymentFeignService paymentFeignService;

/**
 * 测试超时
 * @return
 */
@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeOut()
{
    return paymentFeignService.paymentFeignTimeOut();
}

4、启动项目测试

  • 先自测访问提供者的业务是否正常:http://localhost:8001/payment/feign/timeout(等待三秒再响应结果)
  • 通过Feign-Order80消费者的接口测试调用提供者的访问是否正常:http://localhost/consumer/payment/feign/timeout

默认连接是1秒钟,程序设置了三秒导致连接超时

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MhfmrywP-1664844187558)(image/43、Feign连接超时.png)]

后端超时报错

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a4usrSfL-1664844187558)(image/44、后端超时.png)]

5、在YAML配置文件中开启超时连接

设置配置文件下面的ribbon连接时间后等待三秒访问正常不会再报错

server:
  port: 80
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
  #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
  ReadTimeout: 5000
  #指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000

4、OpenFeign日志打印功能

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

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

1、日记级别

NONE:默认的,不显示任何日志;

BASIC:仅记录请求方法、URL、响应状态码及执行时间;

HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息;

FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据。

2、配置日记级别配置类

注意不要导错包

返回的日记级别对应上面的4个

package com.zcl.springcloud.config;

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

/**
 * 描述:Feign日记级别配置
 *
 * @author zhong
 * @date 2022-09-19 15:27
 */
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel()
    {
        return Logger.Level.FULL;
    }
}

3、YAML配置文件开启日记信息打印

logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.zcl.springcloud.service.PaymentFeignService: debug

启动羡慕测试输出内容

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-z2Fg4dyi-1664844187559)(image/45、Feign日记输出内容.png)]

到此这篇关于OpenFeign服务接口调用的文章就介绍到这了,更多相关OpenFeign接口调用内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://blog.csdn.net/baidu_39378193/article/details/1271589

[!--infotagslink--]

相关文章

  • Spring AOP 对象内部方法间的嵌套调用方式

    这篇文章主要介绍了Spring AOP 对象内部方法间的嵌套调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-08-29
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • c# 三种方法调用WebService接口

    这篇文章主要介绍了c# 三种方法调用WebService接口的相关资料,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-07
  • 完美解决SpringCloud-OpenFeign使用okhttp替换不生效问题

    这篇文章主要介绍了完美解决SpringCloud-OpenFeign使用okhttp替换不生效问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-02-25
  • vue接口请求加密实例

    这篇文章主要介绍了vue接口请求加密实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-12
  • js实现调用网络摄像头及常见错误处理

    这篇文章主要介绍了js实现调用网络摄像头及常见错误处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-03-07
  • c#动态调用Webservice的两种方法实例

    这篇文章介绍了c#动态调用Webservice的两种方法实例,有需要的朋友可以参考一下...2020-06-25
  • c#中WebService的介绍及调用方式小结

    这篇文章主要给大家介绍了关于c#中的WebService及其调用方式的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • 解决Vue watch里调用方法的坑

    这篇文章主要介绍了解决Vue watch里调用方法的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-07
  • 解决vue watch数据的方法被调用了两次的问题

    这篇文章主要介绍了解决vue watch数据的方法被调用了两次的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-11-07
  • C#中加载dll并调用其函数的实现方法

    下面小编就为大家带来一篇C#中加载dll并调用其函数的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • C#简单了解接口(Interface)使用方法

    这篇文章主要介绍了C#简单了解接口(Interface)使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-12-08
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • C# Rx的主要接口深入理解

    这篇文章主要介绍了C# Rx的主要接口深入理解的相关资料,需要的朋友可以参考下...2020-06-25
  • PHP调用MySQL存储过程并返回值实现程序

    本文章来给大家详细介绍在php中如何来调用执行mysql存储过程然后返回由存储过程返回的值了,有需要了解的同学可进入参考。 。调用存储过程的方法。 a。如果存储过...2016-11-25
  • Feign接口方法返回值设置方式

    这篇文章主要介绍了Feign接口方法返回值设置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-08
  • C#异步调用的好处和方法分享

    我们要明确,为什么要进行异步回调?众所周知,普通方法运行,是单线程的,如果中途有大型操作(如:读取大文件,大批量操作数据库,网络传输等),都会导致方法阻塞,表现在界面上就是,程序卡或者死掉,界面元素不动了,不响应了...2020-06-25
  • C#调用python脚本的方法步骤(2种)

    这篇文章主要介绍了C#调用python脚本的方法步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-06-25
  • javascript实现方法调用与方法触发小结

    这篇文章主要介绍了javascript实现方法调用与方法触发小结的相关资料,需要的朋友可以参考下...2016-03-30
  • 如何设计一个安全的API接口详解

    在日常开发中,总会接触到各种接口,前后端数据传输接口,第三方业务平台接口,下面这篇文章主要给大家介绍了关于如何设计一个安全的API接口的相关资料,需要的朋友可以参考下...2021-08-12