驗證資料庫中URL的有效性

壹頁書發表於2017-07-13
曲庫中一些歌曲的URL雖然存在,但是根據URL已經下載不到音樂了.
Nginx顯示404錯誤.

驗證資料庫中歌曲的URL是否能夠下載

首先,先把資料庫中的歌曲URL匯出到檔案.如下格式(歌曲ID,音樂地址型別,路徑)
1000;AccompanimentURL ;/00/00/00001000_accompaniment.m4a

然後使用程式掃描URL

        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.7</version>

        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.7</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.0.Final</version>
        </dependency>

程式比較渣..以後得學習一下物件封裝


  1. import java.io.BufferedReader;  
  2. import java.io.FileInputStream;  
  3. import java.io.FileWriter;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.util.HashMap;  
  7. import java.util.HashSet;  
  8. import java.util.Map;  
  9. import java.util.Set;  
  10. import java.util.concurrent.BlockingQueue;  
  11. import java.util.concurrent.LinkedBlockingQueue;  
  12. import java.util.concurrent.Semaphore;  
  13. import java.util.concurrent.atomic.AtomicInteger;  
  14.   
  15. import io.netty.bootstrap.Bootstrap;  
  16. import io.netty.buffer.ByteBuf;  
  17. import io.netty.buffer.Unpooled;  
  18. import io.netty.channel.Channel;  
  19. import io.netty.channel.ChannelHandlerContext;  
  20. import io.netty.channel.ChannelInboundHandlerAdapter;  
  21. import io.netty.channel.ChannelInitializer;  
  22. import io.netty.channel.EventLoopGroup;  
  23. import io.netty.channel.nio.NioEventLoopGroup;  
  24. import io.netty.channel.socket.nio.NioSocketChannel;  
  25. import io.netty.handler.codec.LineBasedFrameDecoder;  
  26. import io.netty.handler.codec.string.StringDecoder;  
  27.   
  28. public class URLChecker {  
  29.     public static void main(String[] args) {  
  30.         String sourceFile="F:\\normal.txt";  
  31.         String resultFile="F:\\result.csv";  
  32.         new URLInput(sourceFile, resultFile);  
  33.           
  34.     }  
  35.   
  36. }  
  37.   
  38. class URLConnection extends Thread{  
  39.     @Override  
  40.     public void run() {  
  41.         while(true){  
  42.             int start=count.get();  
  43.             try {  
  44.                 Thread.sleep(1000);  
  45.             } catch (InterruptedException e) {  
  46.                 // TODO Auto-generated catch block  
  47.                 e.printStackTrace();  
  48.             }  
  49.             int end=count.get();  
  50.             System.out.println("每秒檢查:"+(end-start));  
  51.         }  
  52.     }  
  53.   
  54.     Semaphore sem = new Semaphore(20);  
  55.     String[] hosts = new String[5];  
  56.     AtomicInteger count = new AtomicInteger();  
  57.   
  58.     EventLoopGroup group = new NioEventLoopGroup(3);  
  59.     URLInput input;  
  60.     URLOutput output;  
  61.     URLConnection(URLInput input,URLOutput writer) {  
  62.         hosts[0] = "172.16.1.151";  
  63.         hosts[1] = "172.16.1.152";  
  64.         hosts[2] = "172.16.1.153";  
  65.         hosts[3] = "172.16.1.154";  
  66.         hosts[4] = "172.16.1.155";  
  67.           
  68.         this.output=writer;  
  69.         this.input=input;  
  70.   
  71.     }  
  72.   
  73.     public void connection(final Map<String, String> map)  
  74.             throws InterruptedException {  
  75.         sem.acquire();  
  76.         int index = count.getAndIncrement();  
  77.         Bootstrap boot = new Bootstrap();  
  78.   
  79.         boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer() {  
  80.             @Override  
  81.             protected void initChannel(Channel ch) throws Exception {  
  82.                 ch.pipeline().addLast(new LineBasedFrameDecoder(409600));  
  83.                 ch.pipeline().addLast(new StringDecoder());  
  84.                 ch.pipeline().addLast(new HttpClientHandler(map, sem,input,output));  
  85.             }  
  86.         });  
  87.         boot.connect(hosts[index % hosts.length], 80);  
  88.   
  89.     }  
  90.       
  91.       
  92. }  
  93.   
  94. class HttpClientHandler extends ChannelInboundHandlerAdapter {  
  95.     StringBuffer sb = new StringBuffer(512);  
  96.     Map<String, String> map = new HashMap<String, String>();  
  97.     Semaphore sem;  
  98.     URLInput input;  
  99.     URLOutput writer;  
  100.   
  101.   
  102.     public HttpClientHandler(Map<String, String> map, Semaphore sem, URLInput input, URLOutput writer) {  
  103.         this.map = map;  
  104.         this.sem = sem;  
  105.   
  106.         this.writer=writer;  
  107.         this.input=input;  
  108.     }  
  109.   
  110.     @Override  
  111.     public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {  
  112.         sem.release();  
  113.           
  114.         ctx.close();  
  115.         writer.addSuccURL(map);  
  116.     }  
  117.   
  118.     @Override  
  119.     public void channelActive(ChannelHandlerContext ctx) throws Exception {  
  120.   
  121.         StringBuilder sb = new StringBuilder();  
  122.         sb.append("HEAD " + map.get("url") + " HTTP/1.0\r\n");  
  123.         sb.append("HOST:" + 80 + "\r\n");  
  124.         sb.append("Accept:*/*\r\n");  
  125.         sb.append("\r\n");  
  126.         ByteBuf bb = Unpooled.copiedBuffer(sb.toString().getBytes("utf8"));  
  127.         ctx.writeAndFlush(bb);  
  128.   
  129.     }  
  130.   
  131.     @Override  
  132.     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {  
  133.         String content = (String) msg;  
  134.         if (content.contains(":")) {  
  135.             String[] s = content.split(":");  
  136.             map.put(s[0].trim(), s[1].trim());  
  137.         } else if (content.startsWith("HTTP/1.1")) {  
  138.             map.put("httpcode", content.replaceAll("HTTP/1.1 """));  
  139.         }  
  140.   
  141.     }  
  142.   
  143.     @Override  
  144.     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {  
  145.         cause.printStackTrace();  
  146.         ctx.close();  
  147.         input.addFailUrl(map);  
  148.         sem.release();  
  149.     }  
  150.   
  151. }  
  152.   
  153. class URLInput {  
  154.     URLConnection urlcon;  
  155.     URLInput(String sourceFile, String resultFile) {  
  156.         URLOutput output=new URLOutput(resultFile);  
  157.         urlcon=new URLConnection(this, output);  
  158.         output.start();  
  159.         urlcon.start();  
  160.         try {  
  161.             init(resultFile);  
  162.             read(sourceFile);  
  163.         } catch (IOException e) {  
  164.             e.printStackTrace();  
  165.         } catch (InterruptedException e) {  
  166.             e.printStackTrace();  
  167.         }  
  168.     }  
  169.   
  170.     /**  
  171.      * 初始化已經處理的檔案,用於中斷處理後的恢復執行  
  172.      *   
  173.      * @param resultFile  
  174.      * @throws IOException  
  175.      */  
  176.     private void init(String resultFile) throws IOException {  
  177.         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(resultFile)));  
  178.         String row = null;  
  179.         while ((row = br.readLine()) != null) {  
  180.             String[] data = row.split(",");  
  181.             set.add(data[0]);  
  182.   
  183.         }  
  184.         br.close();  
  185.     }  
  186.   
  187.     public void addFailUrl(Map<String, String> map) {  
  188.         failq.add(map);  
  189.     }  
  190.   
  191.     final BlockingQueue<Map<String, String>> failq = new LinkedBlockingQueue<Map<String, String>>();  
  192.     Set<String> set = new HashSet<String>();  
  193.   
  194.     private void read(String sourceFile) throws IOException, InterruptedException {  
  195.         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(sourceFile)));  
  196.         String row = null;  
  197.         while ((row = br.readLine()) != null) {  
  198.             while (failq.size() != 0) {  
  199.   
  200.                 final Map<String, String> m = failq.take();  
  201.                 urlcon.connection(m);  
  202.             }  
  203.   
  204.             String[] data = row.split(";");  
  205.             final Map<String, String> map = new HashMap<String, String>();  
  206.             map.put("songid", data[0]);  
  207.             map.put("type", data[1]);  
  208.             map.put("url", data[2]);  
  209.             if (!set.contains(data[0])) {  
  210.                 urlcon.connection(map);  
  211.             }  
  212.         }  
  213.         br.close();  
  214.         System.out.println("Finish!!");  
  215.     }  
  216. }  
  217.   
  218. class URLOutput extends Thread {  
  219.     BlockingQueue<Map<String, String>> succq = new LinkedBlockingQueue<Map<String, String>>();  
  220.     String resultFile;  
  221.   
  222.     public void addSuccURL(Map<String, String> map) {  
  223.         succq.add(map);  
  224.     }  
  225.   
  226.     public URLOutput(String resultFile) {  
  227.         this.resultFile = resultFile;  
  228.     }  
  229.   
  230.     @Override  
  231.     public void run() {  
  232.         Map<String, String> map = null;  
  233.         FileWriter fw = null;  
  234.         try {  
  235.             fw = new FileWriter(resultFile, true);  
  236.             while ((map = succq.take()) != null) {  
  237.                 fw.write(map.get("songid") + "," + map.get("type") + "," + map.get("url") + "," + map.get("httpcode")  
  238.                         + "," + map.get("Content-Length") + "\n");  
  239.             }  
  240.         } catch (InterruptedException e) {  
  241.             e.printStackTrace();  
  242.         } catch (IOException e) {  
  243.             e.printStackTrace();  
  244.         } finally {  
  245.             try {  
  246.                 fw.close();  
  247.             } catch (IOException e) {  
  248.                 e.printStackTrace();  
  249.             }  
  250.         }  
  251.     }  
  252.   


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2142047/,如需轉載,請註明出處,否則將追究法律責任。

相關文章