上传多个文件时,使用多路复用 http2 功能应该会显着提高性能。
Java 有一个本地支持 HTTP/2 协议的 httpclient,所以考虑到我尝试编写代码以供自己理解。
这项任务似乎并不像我最初想的那样容易,或者另一方面,我似乎无法找到能够在上传中使用多路复用的服务器(如果存在)。
这是我写的代码,有人有想法吗?
HttpClient httpClient = HttpClient.newBuilder().version(HttpClient.Version.HTTP_2).build();
String url = "https://your-own-http2-server.com/incoming-files/%s";
Path basePath = Path.of("/path/to/directory/where/is/a/bunch/of/jpgs");
Function<Path, CompletableFuture<HttpResponse<String>>> handleFile = file -> {
String currentUrl = String.format(url, file.getFileName().toString());
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(currentUrl))
.header("Content-Type", "image/jpeg")
.PUT(HttpRequest.BodyPublishers.ofFile(file))
.build();
return httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
};
List<Path> files = Files.list(basePath).collect(toList());
files.parallelStream().map(handleFile).forEach(c -> {
try {
final HttpResponse<String> response = c.get();
System.out.println(response.statusCode());
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException((e));
}
});