【发布时间】:2019-05-16 05:52:59
【问题描述】:
我正在尝试从 Amazon S3 下载文件。
我希望用户通过 GET api 访问我的应用。
应用反过来从 S3 获取内容并将其作为可下载文件返回给用户。
注意:
我不想将文件本地存储在我的服务器中,我希望它直接从亚马逊 s3 流式传输到最终用户
我尝试使用大约 300 MB 的文件,如果我像下面这样在本地运行它 内存占用低,即本地存在相同文件时
@GET
@Path("/pdfdownload")
@Produces("application/pdf")
public Response getFile() {
File file = new File('/pathToFile'); // in local
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition", "attachment; filename=file.pdf");
return response.build();
}
但是当我从 Amazon s3 下载相同的内容时,我的 tomcat 服务器的内存迅速增加到大约 600 MB,我想我正在流式传输内容,但是当我查看使用的内存时我怀疑它 我错过了什么吗?
@GET
@Path("/pdfdownload")
@Produces("application/pdf")
public Response getFile2() {
final S3Object s3Object = getAmazonS3Object();// AWS S3
final S3ObjectInputStream s3is = s3Object.getObjectContent();
final StreamingOutput stream = new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
byte[] read_buf = new byte[1024];
int read_len = 0;
while ((read_len = s3is.read(read_buf)) > 0) {
os.write(read_buf, 0, read_len);
}
os.close();
s3is.close();
}
};
ResponseBuilder response = Response.ok(stream);
response.header("Content-Disposition", "attachment; filename=file.pdf");
return response.build();
}
private S3Object getAmazonS3Object() {
AWSCredentials credentials = new BasicAWSCredentials("accesskey",
"secretkey");
try {
AmazonS3 s3 = new AmazonS3Client(credentials);
S3Object s3object = s3.getObject(new GetObjectRequest("bucketName", "filename_WithExtension"));
return s3object;
} catch (AmazonServiceException e) {
System.err.println(e.getErrorMessage());
System.exit(1);
}
System.out.println("Done!");
return null;
}
波姆:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk</artifactId>
<version>1.11.542</version>
</dependency>
类似于这个S3 download pdf - REST API
我不想使用 PreSignedURl:https://docs.aws.amazon.com/AmazonS3/latest/dev/ShareObjectPreSignedURLJavaSDK.html
请看这篇关于流媒体的文章:https://memorynotfound.com/low-level-streaming-with-jax-rs-streamingoutput/
能否请一些人帮忙解释一下为什么内存会激增?
【问题讨论】:
标签: amazon-web-services amazon-s3 download jax-rs aws-sdk