/**
* @Author: feifei
* @Date: 2023/01/28/2:36 下午
* @Description:
*/
@Slf4j
public class CXFTest {
@Autowired
private static TransactionTemplate transactionTemplate;
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 1000L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1000),
ThreadFactoryBuilder.create().setNamePrefix("bingfa-shiwu-test-").build(),
new RejectedExecutionHandler() {
@SneakyThrows
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.error("线程积压过多", r);
throw new Exception("线程积压过多");
}
});
public static void main(String[] args) {
//编程式事务来进行事务的控制
List<Integer> result = transactionTemplate.execute(transactionStatus -> {
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < 5; i++) {
temp.add(i);
}
List<CompletableFuture<Integer>> futureList = temp.stream().map(a -> CompletableFuture.supplyAsync(() -> {
if (a == 4) {
throw new RuntimeException("错误啦,达咩");
}
Integer tempNum = a + 1;
log.info(tempNum.toString());
return tempNum;
}, executor)).collect(Collectors.toList());
List<Integer> res = new ArrayList<>();
try {
res = futureList.stream().map(future -> {
try {
return future.get();
} catch (Exception e) {
log.info("并发修改异常");
throw new RuntimeException("修改异常");
}
}).collect(Collectors.toList());
} catch (Exception e) {
log.info("有异常捏,整体回滚");
//demo里临时手动关闭线程池
executor.shutdownNow();
throw new RuntimeException("有异常任务执行结束");
}
log.info("事务成功结束了");
return res;
});
//打印最终结果
log.info(JSONObject.toJSONString(result));
}
}
多线程事务demo
最新推荐文章于 2024-05-01 15:53:47 发布