事务支持
灵感
TransactionDefinition txDef = new DefaultTransactionDefinition();
TransactionStatus txStatus = transactionManager.getTransaction(txDef);
try {
//do your stuff here like
doWhateverAsync().then(transactionManager.commit(txStatus);)
} catch (Exception e) {
transactionManager.rollback(txStatus);
throw e;
}
用法
PlatformTransactionManager txManager = null;
TransactionDefinition txDef = new DefaultTransactionDefinition();
TransactionStatus txStatus = txManager.getTransaction(txDef);
CompletableFuture.supplyAsync(() -> 1)
.thenAccept(data -> txManager.commit(txStatus))
.exceptionally(e -> {
txManager.rollback(txStatus);
return null;
});
如何优雅的处理超时
public static <T> CompletableFuture<T> failAfter(Duration duration) {
final CompletableFuture<T> promise = new CompletableFuture();
scheduler.schedule(()-> {
final TimeoutException ex = new TimeoutException("Timeout after " + duration;
return promise.completeExceptionally(ex);
}, duration.toMillis(), MILLISECONDS);
return promise;
}
private static final SchedulerExecutorService scheduler =
Executors.newScheduledThreadPool(1,
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("failAfter-%d")
.build());
public static <T> CompletableFuture<T> withIn(CompletableFuture<T> future, Duration duration) {
final CompletableFuture<T> timeout = failAfter(duration);
return future.applyToEither(timeout, Function.identity());
}
测试代码
public void testTimeoutCf() {
final CompletableFuture<Response> resCf = withIn(
asyncCode(), Duration.ofSeconds(1));
resCf.thenAccept(this::send)
.exceptionally(cause -> {
log.error(cause);
return null;
})
}