文章目录
一、Feign概述
Feign 是一个声明式webservice客户端,使用Feign 能让编写Web Service客户端更简单 ,它的使用方法是 定义一个服务接口然后在上面添加注解。Spring Cloud对Feign 进行了封装,使其支持了Spring Mvc 标准注解和HttpMessageConverters ,Fegin可以与Eureka 和Ribbon组合使用已支持负载均衡
Feign的实现流程
首先通过 @EnableFelgnClients注解开启FeignClient的功能 ,只有这个注解存在,才会在程序启动时开启对 @FeignClient注解的包扫描。
根据Feign的规则实现接口,并在接口上加上@FeignClient注解。
程序启动后,会进行包扫描,扫描所有的@FeignClient注解的类,并将这些信息注入到lOC容器中。
当接口中的方法被调用时,通过JDK的动态代理生成具体的 RequestTemplate模板对象 。
根据RequestTemplate再生成HTTP的Request对象。
Request对象交给Client处理,其中Client网络请求框架可以是 HttpURLConnection, HttpClient与OkHttp(主要看依赖是什么)。
最后,Client被封装到LoadBalanceClient类,该类结合Ribbon做到了负载均衡。
二、OpenFeign
官网地址:https://spring.io/projects/spring-cloud-openfeign
OpenFeign 全称 Spring Cloud OpenFeign,它是 Spring 官方推出的一种声明式服务调用与负载均衡组件,它的出现就是为了替代进入停更维护状态的 Feign。
OpenFeign 是 Spring Cloud 对 Feign 的二次封装,它具有 Feign 的所有功能,并在 Feign 的基础上增加了对 Spring MVC 注解的支持,例如 @RequestMapping、@GetMapping 和 @PostMapping 等。
OpenFeign 常用注解
Feign和OpenFeign 的区别
三、 OpenFeign 整合服务接口调用
1、新建cloud-consumer-feign-order80
2、添加依赖
<?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>cloud2024</artifactId>
<groupId>com.my.springcloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloud-consumer-order80</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>com.my.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>${project.version}</version>
</dependency>
<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>
<!--包含了sleuth+zipkin-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.cloud</groupId>-->
<!-- <artifactId>spring-cloud-starter-zipkin</artifactId>-->
<!-- </dependency>-->
</dependencies>
</project>
3、配置yml
server:
port: 80
spring:
application:
name: cloud-order-service
#eureka配置
eureka:
client:
#表示是否将自己注册进EurekaServer默认为true
register-with-eureka: true
#是否从EurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
fetchRegistry: true
service-url:
#defaultZone: http://localhost:7001/eureka # 单机版
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群版
instance:
#向注册中心注册服务ID
instance-id: ${spring.cloud.client.ip-address}:${server.port}
prefer-ip-address: true #访问路径可以显示IP地址
#Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
lease-renewal-interval-in-seconds: 30
#Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
lease-expiration-duration-in-seconds: 90
4、主启动类上添加@EnableFeignClients
package com.my.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class OrderFeignApp80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignApp80.class, args);
}
}
5、添加业务 Controller
package com.my.springcloud.controller;
import com.my.springcloud.entities.Payment;
import com.my.springcloud.service.PaymentFeignService;
import com.my.springcloud.utils.RestResponse;
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;
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/get/{id}")
public RestResponse<Payment> getPaymentById(@PathVariable("id") Long id) {
return paymentFeignService.getPaymentById(id);
}
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout() {
// OpenFeign客户端一般默认等待1秒钟
return paymentFeignService.paymentFeignTimeout();
}
}
6、新增OpenFeign业务接口
定义业务逻辑接口+@FeignClient 配置调用 provider服务
1、新建PaymentFeignService接口并在接口上添加@FeignClient 注解
**value = "CLOUD-PAYMENT-SERVICE" 代表调用的是哪个微服务(就是yml配置文件中的application.name:微服务名称)**
package com.my.springcloud.service;
import com.my.springcloud.entities.Payment;
import com.my.springcloud.utils.RestResponse;
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;
/**
* @auther
* @desc 定义Open Feign接口, 调用 provider服务
*/
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
public RestResponse<Payment> getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();
}
打开eureka注册中心也可以看到调用服务名称
注意事项
PaymentFeignService里面定义的方法签名和参数要和provider提供服务的保持一致
cloud-provider-payment8001 服务提供者
cloud-provider-payment8001微服务名字
7、测试OpenFegin
访问 http://localhost/consumer/payment/get/1
再次访问效果如下
四、OpenFeign配置日志增强功能
OpenFeign提供了日志打印功能,我们可以通过配置来调整日恙级别,从而了解Feign 中 Http请求的细节。
说白了就是对Feign接口的调用情况进行监控和输出
日志级别
NONE:默认的,不显示任何日志;
BASIC:仅记录请求方法、URL、响应状态码及执行时间;
HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息;
FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。
1.在配置类中添加日志配置
import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @auther lml
* @desc Openfegin日志增强配置
*/
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
注:这里的logger是feign包里的
2.yml文件配置哪个接口以什么日志级别监听
#设置openfeign日志增强
logging:
level:
# feign日志以什么级别监控哪个接口
com.my.springcloud.service.PaymentFeignService: debug
也可以配置包路径
logging:
level:
com.my.springcloud.service: debug
3.测试open fegin日志增强:
五、OpenFeign超时控制
前面简单介绍了Feign和OpenFeign的关系,言归正传,接下来我们看看OpenFeign如何设置调用超时,openFeign其实是有默认的超时时间的,默认分别是连接超时时间10秒、读超时时间60秒,源码在feign.Request.Options#Options()这个方法中。
Feign的原理
虽然有了接口,但是仅仅有接口是不够的,因为接口又不能创建对象,我们得需要对象。
Feign为了方便我们为接口创建对象,提供的Feign.Builder这个内部类
OpenFeign 超时场景
默认Feign 客户端只等待1秒钟,但是服务端处理需要超过1秒钟,导致Feign 客户端不想等待了,直接返回报错
为了避免这样的情况,有时候我们需要设置Feign客户端的超时控制
一、服务提供方8001写暂停程序模拟调用超时
1.在cloud-provider-payment8001 模拟调用超时
//模拟openfegin调用超时
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout() {
// 业务逻辑处理正确,但是需要耗费3秒钟
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
2、服务消费方80添加方法
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();
}
3、服务消费方80添加超时方法
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout() {
// OpenFeign客户端一般默认等待1秒钟
return paymentFeignService.paymentFeignTimeout();
}
}
4、模拟OpenFeign超时
OpenFeign 只等待1秒,超过后报错:
访问 http://localhost:8001/payment/feign/timeout
5、在yml配置超时控制
ribbon 整合了,支持负载均衡,它的超时控制也由最底层的 ribbon 进行控制,yml 添加配置:
#设置feign 客户端超时时间(openFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
重启80后 测试
数据在3秒后返回,没有报错。
OpenFeign 默认是1秒钟,部分业务时间长了可以通过这个方法进行设置
Feign超时优化
设置Ribbon超时时间
ribbon:
ReadTimeout: 5000 # 请求连接的超时时间
ConnectionTimeout: 10000 # 请求处理的超时时间
设置OpenFeign超时时间
feign:
client:
config:
default: # 所有服务
connect-timeout: 5000 # 配置指定服务连接超时时间
read-timeout: 5000 # 配置指定服务等待超时时间
请求连接优化
OpenFeign 底层通信组件默认使用 JDK 自带的 URLConnection 对象进行 HTTP 请求的,因为没有使用连接池,所以性能不是很好。我们可以将 OpenFeign 的通讯组件,手动替换成像 Apache HttpClient 或 OKHttp 这样的专用通信组件,这些的专用通信组件自带连接池可以更好地对 HTTP 连接对象进行重用与管理,同时也能大大的提升 HTTP 请求的效率。接下来我以 Apache HttpClient 为例,演示一下专用通讯组件的使用。
1 引入Apache HttpClient依赖
<!-- 添加 openfeign 框架依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 添加 httpclient 框架依赖 -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2 开启Apache HttpClient使用
# feign超时设置
feign:
client:
config:
default: # default全局的配置
loggerLevel: BASIC # 日志级别,BASIC就是基本的请求和响应信息
httpclient:
enabled: true # 开启feign对HttpClient的支持
max-connections: 200 # 最大的连接数
max-connections-per-route: 50 # 每个路径的最大连接数