import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
/**
* @Description: 多线程事务
* @Author: zchstart
* @Date: 2023/4/26 9:10
*/
public class TransactionThreadTest {
@Autowired
private JpaTransactionManager txManager;
public String test() {
AtomicReference<String> s1 = new AtomicReference<>();
AtomicReference<String> s = new AtomicReference<>();
try {
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
CountDownLatch countDownLatch = new CountDownLatch(2);
// 事务定义
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// 每次都开启一个新事务
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
CompletableFuture<String> voidCompletableFuture = getVoidCompletableFuture(atomicBoolean, countDownLatch, def, () -> {
s.set(insert1());
return s.get();
});
CompletableFuture<String> voidCompletableFuture2 = getVoidCompletableFuture(atomicBoolean, countDownLatch, def, () -> {
s1.set(insert2());
return s1.get();
});
CompletableFuture.allOf(voidCompletableFuture, voidCompletableFuture2).join();
if (!"替换成功".equals(s1.get()) || !"导入成功".equals(s.get())) {
throw new Exception(s1.get() + "/" + s.get());
}
return "导入成功";
} catch ( Exception e) {
throw new Exception(s.get() + "/" + s1.get());
}
}
private CompletableFuture<String> getVoidCompletableFuture(AtomicBoolean atomicBoolean, CountDownLatch countDownLatch,
DefaultTransactionDefinition def, Supplier<String> supplier) {
return CompletableFuture.supplyAsync(() -> {
TransactionStatus transaction = txManager.getTransaction(def);
String s = "";
try {
s = supplier.get();
} catch (Exception e) {
atomicBoolean.set(true);
} finally {
countDownLatch.countDown();
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
atomicBoolean.set(true);
e.printStackTrace();
}
if (atomicBoolean.get()) {
txManager.rollback(transaction);
} else {
txManager.commit(transaction);
}
return s;
});
}
}
多线程事务
最新推荐文章于 2024-11-04 20:33:37 发布