SpringBoot集成Feign组件子模块互相调用
项目背景
目前正在开发一个SpringBoot项目,此项目基于ruoyi分离版进行二次开发。
项目需求描述
项目中有两个系统模块需要进行相互直接调用,但此方案会导致依赖循环问题,项目无法启动,并且会耦合。
项目需求分析
解决以上问题,要求两个模块进行解耦,解决依赖循环。
初始方案
当初一开始打算采用 消息中间件(rabbitMq)进行数据交互,发现项目运行过程中,系统服务器并不稳定,经常重启服务器,并且经常消费端无法消费数据。因此放弃此方案。
项目解决方案
采用 Feign组件进行子模块互相调用
一、feign 和 openfeign ?
Feign 是 Springcloud 组件中的一个轻量级 Restful 的 HTTP 服务客户端,Feign 内置了 Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign 的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务。
OpenFeign 是 springcloud 在Feign的基础上支持了 SpringMVC 的注解,如 @RequestMapping 等等。OpenFeign 的 @FeignClient 可以解析 SpringMVC 的 @RequestMapping 注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。
二、为什么要使用 openfeign ?
1、Feign 本身不支持 Spring MVC 的注解,它有一套自己的注解
2、Fegin 是 Netflix 公司产品,停止更新了。
3、使用 OpenFeign 可以简化项目之间接口的调用,我们不需要关心 http 调用的代码
三、SpringBoot集成Feign组件
1、引入基础依赖
<dependencyManagement>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.github.openfeign/feign-httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
<version>11.0</version>
</dependency>
</dependencies>
</dependencyManagement>
2、application.yml 配置文件
server:
port: 8081
feign:
httpclient:
enabled: true
3、被调用 controller
@RestController
@RequestMapping("/demo")
public class FeignProvideController {
@GetMapping("/provide")
public String test((@RequestBody List<xxx> xxxList, @RequestParam Long userId){
return "hello openfegin xxxx";
}
}
4、服务调用方 openfeign 调用服务提供方
模块中需要引入 1 中的依赖
5、项目启动类中增加注解
@SpringBootApplication
@EnableFeignClients
public class OpenfeginDomeApplication {
public static void main(String[] args) {
SpringApplication.run(OpenfeginApplication.class, args);
}
}
6、服务器调用方 编写客户端调用接口
@FeignClient 标注该类是一个feign接口
name:因为这里并未进行服务注册,所以就随便命名一个
url:被调用的服务提供方的接口地址
@FeignClient(name = "demo",url = "http://localhost:8081/demo")
public interface FeginDemo {
//被调用接口的请求类型
@RequestMapping(value = "/provide", method = RequestMethod.POST)
String test(@RequestBody List<xxx> xxxList, @RequestParam("userId") Long userId);
}
7、测试调用服务端提供端接口
@RestController
@RequestMapping("/feginDemo")
public class FeginDemoController {
@Autowired
FeginDemo feginDemo;
@GetMapping("/test")
public String test(){
String test = feginDemo.test();
return test;
}
}