【发布时间】:2016-06-28 14:03:57
【问题描述】:
我想在我的 REST 服务中限制下载速率,这是我的代码:
@GET
@Path("/laboDownloadWithLimit")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFile()
{
final File file = new File("SampleVideo_1280x720_50mb.mp4");
final StreamingOutput streamingOutput = new StreamingOutput()
{
@Override
public void write(
final OutputStream outputStream)
throws IOException, WebApplicationException
{
final InputStream inputStream = new FileInputStream(file);
final byte[] buffer = new byte[2048];
int len;
while ((len = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, len);
Thread.sleep(10);
}
}
};
return Response.ok(streamingOutput)
.type(MediaType.APPLICATION_OCTET_STREAM_TYPE)
.header("Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" ).build();
}
但我认为存在更好的方法来解决这个问题,我应该使用什么?我正在使用 Jetty 7.4.5
【问题讨论】:
-
你可以看看 Jetty 如何在他们的 servlet 中实现它:DataRateLimitedServlet。阅读他们的代码,我认为您的实现并不遥远。他们似乎只是使用调度程序进行写入操作,但是您已将其包装在输出中,因此应该没问题