我正在尝试用 Mono 的值填充 Flux 内的对象。当我尝试这样做时,它只是忽略我的“设置”操作。我认为这是因为 Flux 是并行工作的,而 Mono 不是。我该如何解决这个问题?
Flux.fromIterable(proxyParserService.getProxyList())
.parallel()
.runOn(Schedulers.parallel())
.filter(proxy -> proxy.getCorrupted() == null || !proxy.getCorrupted())
.subscribe(proxy -> {
try {
RestTemplate restTemplate = getProxiedTemplate(proxy.getHost(), proxy.getPort());
restTemplate.exchange(URI, HttpMethod.GET, HttpEntity.EMPTY, String.class);
geoDataService.getData(proxy.getHost()) // Here comes the Mono object, that contains needed value to set into "proxy"
.subscribe(geoData ->
{
log.info("GEODATA: {} ", geoData);
proxy.setCountryCode(geoData.getCountryCode()); // ignored somehow
});
proxy.setCorrupted(false);
addresses.add(proxy);
log.info("IP {}:{} is OK", proxy.getHost(), proxy.getPort());
log.info("Final result: {}", proxy.toString());
} catch (ResourceAccessException e) {
log.info("IP {}:{} is corrupted!", proxy.getHost(), proxy.getPort());
proxy.setCorrupted(true);
addresses.add(proxy);
}
},
throwable -> log.error(String.format("Exception caught while trying to fill map: %s", throwable.getCause())));
}
如您所见,我正在尝试将国家/地区代码设置为代理。
最佳答案
已解决。在“flatMap”运算符中添加了 Mono 对象。 示例:
Flux.fromIterable(proxyParserService.getProxyList())
.parallel()
.runOn(Schedulers.parallel())
.filter(poxy -> !valueExist(addresses.values(), poxy))
.flatMap(geoDataService::getData) // Now it runs in parallel threads
.subscribe(proxy -> {
try {
RestTemplate restTemplate = getProxiedTemplate(proxy.getHost(), proxy.getPort());
restTemplate.exchange(URI, HttpMethod.GET, HttpEntity.EMPTY, String.class);
proxy.setCorrupted(false);
addresses.put(proxy.getCountryCode(), proxy);
log.info("IP {}:{} is OK", proxy.getHost(), proxy.getPort());
log.info("Final result: {}", proxy.toString());
} catch (ResourceAccessException e) {
log.info("IP {}:{} is corrupted!", proxy.getHost(), proxy.getPort());
proxy.setCorrupted(true);
addresses.put(proxy.getCountryCode(), proxy);
}
},
throwable -> log.error(String.format("Exception caught while trying to fill map: %s", throwable.getCause())));
关于java - 如何在同一线程中并行通量内运行单声道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59652807/