java - Feign 客户端在 Spring boot/Crawler4j 应用程序中总是抛出空指针异常

标签 java spring crawler4j openfeign

我正在 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
}
}

我的Hubclient

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

最佳答案

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

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

关于java - Feign 客户端在 Spring boot/Crawler4j 应用程序中总是抛出空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61175312/

相关文章:

java - Spring事务管理@Transactional行为

spring - 为什么 Autowiring bean 为空?

java - 是否可以通过Crawler4j检索网站内容?

java - 为什么crawler4j随机挂起?

java - c :forEach inside rich:dataTable 的问题

Java 8 Iterable.forEach() 与 foreach 循环

spring - Groovy Spring Bean 类路径

java - 提高crawler4j的性能

Java:内存分析器工具 (MAT) 用法:比较两个 heapdump

java - 升级 spring-boot-starter-parent 后 WebApplicationInitializer 不工作