介绍
微服务架构下,业务的拆分导致我们无法调用其他模块的方法,使用openFeign可以帮助我们解决这一问题
一.建立项目
建立项目之后,我们需要创建两个业务模块
二.引入依赖
使用openfeign必须要和服务注册中心的组件一起使用,这里我们使用nacos来作为我们的服务注册中心
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
三.启动类加注解
在调用方的启动类的类名上面加如下注解
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
四.编写被调用方的代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("test")
public void test(){
System.out.println(1);
}
}
五.编写调用方的代码
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
@Service//此处service必加
@FeignClient("B")//此处B是B模块的名称
public interface TestService {
@RequestMapping("test")
void test();
}
import com.example.a.client.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("test")
public void test(){
testService.test();
}
}
然后测试即可