Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地实现微服务之间的调用。
一、Feign的优点是什么?
1.feign采用的是基于接口的注解;
2.feign整合了ribbon,具有负载均衡的能力;
3.整合了Hystrix,具有熔断的能力。
二、项目编码
服务消费者content-center(内容中心微服务)向服务提供者user-center(用户中心微服务)发送请求,获取用户的微信昵称,我们通过Feign来实现该需求。
请求路径:http://localhost:8082/user/1
响应的json数据:
{"id":1,"wxId":"aaa","wxNickname":"大坏蛋","roles":"admin","avatarUrl":"xxx","createTime":"2022-01-14T02:10:02.000+0000","updateTime":"2022-01-14T02:10:02.000+0000","bonus":100}
2.1、在pom.xml中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
2.2、在BootApplication中添加@EnableFeignClients注解
package personal.qin.contentcenter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class ContentCenterApplication {
public static void main(String[] args) {
SpringApplication.run(ContentCenterApplication.class, args);
}
}
2.3、新建FeignClient实现Feign远程请求
package personal.qin.contentcenter.feignclient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import personal.qin.contentcenter.domain.dto.UserDTO;
//Feign访问微服务的名称
@FeignClient(name = "user-center")
public interface UserCenterFeignClient {
/**
* Feign会自动构建URL为http://user-center/user/{id}
* @param id
* @return
*/
@GetMapping("/user/{id}")
UserDTO findById(@PathVariable Integer id);
}
2.4、新建测试Controller
package personal.qin.contentcenter.controller;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import personal.qin.contentcenter.domain.dto.UserDTO;
import personal.qin.contentcenter.feignclient.UserCenterFeignClient;
@RestController
@RequestMapping("/content")
public class ContentController {
@Autowired
private UserCenterFeignClient userCenterFeignClient;
@GetMapping("/{id}")
public UserDTO findById(@PathVariable Integer id){
return userCenterFeignClient.findById(id);
}
}
2.5、测试效果
访问UserController可以通过feign顺利调用到user-center中的方法
http://localhost:8012/content/1
三、Feign自定义日志级别
级别 | 打印内容 |
NONE(默认值) | 不记录任何日志 |
BASIC | 仅记录请求方法、URL、请求状态码以及执行时间 |
HEADERS | BASIC级别的基础之上,记录请求和响应的header |
FULL | 记录请求和响应的header、body和元数据 |
3.1、在application.yml添加属性
在application.yml中结合log添加属性
#设置日志输出级别
logging:
level:
com.itmuch.contentcenter.feignclient.UserCenterFeignClient: debug
feign:
client:
config:
#想要调用的微服务的名称
user-center:
loggerLevel: full
3.2、测试效果
四、Feign支持的配置项
配置项 | 作用 |
Logger.Level | 指定日志级别 |
Retryer | 指定重试策略 |
ErrorDecoder | 指定错误解码器 |
Request.Options | 超时时间 |
Collection<RequestInterceptor> | 拦截器 |
SetterFactory | 用于设置Hystrix的配置属性,当Feign整合Hystrix时才会使用 |
application.yml配置参考
五、多参数请求
多参数可以使用@SpringQueryMap注解实现
package com.itmuch.contentcenter.feignclient;
import com.itmuch.contentcenter.domain.dto.user.UserDTO;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "user-center")
public interface TestUserCenterFeignClient {
@GetMapping("/q")
UserDTO query(@SpringQueryMap UserDTO userDTO);
}
注意,在开发中可能会出现多个Feign接口访问同一个微服务的情况,解决方法:
在application.yml中添加属性配置
spring:
#解决Feign多个Client接口指向同一个微服务出现异常的问题
main:
allow-bean-definition-overriding: true
六、脱离Nacos单独使用Feign
6.1、新建FeignClient,请求百度
package com.itmuch.contentcenter.feignclient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient(name = "baidu", url = "http://www.baidu.com")
public interface TestBaiduFeignClient {
@GetMapping("")
public String index();
}
6.2、在测试Controller中调用FeignClient方法
@Autowired
private TestBaiduFeignClient testBaiduFeignClient;
@GetMapping("baidu")
public String baiduIndex(){
return testBaiduFeignClient.index();
}
6.3、测试效果
七、RestTemplate和Feign对比
角度 | RestTemplate | Feign |
可读性、可维护性 | 一般 | 极佳 |
开发体验 | 欠佳 | 极佳 |
性能 | 很好 | 中等(RestTemplate的50%左右,但是可以使用连接池将性能提升15%所有) |
灵活性 | 极佳 | 中等(内置功能可以满足绝大多数需求) |
八、Feign的性能优化
8.1、使用连接池提升15%性能
pom.xml中添加依赖
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
application.yml中添加属性配置连接池
feign:
httpclient:
#让feign使用Apache httpclient做请求,而不是默认的urlconnection
enabled: true
#feign的最大连接数
max-connections: 200
#feign单个路径的最大连接数
max-connections-per-route: 50
8.2、将日志的级别设置为basic,不要使用full
feign:
client:
config:
#想要调用的微服务的名称或全局配置
default:
loggerLevel: basic
九、Feign的常见问题总结
参考:https://www.imooc.com/article/289005
十、pom.xml及源代码下载
(代码)SpringCloud第07讲:Http模板化客户端Feign
<?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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>personal.qin</groupId>
<artifactId>content-center</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>content-center</name>
<description>content-center</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.5.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<!--整合spring cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!--整合spring cloud alibaba-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>0.9.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<configurationFile>
${basedir}/src/main/resources/generator/generatorConfig.xml
</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
</project>