OpenFeign
概念:就是远程调用方法,跟Ribbon类似。可以理解为封装的一套服务接口+注解的方式的远程调用器。
OpenFeign能干什么
它的宗旨是在编写Java Http客户端接口的时候变得更加容易,其底层整合了Ribbon,所以也支持负载均衡。
之前我们使用Ribbon的时候,利用RestTemplate对Http请求进行封装处理,但是在实际开发中,由于对服务依赖的调用不可能就一处,往往一个接口会被多处调用,所以通常都会针对每个微服务自行封装一些客户端类来包装这些依赖服务的调用。所以OpenFeign在此基础之上做了进一步的封装,由它来帮助我们定义和实现依赖服务接口的定义,我们只需创建一个接口并使用注解的方式来配置它,即可完成对微服务提供方的接口绑定,简化Ribbon的操作。
具体使用
- POM 需要在父级项目引入相关依赖
<properties>
<java.version>1.8</java.version>
<spring-cloud-alibaba-version>2.2.5.RELEASE</spring-cloud-alibaba-version>
<spring-cloud-openfeign-version>2.2.6.RELEASE</spring-cloud-openfeign-version>
</properties>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>${spring-cloud-openfeign-version}</version>
</dependency>
- 子项目引入依赖
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.gek</groupId>
<artifactId>SpringCloudAlibabaMSB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gek</groupId>
<artifactId>cloudAlibaba-openFegin-8888</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>cloudAlibaba-openFegin-8888</name>
<description>cloudAlibaba-openFegin-8888</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.gek</groupId>
<artifactId>cloudalibaba-commons</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
- 主启动类加上注解@EnableFeignClients
package com.gek.cloudalibabaopenfegin8888;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients //openfeign注解
public class CloudAlibabaOpenFegin8888Application {
public static void main(String[] args) {
SpringApplication.run(CloudAlibabaOpenFegin8888Application.class, args);
}
}
- yml配置
server:
port: 8888
spring:
application:
name: nacos-consumer-openfeign
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
management:
endpoints:
web:
exposure:
include: "*"
- 调用服务提供者对外提供接口
package com.gek.cloudalibabaopenfegin8888.service;
import com.gek.cloudalibabacommons.entity.JsonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Service
/**
* 表示调用服务的名称
*/
@FeignClient("nacos-provider")
public interface OpenFeignService {
/**
* 表示调用服务的方法
* @param id
* @return
*/
@GetMapping("info/{id}")
public JsonResult<String> msbSql(@PathVariable("id") Long id);
}
6. 新建控制器远程调用服务
package com.gek.cloudalibabaopenfegin8888.controller;
import com.gek.cloudalibabacommons.entity.JsonResult;
import com.gek.cloudalibabaopenfegin8888.service.OpenFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class OpenFeignController {
@Autowired
private OpenFeignService openFeignService;
@GetMapping("info/{id}")
public JsonResult<String> msbSql(@PathVariable("id") Long id){
return openFeignService.msbSql(id);
}
}
- 测试
修改openFeign超时时间
概念
OpenFeign 客户端默认等待1秒钟,但是如果服务端业务超过1秒,则会报错。为了避免这样的情况,我们需要设置feign客户端的超时控制。
解决办法
由于OpenFeign 底层是ribbon 。所以超时控制由ribbon来控制。在yml文件中配置
超时案例演示
首先演示超时效果,我们现在9003/9004上设置一个延迟3秒执行的方法,来模仿长业务线调用。
- 在9003和9004上创建超时方法
@GetMapping("/timeOut")
public String timeOut() {
try {
System.out.println("延迟响应");
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return serverPort;
}
- 客户端8888通过OpenFeign来进行调用
service
/**
* 测试openfeign超时时间控制
* @return
*/
@GetMapping("/timeOut")
public String timeOut();
controller
@GetMapping("/testTimeOut")
public String testTimeOut(){
return openFeignService.timeOut();
}
测试结果:
时间超过1秒,报错
修改yml文件,修改openfeign的超时时间
server:
port: 8888
spring:
application:
name: nacos-consumer-openfegin
cloud:
nacos:
discovery:
server-addr: localhost:8848
#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接后从服务器读取到可用资源所用的时间
ReadTimeout: 5000
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ConnectTimeout: 5000
management:
endpoints:
web:
exposure:
include: '*'
测试结果:
可以正常响应
openFeign日志打印
日志级别:
-
NONE:默认的,不显示任何日志;
-
BASIC:仅记录请求方法、URL、响应状态码及执行时间;
-
HEADERS:除了 BASIC 中定义的信息之外,还有请求和响应的头信息;
-
FULL:除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据。
- 需要在启动类中通过@Bean注解注入OpenFeign的日志功能
package com.gek.cloudalibabaopenfegin8888;
import feign.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients //openfeign注解
public class CloudAlibabaOpenFegin8888Application {
public static void main(String[] args) {
SpringApplication.run(CloudAlibabaOpenFegin8888Application.class, args);
}
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
- 在yml中配置
server:
port: 8888
spring:
application:
name: nacos-consumer-openfeign
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
# 配置openFeign超时时间
# 设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
ReadTimeout: 5000 #指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000 #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
logging:
level:
# openfeign日志以什么级别监控哪个接口
com.gek.cloudalibabaopenfegin8888.service.OpenFeignService: debug
management:
endpoints:
web:
exposure:
include: "*"
测试效果
sentinel整合openfeign
引入OpenFegin
- 我们需要在当前的8084项目中引入对应的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 添加sentinel对openfeign的支持
#配置sentinel下的openfeign支持
feign:
sentinel:
enabled: true
- 主启动类要添加@EnableFeignClients注解
package com.gek.cloudalibabaconsumer8084;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class CloudAlibabaConsumer8084Application {
public static void main(String[] args) {
SpringApplication.run(CloudAlibabaConsumer8084Application.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- OpenFegin接口编写
这里我们的接口写法和之前保持一致,但是要注意,我们这里要多增加一个FeignClient的属性:
- fallback: 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口
package com.gek.cloudalibabaconsumer8084.service;
import com.gek.cloudalibabacommons.entity.JsonResult;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Service
@FeignClient(value = "nacos-provider",fallback = FeignServiceImpl.class)
public interface FeignService {
@GetMapping("info/{id}")
public JsonResult<String> msbSql(@PathVariable("id") Long id);
}
FeignServiceImpl
package com.gek.cloudalibabaconsumer8084.service;
import com.gek.cloudalibabacommons.entity.JsonResult;
import org.springframework.stereotype.Component;
@Component
public class FeignServiceImpl implements FeignService {
@Override
public JsonResult<String> msbSql(Long id) {
return new JsonResult<String>(444,"服务降级返回");
}
}
controller
@GetMapping("info/{id}")
public JsonResult<String> msbSql(@PathVariable("id") Long id){
if(id > 3){
throw new RuntimeException("没有该id");
}
return feignService.msbSql(id);
}
测试
此时如果我们访问http://localhost:8084/getInfo/1的地址,是没有问题的,但是如果此时我们人为结束9003/9004服务,这个时候就会触发fallback属性对应的处理类型,完成服务降级。
断开服务后
openfeign 遇到的坑
问题:当请求参数是RequestBody,本来是GET请求的uri,自动被feign转化成为post请求,从而请求不到
远程调用请求不到,请求到的是post下的请求