目录
3.3 OpenFeign 与 Loadbalancer 实现负载均衡
微服务是将一个单体应用拆分成一个个较小的服务,那服务拆分后出现的第一个问题就是服务间的相互调用,下面再来看下 Spring Cloud 的组件构成。
今天主要介绍远程调用采用 OpenFeign 的实现方式。
一、OpenFeign 简介
OpenFeign 是一个 Java 语言编写的声明式服务客户端工具,它的前身是 Netflix Feign,Feign 内置了 Ribbon 进行客户端负载均衡。后来随着 Feign 项目进入了维护模式,不在积极更新,Spring Cloud 团队采纳了 Feign 的思想和基本架构,将其发展为 Spring Cloud OpenFeign。
OpenFeign 旨在简化服务间的 HTTP 调用,让用户能够通过定义接口的方式来调用远程服务,而无需关注底层的 HTTP 请求细节和连接管理。
OpenFeign 的主要特点如下:
- 声明式编程:开发者只需要编写接口并在接口上添加注解,如 @FeignClient 和 HTTP 方法相关的注解,无需关心底层 HTTP 的请求细节
- 易于维护:服务消费者只需关注服务提供者的 API 接口定义,降低了服务间的耦合度,方便代码维护和管理
- 支持拦截器:可以自定义 Feign 的请求拦截器,用于实现认证、日志记录、重试等逻辑
- 编程友好:OpenFeign 的 API 设计简洁,符合直觉,能够显著提高开发效率
1.1 项目集成
添加依赖
<!-- openfeign组件,注意需要添加先 SpringCloud 相应依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
启用 OpenFeign,在启动类上添加 @EnableFeignClients 注解来开启 OpenFeign。
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
// 启用 OpenFeign 注解,如何生效的,后边介绍
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
配置服务发现,如果使用了注册中心组件,如Nacos、Consul,Spring Cloud OpenFeign 会自动整合。
定义 Feign 客户端,创建一个接口,通过 @FeignClient 注解指定服务名,并在接口方法上使用 HTTP 方法注解定义请求映射。
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(name = "userservice")
public interface UserServiceClient {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
最后就是注入 Feign 客户端,将定义好的 Feign 客户端注入到需要使用的地方,就像注入普通 Spring Bean 一样。
二、OpenFeign 原理
OpenFeign 通过解析注解标签生成一个动态代理类,这个代理类会将接口调用转化为一个远程服务调用的 Request,并发送给目标服务。
首先看下 Spring 是如何找到你定义的 OpenFeign 客户端的。