由于我仍然没有找到适合我的主题的完全令人满意的 react 性解决方案:click ,主要假设是:
How to run a Web Flux method cyclically in a reactive way?
我找到了一个解决方法,使用@Scheduled
注释使其成为现实。实现如下:
@Component
@AllArgsConstructor
public class Covid19APIHandler {
private Covid19APIService apiService;
private CountryCasesHistoryRepository repository;
private CountryCasesWrapperRepository countryCasesWrapperRepository;
private ServerRequest serverRequest;
public Mono<Void> getCountryCasesAndSave(ServerRequest serverRequest) {
return apiService
.findCasesByCountry()
.flatMap(
wrapper ->
countryCasesWrapperRepository
.save(
CountryCasesWrapper.builder()
.countries_stat(wrapper.getCountries_stat())
.statistic_taken_at(wrapper.getStatistic_taken_at())
.build())
.then(Mono.empty()));
}
@Scheduled(fixedDelay = 10000)
public void casesByCountryScheduled() {
getCountryCasesAndSave(serverRequest);
}
}
问题是在代码执行时我收到错误:
Description:
Parameter 3 of constructor in com.covid.application.Covid19APIHandler required a bean of type 'org.springframework.web.reactive.function.server.ServerRequest' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.web.reactive.function.server.ServerRequest' in your configuration.
我尝试了 final
关键字和 @RequiredArgsConstructor
,生成所有参数。通过 IntelliJ 构造函数,但我的 ServerRequest 字段仍未初始化。问题来了,如何创建我的 ServerRequest
自定义 bean 并使其正确初始化。我将不胜感激有关如何使其成为现实的建议。
最佳答案
正如评论中所指出的,为什么你甚至需要一个ServerRequest
,你甚至没有使用它。删除它并清理代码。
@Component
public class Covid19APIHandler {
private Covid19APIService apiService;
private CountryCasesWrapperRepository countryCasesWrapperRepository;
@Autowire
public Covid19APIHandler(Covid19APIService apiService, CountryCasesHistoryRepository repository) {
this.apiService = apiService;
this.repository = repository;
}
@Scheduled(fixedDelay = 10000)
public void casesByCountryScheduled() {
apiService.findCasesByCountry()
.flatMap(response ->
return countryCasesWrapperRepository.save(
CountryCasesWrapper.builder()
.countries_stat(response.getCountries_stat())
.statistic_taken_at(response.getStatistic_taken_at())
.build()))
.subscribe();
}
}
在此代码中,您的计划任务将按照 fixedDelay
运行,如果您希望它每小时运行一次,我建议在计划程序中设置一个 cron
作业。
由于订阅
,代码将运行。您会看到,当您调用 subscribe
时,您基本上是在运行代码。 消费者
应该始终是订阅者
。您的应用程序是另一个应用程序的消费者
。因此,您的服务通过调用 subscribe 来发起请求,这将开始发出请求并将其存储在数据库中的流程。
我建议阅读以下内容
带有@Scheduled的cron作业
cron 语法
https://en.wikipedia.org/wiki/Cron
在您订阅之前不会发生任何事情(reactor 文档)
https://projectreactor.io/docs/core/release/reference/#reactive.subscribe
关于java - 获取NoSuchBeanDefinitionException : No qualifying bean of type ServerRequest in Spring WebFlux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61327789/