【问题标题】:Feign client always throws a null pointer exception in a Spring boot/Crawler4j appFeign 客户端总是在 Spring boot/Crawler4j 应用程序中抛出空指针异常
【发布时间】:2020-07-25 06:28:19
【问题描述】:

我在 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 将抛出空指针。

【问题讨论】:

  • 您好,请问可以添加stacktrace吗?
  • @MykhailoMoskura - 对不起,是的。刚刚做了。
  • 注入时 hubClient 是否为 null 或 webPage.toString() 返回 null ?
  • hubClient 为空。
  • 你在春季将 MyCrawler 注册为 bean 吗?

标签: java spring crawler4j openfeign


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 2021-08-31
    • 1970-01-01
    • 2017-12-20
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    相关资源
    最近更新 更多