CompletableFuture事务处理

简介: CompletableFuture事务处理

男人的盟誓是女人的陷阱——莎士比亚

使用CompletableFuture进行异步任务编排时,可能会有事务的支持需求,我们这里可以使用之前我写的手动回滚、提交事务进行处理

代码案例如下,所用框架stream-query:

首先是不加事务的

package io.github.vampireachao.stream.plugin.mybatisplus;
import io.github.vampireachao.stream.plugin.mybatisplus.pojo.po.UserInfo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
/**
 * AsyncTest
 *
 * @author VampireAchao
 * @since 2022/12/6
 */
@SpringBootTest
class AsyncTest {
    @Test
    @Transactional
    void test(@Autowired ThreadPoolTaskExecutor executor) {
        UserInfo userInfo = new UserInfo();
        userInfo.setName("ruben");
        Database.save(userInfo);
        CompletableFuture.runAsync(() -> {
                Assertions.assertNotNull(userInfo.getId(), "id is null");
                Assertions.assertNotNull(Database.getById(userInfo.getId(), userInfo.getClass()), "user is null");
        }, executor).join();
    }
}


此处会抛出assertNotNull,提示user is null

因为外部事务未提交,但内部默认事务没有设置为读未提交

修改后事务支持的代码:

package io.github.vampireachao.stream.plugin.mybatisplus;
import io.github.vampireachao.stream.plugin.mybatisplus.pojo.po.UserInfo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
/**
 * AsyncTest
 *
 * @author VampireAchao
 * @since 2022/12/6
 */
@SpringBootTest
class AsyncTest {
    @Test
    @Transactional
    void test(
            @Autowired TransactionTemplate transactionTemplate,
            @Autowired ThreadPoolTaskExecutor executor) {
        UserInfo userInfo = new UserInfo();
        userInfo.setName("ruben");
        Database.save(userInfo);
        CompletableFuture.runAsync(() -> {
            PlatformTransactionManager transactionManager = Objects.requireNonNull(transactionTemplate.getTransactionManager());
            DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
            transactionDefinition.setIsolationLevel(TransactionDefinition.ISOLATION_READ_UNCOMMITTED);
            TransactionStatus transactionStatus = transactionManager.getTransaction(transactionDefinition);
            try {
                Assertions.assertNotNull(userInfo.getId(), "id is null");
                Assertions.assertNotNull(Database.getById(userInfo.getId(), userInfo.getClass()), "user is null");
                transactionManager.commit(transactionStatus);
            } catch (Throwable e) {
                transactionManager.rollback(transactionStatus);
                throw e;
            }
        }, executor).join();
    }
}

成功执行

相关文章
|
Java Spring 容器
解决Spring的UnsatisfiedDependencyException异常的方法
在Spring开发中,UnsatisfiedDependencyException异常意味着依赖注入失败,影响应用稳定性。该异常由Spring容器在无法满足bean依赖时抛出,常见原因包括bean定义错误、循环依赖、多个候选bean等。解决方法包括:检查bean定义和注入的正确性、解决循环依赖、确认依赖包的兼容性、使用@Qualifier或@Primary注解。通过日志、调试工具和异常对比来定位问题。持续学习Spring框架有助于更好地解决此类异常。
11330 11
|
XML Java 关系型数据库
Spring Boot 异常处理回滚事务详解(自动回滚、手动回滚、部分回滚)
Spring Boot 异常处理回滚事务详解(自动回滚、手动回滚、部分回滚)
4735 0
|
7月前
|
SQL 人工智能 自然语言处理
CEO 想要“可以追问”的报表:从静态 Dashboard 到交互式 AI 决策报告
把报表从“静态展示结果”升级为“可交互的决策分析入口”。
|
人工智能 自然语言处理 计算机视觉
CVPR 2024 | 赋能大语言模型以精准理解视频时序瞬间 | LLM | 时序预测
VTimeLLM提出新型时间感知架构,赋能大语言模型精准理解视频时序瞬间。通过时间对齐表征与时序预训练,实现事件定位、时序推理与细粒度视频理解,支持自然语言交互式探索视频内容。
404 0
CVPR 2024 | 赋能大语言模型以精准理解视频时序瞬间 | LLM | 时序预测
完美解决 fatal: unable to access ‘https://github.com/Homebrew/brew/‘
完美解决 fatal: unable to access ‘https://github.com/Homebrew/brew/‘
3341 0
|
SQL 测试技术 API
如何编写API接口的自动化测试脚本
本文详细介绍了编写API自动化测试脚本的方法和最佳实践,涵盖确定测试需求、选择测试框架、编写测试脚本(如使用Postman和Python Requests库)、参数化和数据驱动测试、断言和验证、集成CI/CD、生成测试报告及维护更新等内容,旨在帮助开发者构建高效可靠的API测试体系。
|
网络安全 数据安全/隐私保护
什么是 CSRF 攻击
CSRF(跨站请求伪造)攻击是指攻击者诱导用户点击恶意链接或提交表单,利用用户已登录的身份在目标网站上执行非授权操作,如转账、修改密码等。这种攻击通常通过嵌入恶意代码或链接实现。
|
Java 数据库连接 数据库
|
Java Spring 容器
Spring boot 自定义ThreadPoolTaskExecutor 线程池并进行异步操作
Spring boot 自定义ThreadPoolTaskExecutor 线程池并进行异步操作
1720 3
|
Java 数据库 数据安全/隐私保护
在Spring框架中如何确保事务一致性?
【2月更文挑战第5天】
1257 0
在Spring框架中如何确保事务一致性?