线程池下载图片

//本地有差不多1w的图片链接需要下载,单线程也能慢慢下载,但是感觉太浪费时间,对一个开发者来说,时间是不可以浪费的,执行完毕后,差不多160S 1w张图片 960M还是可以接受的。
//本地有一份excel,把数据放入到数据库里面再进行操作。开始想的是直接读取excel里面的链接,再去下载,这样一是速度很慢 二是还得写读取excel的代码 时间不是很够用。
@Service
public class downPngService {

   @Autowired
   FlashdataDao flashdataDao;

   public  void downPng(){
      System.out.println("开始。。。。。");
      long start=System.currentTimeMillis();
      try {
         Map<String,Object> map=new HashMap<>();
         map.put("status","0");//还没下载的链接
         List<FlashdataDO> infoList=flashdataDao.list(map);
         ArrayBlockingQueue<FlashdataDO> queue = new ArrayBlockingQueue<FlashdataDO>(infoList.size());
         queue.addAll(infoList);
         int threadSize=10;//由于是本地cpu有限只开了10个线程
         ExecutorService es = Executors.newFixedThreadPool(threadSize);
         for (int i = 0; i < threadSize; i++) {
            es.execute(new Runnable() {
               @Override
               public void run() {
                  while (!queue.isEmpty()) {
                     try {
                        FlashdataDO flashdataDO=queue.poll(30, TimeUnit.MINUTES);
                        boolean flag=download(flashdataDO.getFileStorePath(),"D:/flash/flashzip/"+flashdataDO.getCasename()+".png");
                        if (flag){
                           System.out.println("下载成功。。。");
                           FlashdataDO updateDo=new FlashdataDO();
                           updateDo.setCasename(flashdataDO.getCasename());
                           updateDo.setStatus("1");
                           int i=flashdataDao.update(updateDo);
                           System.out.println(i>0?"更新成功。。。":"更新失败");
                        }
                     } catch (InterruptedException e) {
                        e.printStackTrace();
                     }
                  }
               }
            });


         }

         //执行子线程
         es.shutdown();
         while (!es.awaitTermination(100, TimeUnit.MINUTES)) {
            System.out.println("状态:"+es.isShutdown()+"==============="+es.isTerminated());
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
      long end=System.currentTimeMillis();
      System.out.println("下载完毕,耗时:  "+(end-start)/1000+"秒");
   }
}

以下是根据文件链接下载文件的util类下的方法:

/**
  * 根据url 下载文件
  * @param urlString
  * @param filename
  * @return
  */
 public boolean download(String urlString, String filename) {
     try {
         if (StringUtils.isBlank(urlString)) {//无效的url
   logger.info("当前下载文件的url为空: {}",urlString);
   return false;
}
logger.info("当前下载地址:{},文件路径:{}",urlString,filename);
         URL url = new URL(urlString);
         HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
         urlCon.setConnectTimeout(6000);
         urlCon.setReadTimeout(8000);
         int code = urlCon.getResponseCode();
         logger.info("下载文件时,Http状态码:{}",code);
         if (code != HttpURLConnection.HTTP_OK) {
   throw new Exception("文件读取失败,地址: "+urlString+",状态码:"+code);
}
         //读文件
         DataInputStream in = new DataInputStream(urlCon.getInputStream());
         DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
         byte[] buffer = new byte[2048];
         int count = 0;
         while ((count = in.read(buffer)) > 0) {
   out.write(buffer, 0, count);
}
         out.close();
         in.close();
         return  true;
     } catch (Exception e) {
         e.printStackTrace();
         logger.info("下载文件时发生异常:{}",e);
     }
     return false;
 }

转载于:https://my.oschina.net/648885471/blog/1842541

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值