简介
Feign是声明性(注解)web服务客户端。它使得编写web服务客户端更加容易。要使用Feign,可以创建一个接口并对其使用注解。它具有可插入注解支持,包括Feign注解和JAX-RS注解。Feign还支持可插拔编码器和解码器。Spring Cloud添加了对Spring MVC注解的支持,并支持使用HttpMessageConverters,Spring Web中默认使用的注解。Spring Cloud集成了Ribbon和Eureka以及Spring Cloud LoadBalancer,以在使用Feign是提供负载均衡的Http客户端。
Feign是一个远程调用的组件;Feign集成了ribbon,robbon又集成了eureka。
基础使用
provider模块
首先我们新建一个order-service模块作为provider。对应的配置内容如下。
然后该provider模块的依赖如下:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.12.RELEASE</version>
<relativePath />
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-cloud.version>Hoxton.SR12</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
接下来我们简单的写一个接口用于测试:
@GetMapping("/order")
public String orderTest() {
return "订单服务已提供";
}
consumer模块
新建一个user-service模块作为consumer模块。其配置文件内容与provider模块除了端口与应用名外都一致。
因为我们需要使用OpenFeign,所以我们要添加相应的依赖,如下:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
从简介中我们知道openfeign
是一个声明式客户端,因此我们需要在启动类加上注解@EnableFeignClients
开启 Feign 的客户端功能,帮助我们进行调用。
然后我们新建一个接口作为OpenFeign的客户端,注意:我们要在该接口上添加@FeignClient(value = "自己的服务名")
。同时,我们接口中的方法,就可以直接使用需要调用的服务中的方法签名(也就是请求方式、url、返回类型、方法名、参数等一定要保持一致)。
最后,我们在user-service模块中的controller中注入openFeign的客户端,直接在请求接口中调用即可远程调用order-service中的接口。
远程过程调用成功。