public String handle(Function<Consumer<Object>, WebPortalMessageWrapper> processor, Consumer<Object> emailSendHandler) { CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> { long start = System.currentTimeMillis(); xxx x = processor.apply(xxx); if (System.currentTimeMillis() - start >= UPLOAD_TIMEOUT * 1000) { // send email (success or fail) emailSendHandler.accept(x); log.warn("Timeout when call TimeoutHandler.handler sub thread - {}", UPLOAD_TIMEOUT); return TIMEOUT_MESSAGE; } return x; }, taskExecutor).exceptionally(e -> { log.error("Error when call TimeoutHandler.handler sub thread, error={}", e.getMessage(), e); // send failure email emailSendHandler.accept(e.getMessage()); return String.format(STATUS_FAILED_MESSAGE, e.getMessage()); }); try { return future.get(UPLOAD_TIMEOUT, TimeUnit.SECONDS); } catch (TimeoutException e) { log.warn("Timeout when call TimeoutHandler.handler"); return TIMEOUT_MESSAGE; } catch (Exception e) { log.error("Error when call TimeoutHandler.handler, error={}", e.getMessage(), e); // send failure email emailSendHandler.accept(e.getMessage()); return String.format(STATUS_FAILED_MESSAGE, e.getMessage()); } } @PostMapping(value = "xxx", produces = "application/json;charset=UTF-8") @ResponseBody public String saveTemplateData(xxx) { return timeoutHandler.handle( (emailSendHandler) -> this.saveTemplateData(xxx), (result) -> timeoutHandler.sendEmail(result, x)); }
相互学习,共同进步!