【发布时间】:2020-05-06 20:28:41
【问题描述】:
我尝试在使用 Flux 发布者执行另一个方法后执行一个方法,但从未调用方法 doOnComplete。
代码如下:
public class Client implements Serializable {
private Long id;
private String category;
// other properties, getters and setters
}
interface ClientRepository extends JpaRepository<Client,Long> {
List<Client> findAllByCategory(String category);
@Transactional
void deleteByCategory(String category);
}
class ClientResponse {
private Long status;
private String message;
}
@Component
class ClientService {
@Autowired
ClientRepository clientRepository;
@Autowired
WebClient webClient;
public Mono<ClientResponse> deleteRemoteClient(Long idClient) {
return webClient.post()
.uri("/api/remoteClient/{idClient}",idClient)
.retrieve()
.bodyToMono(ClientResponse.class)
.doOnSuccess(ok -> System.out.println(
"Delete success for client= " + idClient))
.doOnError(err -> System.out.println(
"Delete failed for client= " + idClient + ", err =" + err));
}
/**
* Get All clients by category, then delete them remotely one by one.
* When everything goes well, delete all clients locally in one shot by category
**/
public Flux<ClientResponse> deleteLocalClientByCategory(String category) {
return Flux.fromStream(clientRepository.findAllByCategory(category).stream())
.flatMap(client -> deleteRemoteClient(client.getId()))
.doOnComplete(() -> clientRepository.deleteByCategory(category));
}
}
@Component
class ClientHandler {
@Autowired
ClientService service;
public Mono<ClientResponse> deleteByCatgeory(ServerRequest request) {
return service.deleteLocalClientByCategory(
Long.parseLong(request.queryParam("category").get()))
.publishNext()
.flatMap(response -> ServerResponse.ok().build());
}
}
正如我之前提到的,方法deleteRemoteClient(client.getId()) 但不是clientRepository.deleteByCategory(category)。
【问题讨论】:
-
通量订阅的地点/时间?
-
@DarrenForsythe 你的意思是订阅必须在 deleteRemoteClient(client.getId()) 上完成,返回一个 Mono?
-
我的意思是整个链条,
deleteLocalClientByCategory在哪里调用? -
@DarrenForsythe 我更新了帖子,看看我在哪里打电话给
deleteLocalClientByCategory -
JpaRepository表示您正在使用阻塞数据库,这反过来又意味着您执行的每个数据库调用都是阻塞的,并且您的应用程序可能性能不佳,并且在中等期间存在线程饥饿的巨大风险加载。
标签: spring spring-boot spring-data-jpa spring-webflux