目录
- OpenFeign服务接口调用
 - 1、概述
 - 2、OpenFeign使用步骤
 - 3、OpenFeign超时控制
 - 4、OpenFeign日志打印功能
 
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两者的区别
Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</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)]](http://img.558idc.com/uploadfile/allimg/java/2022100610203620.jpg)
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)]](http://img.558idc.com/uploadfile/allimg/java/2022100610203621.jpg)
后端超时报错
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a4usrSfL-1664844187558)(image/44、后端超时.png)]](http://img.558idc.com/uploadfile/allimg/java/2022100610203622.jpg)
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)]](http://img.558idc.com/uploadfile/allimg/java/2022100610203623.jpg)
到此这篇关于OpenFeign服务接口调用的文章就介绍到这了,更多相关OpenFeign接口调用内容请搜索自由互联以前的文章或继续浏览下面的相关文章希望大家以后多多支持自由互联!
