今天在一次會(huì)議中,有朋友問(wèn)我,如何避免資源被迅雷等工具多線程下載?
確實(shí),一些中小企業(yè)站點(diǎn),尤其是個(gè)人站點(diǎn),由于沒有過(guò)多資金,服務(wù)器承受不了大的壓力,站點(diǎn)提供的資源,一旦被迅雷等多線程工具下載,
對(duì)服務(wù)器的壓力還是蠻客觀的。
那么有什么辦法避免多線程下載呢?其實(shí)最簡(jiǎn)單的辦法,就是服務(wù)端根本就不要提供Content-Length值。試想一下,如果多線程下載工具得不到文件總大小值,如何分配去分配每個(gè)線程需要下載的量呢?不得已,只能通過(guò)單線程下載了。
以http下載為例,我寫了一個(gè)提供下載的servlet,由于不返回Content-Length值(只返回了
ContentType值),這個(gè)serlvet返回的流,只能單線程下載。
public class Download extends HttpServlet {
private static final long serialVersionUID = 8401962046132204450L;
private static final String FILE_PATH = "/home/jones/tmp/sample.zip";
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/octet-stream");
OutputStream out = resp.getOutputStream();
FileInputStream in = new FileInputStream(FILE_PATH);
int readLength = 0;
byte[] cache = new byte[1024];
while ((readLength = in.read(cache)) != -1) {
out.write(cache, 0, readLength);
}
in.close();
out.flush();
out.close();
}
}
同樣的道理,只要配置服務(wù)器不要返回Content-Length值,那么就可以有效避免多線程下載了。