- 模拟2个接口,一个调用方,一个被调用方
- 业务场景:没有部署文件系统,并且微服务部署了多台应用,只能通过每次上传文件进行一个同步,所以以此在各应用对应的存储文件目录(一般在
yml
里设置)都同步生成该文件
From
ip
和port
是指该微服务部署的其他应用地址,可存在yml
里,进行遍历,然后逐个应用同步该文件- 传输文件可用
new InputStreamResource
,接收方用MultipartFile
类接收即可
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
@PostMapping("/testFromFile")
public void testFromFile (){
String ip = "192.168.3.217";
String port="8077";
String url = String.format("http://%s:%s/titan-api/test/%s", ip, port, "testToFile");
try {
File file = new File("E:\\aka_test\\11.xlsx");
HttpRequest req = HttpRequest.post(url).form("file",new InputStreamResource(new FileInputStream(file), file.getName()));
try (HttpResponse resp = req.execute()) {
System.out.println(resp);
}
} catch (Exception e) {
log.error("报错",e);
}
}
TO
@PostMapping("/testToFile")
public Result testToFile (MultipartFile file){
File localFile = new File("F:\\aka_test\\" + "/" + file.getOriginalFilename());
try {
file.transferTo(localFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
return Result.returnSuccess("保存文件成功:"+localFile.getName());
}