0

我在 Spring Boot 应用程序中运行 Crawler4j 实例,而我的 OpenFeign 客户端始终为空。

public class MyCrawler extends WebCrawler {

@Autowired
    HubClient hubClient;

    @Override
    public void visit(Page page) {
// Lots of crawler code...
        if (page.getParseData() instanceof HtmlParseData) {
            hubClient.send(webPage.toString()); // Throws null pointer exception
}
}

我的 Hub 客户端

@FeignClient("hub-worker")
public interface HubClient {
    @RequestMapping(method = RequestMethod.POST, value = "/pages", consumes = "application/json")
    void send(String webPage);
    //void createPage(WebPage webPage);
}

我的主要应用程序

@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class CrawlerApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(CrawlerApplication.class, args);
    }
}

堆栈跟踪


ext length: 89106
Html length: 1048334
Number of outgoing links: 158
10:14:38.634 [Crawler 164] WARN  e.u.ics.crawler4j.crawler.WebCrawler - Unhandled exception while fetching https://www.cnn.com: null
10:14:38.634 [Crawler 164] INFO  e.u.ics.crawler4j.crawler.WebCrawler - Stacktrace: 
java.lang.NullPointerException: null
    at com.phishspider.crawler.MyCrawler.visit(MyCrawler.java:79)
    at edu.uci.ics.crawler4j.crawler.WebCrawler.processPage(WebCrawler.java:523)
    at edu.uci.ics.crawler4j.crawler.WebCrawler.run(WebCrawler.java:306)
    at java.base/java.lang.Thread.run(Thread.java:834)

第 79 行是 hubClient 调用。当我将 hubVlient 分解到另一个类中时,我在爬虫类中实例化了 hubclient hc = new hubclient() 然后有一些方法 hc.send(page) 那个分解出来的类中的 hubClient 将抛出空指针。

4

1 回答 1

2

为了将 Spring bean(您的客户端)注入您的 crawler4j Web 爬虫对象,您需要通过 Spring 实例化 Web 爬虫对象。

为此,您需要编写WebCrawlerFactory的自定义实现,它提供/创建 Spring 管理的 Web 爬虫对象。为此,您的 Web 爬虫实现需要是一个 Spring Bean,即至少使用@Component.

于 2020-06-01T15:51:38.517 回答