大概思路就是:
1.本地两个项目都启动起来。但是两个项目需要设定不同的端口,比如A
项目设定端口为8080
,B
项目设置端口为8098
。
2.假设A项目需要调用B项目的接口,比如B项目的接口如下所示:
@RestController
@RequestMapping("/user")
public class ControllerDemo {
@AutoWired
private UserService userService;
@GetMapping("/select")
public Result select() {
return userService.selectAll();
}
}
3.关键点就是在A项目中如何去调用B项目的接口呢?
答:通过http请求去调用,此时需要使用到相应的http请求工具类
比如使用HttpComponents
工具,该工具的maven依赖为:
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
4.关于这个工具类具体怎样使用可以查询其他人的博客学习。下方简述A项目通过HttpComponents
工具调用B项目的接口(这是通用的操作)。
下方为A
项目中的一个类:此处仅测试get方法,其他方法的调用与下述步骤大同小异
public class HttpClientTest {
public static void main(String[] args) throws Exception{
//此处仅测试get方法
//1、创建客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//2、创建Http的请求方式get,post etc... 需要传入请求地址
//此处输入B项目的ControllerDemo类中select()方法的请求url
HttpGet httpGet = new HttpGet("http://localhost:8098/user/select");
//3、httpClient执行请求,并获取返回结果
CloseableHttpResponse response = httpClient.execute(httpGet);
//4、输出获取到的结果
//从response中取出返回的entity
HttpEntity entity = response.getEntity();
//输出
System.out.println("get返回状态行:"+response.getStatusLine());
System.out.println("get返回结果:"+EntityUtils.toString(entity));
//5、关闭连接 也可以直接调用close()方法
HttpClientUtils.closeQuietly(response);
}
5.经过上述步骤,那么A项目就可以通过B项目提供的接口拿到数据了