|
| 1 | +package info.xiaomo.crawler.spider; |
| 2 | + |
| 3 | +import okhttp3.*; |
| 4 | +import org.jsoup.Jsoup; |
| 5 | +import org.jsoup.nodes.Document; |
| 6 | +import org.jsoup.nodes.Element; |
| 7 | +import org.slf4j.Logger; |
| 8 | +import org.slf4j.LoggerFactory; |
| 9 | + |
| 10 | +import java.io.File; |
| 11 | +import java.io.IOException; |
| 12 | +import java.util.*; |
| 13 | +import java.util.concurrent.*; |
| 14 | +import java.util.concurrent.atomic.AtomicInteger; |
| 15 | + |
| 16 | +public class Crawler { |
| 17 | + private static final Logger LOGGER = LoggerFactory.getLogger(Crawler.class); |
| 18 | + private final Set<HttpUrl> fetchedUrls = Collections.synchronizedSet(new LinkedHashSet<HttpUrl>()); |
| 19 | + private final BlockingQueue<HttpUrl> queue = new LinkedBlockingQueue<>(); |
| 20 | + private final ConcurrentMap<String, AtomicInteger> hostnames = new ConcurrentHashMap<>(); |
| 21 | + private OkHttpClient client = null; |
| 22 | + |
| 23 | + private Crawler() { |
| 24 | + init(); |
| 25 | + } |
| 26 | + |
| 27 | + private static Crawler getInstance() { |
| 28 | + return CrawlerHolder.INSTANCE; |
| 29 | + } |
| 30 | + |
| 31 | + public static void main(String[] args) throws ExecutionException, InterruptedException { |
| 32 | + String[] urls = {"https://www.baidu.com/"}; |
| 33 | + List<Future<String>> results = Crawler.getInstance().initUrl(urls).parallelDrainQueue(3); |
| 34 | + for (Future<String> future : results) { |
| 35 | + System.out.println(future.get()); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private Crawler initUrl(String[] urls) { |
| 40 | + for (String url : urls) { |
| 41 | + queue.add(HttpUrl.parse(url)); |
| 42 | + } |
| 43 | + |
| 44 | + return this; |
| 45 | + } |
| 46 | + |
| 47 | + private void init() { |
| 48 | + long cacheByteCount = 1024 * 1024 * 100; |
| 49 | + String dir = "C:\\test"; |
| 50 | + Cache cache = new Cache(new File(dir), cacheByteCount); |
| 51 | + client = new OkHttpClient.Builder().cache(cache).build(); |
| 52 | + } |
| 53 | + |
| 54 | + public List<Future<String>> parallelDrainQueue(int threadCount) { |
| 55 | + ExecutorService executor = Executors.newFixedThreadPool(threadCount); |
| 56 | + List<Future<String>> results = new ArrayList<>(); |
| 57 | + for (int i = 0; i < threadCount; i++) { |
| 58 | + Future<String> future = executor.submit(new Callable<String>() { |
| 59 | + @Override |
| 60 | + public String call() throws Exception { |
| 61 | + try { |
| 62 | + drainQueue(); |
| 63 | + } catch (Exception e) { |
| 64 | + e.printStackTrace(); |
| 65 | + } |
| 66 | + return null; |
| 67 | + } |
| 68 | + }); |
| 69 | + |
| 70 | + results.add(future); |
| 71 | + } |
| 72 | + return results; |
| 73 | + } |
| 74 | + |
| 75 | + private void drainQueue() throws Exception { |
| 76 | + for (HttpUrl url; (url = queue.take()) != null; ) { |
| 77 | + if (!fetchedUrls.add(url)) { |
| 78 | + continue; |
| 79 | + } |
| 80 | + |
| 81 | + try { |
| 82 | + fetch(url); |
| 83 | + } catch (IOException e) { |
| 84 | + e.printStackTrace(); |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + private void fetch(HttpUrl url) throws IOException { |
| 90 | + AtomicInteger hostnameCount = new AtomicInteger(); |
| 91 | + AtomicInteger previous = hostnames.putIfAbsent(url.host(), hostnameCount); |
| 92 | + if (previous != null) { |
| 93 | + hostnameCount = previous; |
| 94 | + } |
| 95 | + |
| 96 | + if (hostnameCount.incrementAndGet() > 100) { |
| 97 | + return; |
| 98 | + } |
| 99 | + |
| 100 | + Request request = new Request.Builder().url(url).build(); |
| 101 | + Response response = client.newCall(request).execute(); |
| 102 | + String responseSource = response.networkResponse() != null |
| 103 | + ? ("(network: " + response.networkResponse().code() + " over " + response.protocol() + ")") : "(cache)"; |
| 104 | + int responseCode = response.code(); |
| 105 | + |
| 106 | + // 打印log |
| 107 | + LOGGER.info("ThreadName:【{}】,ResponseCode:【{}】,URL:【{}】,ResponseSource:【{}】", Thread.currentThread().getName(), |
| 108 | + responseCode, url, responseSource); |
| 109 | + |
| 110 | + String contentType = response.header("Content-Type"); |
| 111 | + if (responseCode != 200 || contentType == null) { |
| 112 | + response.body().close(); |
| 113 | + return; |
| 114 | + } |
| 115 | + |
| 116 | + MediaType mediaType = MediaType.parse(contentType); |
| 117 | + if (mediaType == null || !mediaType.subtype().equalsIgnoreCase("html")) { |
| 118 | + response.body().close(); |
| 119 | + return; |
| 120 | + } |
| 121 | + |
| 122 | + // 获取页面的a[href], 加入LinkedBlockingQueue |
| 123 | + Document document = Jsoup.parse(response.body().string(), url.toString()); |
| 124 | + for (Element element : document.select("a[href]")) { |
| 125 | + String href = element.attr("href"); |
| 126 | + HttpUrl link = response.request().url().resolve(href); |
| 127 | + if (link != null) { |
| 128 | + queue.add(link); |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + private static class CrawlerHolder { |
| 134 | + private static final Crawler INSTANCE = new Crawler(); |
| 135 | + } |
| 136 | +} |
0 commit comments