• Spring多线程事务处理


    一、背景

    本文主要介绍了spring多线程事务的解决方案,心急的小伙伴可以跳过上面的理论介绍分析部分直接看最终解决方案。

    在我们日常的业务活动中,经常会出现大规模的修改插入操作,比如在3.0的活动赛事创建,涉及到十几张表的插入(一张表可能插入一行或者多行数据),由于单线程模型的关系,所有的sql都是串行,即后面的sql必须都要等到前面的sql执行完成才能继续。但是在很多场景下,sql的执行顺序并不影响业务的结果,面对这样的场景,我们很自然的想到了使用异步的方式去处理,可是我们同时又希望整个创建操作是事务性的,即要全部成功,要么全部失败,但是单纯的使用异步线程并不能达到我们理想的效果。

    这个时候,我们需要一种多线程下保证事务的解决方案。

    代码片段,大量的同步保存操作

    1. public void much(){
    2. //业务操作1
    3. doBusiness1();
    4. //业务操作2
    5. doBusiness2();
    6. //业务操作3
    7. doBusiness3();
    8. //业务操作4
    9. doBusiness4();
    10. }
    11. private void doBusiness1() {
    12. //执行sql1
    13. //执行sql2
    14. //执行sql3
    15. //执行sql4
    16. }

    每个业务操作可以是相关联的,也有可能是完全无关的,但如果做成异步的话我们就无法保证事务,怎么去解决这个问题呢?

    二、理论先行

    1.事务介绍

    我们先确定spring事务的本质是什么,spring本身不支持事务,spring实现事务只是对我们原有的业务逻辑做了一层包装,他替我们决定了什么时候开启事务,什么情况下应该向数据库提交,什么时候回滚,及实现我们设置的一些事务参数,包括回滚的条件,传播类型等。

    我们所熟知的spring事务有两种主流的解决方式,一种是声明式事务,一种是编程式事务。

    先来讲我们最常用的声明式事务。

    1.1声明式事务

    声明式事务就是我们最常用的@Transactional注解,通常我们只需要在我们想交由spring控制的事务方法上加上注解即可,这个注解有一些重要的参数,由于不是本文重点,就不在此展开。这是一个经典的spring的aop实现,为了弄清楚在加上@Transactional注解后spring到底为我们做了什么,我们可以从两方面入手,一是spring如何给我们生成相应的代理对象,二是这个代理对象为我们做了什么。

    事务的开始是由@EnableTransactionManagement 注解产生,这个注解在运行时会导入TransactionManagementConfigurationSelector这个类,这个类本质上是一个ImportSelector,他根据adviceMode将特定的配置类导入进去,分别为AutoProxyRegistrar 后置处理器和ProxyTransactionManagementConfiguration Advisor。

    AutoProxyRegistrar 实现了ImportBeanDefinitionRegistrar 重写了registerBeanDefinitions 方法

    1. public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    2. boolean candidateFound = false;
    3. Set<String> annTypes = importingClassMetadata.getAnnotationTypes();
    4. for (String annType : annTypes) {
    5. // ...
    6. AopConfigUtils.registerAutoProxyCreatorIfNecessary(registry);
    7. }
    8. // ...
    9. }
    10. @Nullable
    11. public static BeanDefinition registerAutoProxyCreatorIfNecessary(
    12. BeanDefinitionRegistry registry, @Nullable Object source) {
    13. return registerOrEscalateApcAsRequired(InfrastructureAdvisorAutoProxyCreator.class, registry, source);
    14. }

    该方法最终注入了InfrastructureAdvisorAutoProxyCreator。InfrastructureAdvisorAutoProxyCreator这个类就是一个bean的后置处理器,最终的作用就是处理需要的代理对象。

    1. public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
    2. if (bean != null) {
    3. Object cacheKey = getCacheKey(bean.getClass(), beanName);
    4. if (this.earlyProxyReferences.remove(cacheKey) != bean) {
    5. return wrapIfNecessary(bean, beanName, cacheKey);
    6. }
    7. }
    8. return bean;
    9. }
    10. protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    11. // ...
    12. // 拿当前bean去匹配容器中的 Advisors,如果找到符合的就生成代理对象
    13. // Create proxy if we have advice.
    14. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
    15. if (specificInterceptors != DO_NOT_PROXY) {
    16. this.advisedBeans.put(cacheKey, Boolean.TRUE);
    17. Object proxy = createProxy(
    18. bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
    19. this.proxyTypes.put(cacheKey, proxy.getClass());
    20. return proxy;
    21. }
    22. this.advisedBeans.put(cacheKey, Boolean.FALSE);
    23. return bean;
    24. }

    ProxyTransactionManagementConfiguration的作用就是来生成具体的Advisor,他注册了三个bean,

    1. 该类主要完成以下几个任务:

    2. 创建TransactionAttributeSource对象:用于解析@Transactional注解并生成事务属性。

    3. 创建TransactionInterceptor对象:用于创建事务通知,将事务属性应用到目标方法,这其实就是一个事务模板,如下所示

    1. protected Object invokeWithinTransaction(Method method, @Nullable Class<?> targetClass,
    2. final InvocationCallback invocation) throws Throwable {
    3. //TransactionAttributeSource内部保存着当前类某个方法对应的TransactionAttribute---事务属性源
    4. //可以看做是一个存放TransactionAttribute与method方法映射的池子
    5. TransactionAttributeSource tas = getTransactionAttributeSource();
    6. //获取当前事务方法对应的TransactionAttribute
    7. final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
    8. //定位TransactionManager
    9. final TransactionManager tm = determineTransactionManager(txAttr);
    10. .....
    11. //类型转换为局部事务管理器
    12. PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
    13. final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
    14. if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
    15. //TransactionManager根据TransactionAttribute创建事务后返回
    16. //TransactionInfo封装了当前事务的信息--包括TransactionStatus
    17. TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
    18. Object retVal;
    19. try {
    20. //继续执行过滤器链---过滤链最终会调用目标方法
    21. //因此可以理解为这里是调用目标方法
    22. retVal = invocation.proceedWithInvocation();
    23. }
    24. catch (Throwable ex) {
    25. //目标方法抛出异常则进行判断是否需要回滚
    26. completeTransactionAfterThrowing(txInfo, ex);
    27. throw ex;
    28. }
    29. finally {
    30. //清除当前事务信息
    31. cleanupTransactionInfo(txInfo);
    32. }
    33. ...
    34. //正常返回,那么就正常提交事务呗(当然还是需要判断TransactionStatus状态先)
    35. commitTransactionAfterReturning(txInfo);
    36. return retVal;
    37. }
    38. ...

    1. 创建TransactionAdvisor对象:将事务通知和切点(Pointcut)组合成Advisor。

    2. 创建TransactionAttributeSourceAdvisor对象:将事务属性和切点组合成Advisor

    1. @Configuration(proxyBeanMethods = false)
    2. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    3. public class ProxyTransactionManagementConfiguration extends AbstractTransactionManagementConfiguration {
    4. @Bean(name = TransactionManagementConfigUtils.TRANSACTION_ADVISOR_BEAN_NAME)
    5. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    6. public BeanFactoryTransactionAttributeSourceAdvisor transactionAdvisor(
    7. TransactionAttributeSource transactionAttributeSource, TransactionInterceptor transactionInterceptor) {
    8. BeanFactoryTransactionAttributeSourceAdvisor advisor = new BeanFactoryTransactionAttributeSourceAdvisor();
    9. advisor.setTransactionAttributeSource(transactionAttributeSource);
    10. advisor.setAdvice(transactionInterceptor);
    11. if (this.enableTx != null) {
    12. advisor.setOrder(this.enableTx.getNumber("order"));
    13. }
    14. return advisor;
    15. }
    16. @Bean
    17. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    18. public TransactionAttributeSource transactionAttributeSource() {
    19. // TransactionAttributeSource 是一个接口,具体注入的是 Annotationxxxx
    20. return new AnnotationTransactionAttributeSource();
    21. }
    22. @Bean
    23. @Role(BeanDefinition.ROLE_INFRASTRUCTURE)
    24. public TransactionInterceptor transactionInterceptor(TransactionAttributeSource transactionAttributeSource) {
    25. TransactionInterceptor interceptor = new TransactionInterceptor();
    26. interceptor.setTransactionAttributeSource(transactionAttributeSource);
    27. if (this.txManager != null) {
    28. interceptor.setTransactionManager(this.txManager);
    29. }
    30. return interceptor;
    31. }
    32. }

    1. @Nullable
    2. private TransactionAttributeSource transactionAttributeSource;
    3. private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
    4. @Override
    5. @Nullable
    6. protected TransactionAttributeSource getTransactionAttributeSource() {
    7. return transactionAttributeSource;
    8. }
    9. };
    10. /**
    11. * Set the transaction attribute source which is used to find transaction
    12. * attributes. This should usually be identical to the source reference
    13. * set on the transaction interceptor itself.
    14. * @see TransactionInterceptor#setTransactionAttributeSource
    15. */
    16. public void setTransactionAttributeSource(TransactionAttributeSource transactionAttributeSource) {
    17. this.transactionAttributeSource = transactionAttributeSource;
    18. }
    19. /**
    20. * Set the {@link ClassFilter} to use for this pointcut.
    21. * Default is {@link ClassFilter#TRUE}.
    22. */
    23. public void setClassFilter(ClassFilter classFilter) {
    24. this.pointcut.setClassFilter(classFilter);
    25. }
    26. @Override
    27. public Pointcut getPointcut() {
    28. return this.pointcut;
    29. }

    可以见到里面已经包含了pointcut,这就能将我们需要被增加的事务方法找出。

    ProxyTransactionManagementConfiguration负责将需要包装的bean和方法找出并包装成advisor,InfrastructureAdvisorAutoProxyCreator根据advisor生成相应的代理对象。

    小结:InfrastructureAdvisorAutoProxyCreator遍历容器中的bean,尝试去自动代理,匹配的工作就交由advisor中的point,如果匹配成功就为其创建代理对象,这个代理对象中放入了TransactionInterceptor拦截器

    ,等到相关方法调用时,调用的是代理对象的方法,然后通过责任链模式通过TransactionInterceptor处理,以此来进行事务的操作。

    声明式事务的介绍先到这里,接下来我们来介绍下编程式事务。

    1.2编程式事务

    编程式事务的核心就是将spring为我们做好的那些步骤拆出来,交由开发者去控制事务何时开启、提交、回滚,他的运行本质和声明式事务并没有两样。

    模板如下

    1. public class TransactionMain {
    2. public static void main(String[] args) throws ClassNotFoundException, SQLException {
    3. test();
    4. }
    5. private static void test() {
    6. DataSource dataSource = getDS();
    7. JdbcTransactionManager jtm = new JdbcTransactionManager(dataSource);
    8. //JdbcTransactionManager根据TransactionDefinition信息来进行一些连接属性的设置
    9. //包括隔离级别和传播行为等
    10. DefaultTransactionDefinition transactionDef = new DefaultTransactionDefinition();
    11. //开启一个新事务---此时autocommit已经被设置为了false,并且当前没有事务,这里创建的是一个新事务
    12. TransactionStatus ts = jtm.getTransaction(transactionDef);
    13. //进行业务逻辑操作
    14. try {
    15. update(dataSource);
    16. jtm.commit(ts);
    17. }catch (Exception e){
    18. jtm.rollback(ts);
    19. System.out.println("发生异常,我已回滚");
    20. }
    21. }
    22. private static void update(DataSource dataSource) throws Exception {
    23. JdbcTemplate jt = new JdbcTemplate();
    24. jt.setDataSource(dataSource);
    25. jt.update("UPDATE Department SET Dname=\"大忽悠\" WHERE id=6");
    26. throw new Exception("我是来捣乱的");
    27. }
    28. }

    三、方案探索

    1.直接使用多线程

    我们在开启代码中事务,并在业务逻辑中直接使用多线程,是否能保证事务?

    1. @Transactional
    2. public void testDirect() {
    3. new Thread(()->{
    4. Per per = new Per();
    5. per.setName("t1");
    6. perService.save(per);
    7. }).start();
    8. new Thread(()->{
    9. Per per1 = new Per();
    10. per1.setName("t2");
    11. perService.save(per1);
    12. throw new RuntimeException("Exception test");
    13. }).start();
    14. }

    显然,这种方式并不能保证事务,哪怕加上了事务注解,因为子线程抛出的异常并不能在主线程中捕获,也不能被其他线程感知到。

    2.事务模板中使用多线程

    1. package com.user.util;
    2. import lombok.RequiredArgsConstructor;
    3. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    4. import org.springframework.stereotype.Component;
    5. import org.springframework.transaction.TransactionStatus;
    6. import org.springframework.transaction.support.DefaultTransactionDefinition;
    7. import javax.sql.DataSource;
    8. import java.util.ArrayList;
    9. import java.util.List;
    10. import java.util.concurrent.CompletableFuture;
    11. import java.util.concurrent.ExecutionException;
    12. import java.util.concurrent.Executor;
    13. import java.util.concurrent.atomic.AtomicBoolean;
    14. @Component
    15. @RequiredArgsConstructor
    16. public class MultiplyThreadTransactionManager {
    17. /**
    18. * 如果是多数据源的情况下,需要指定具体是哪一个数据源
    19. */
    20. private final DataSource dataSource;
    21. public void runAsyncButWaitUntilAllDown(List<Runnable> tasks, Executor executor) {
    22. if(executor==null){
    23. throw new IllegalArgumentException("线程池不能为空");
    24. }
    25. DataSourceTransactionManager transactionManager = getTransactionManager();
    26. //是否发生了异常
    27. AtomicBoolean ex=new AtomicBoolean();
    28. List<CompletableFuture> taskFutureList=new ArrayList<>(tasks.size());
    29. List<TransactionStatus> transactionStatusList=new ArrayList<>(tasks.size());
    30. tasks.forEach(task->{
    31. taskFutureList.add(CompletableFuture.runAsync(
    32. () -> {
    33. try{
    34. //1.开启新事务
    35. transactionStatusList.add(openNewTransaction(transactionManager));
    36. //2.异步任务执行
    37. task.run();
    38. }catch (Throwable throwable){
    39. //打印异常
    40. throwable.printStackTrace();
    41. //其中某个异步任务执行出现了异常,进行标记
    42. ex.set(Boolean.TRUE);
    43. //其他任务还没执行的不需要执行了
    44. taskFutureList.forEach(completableFuture -> completableFuture.cancel(true));
    45. }
    46. }
    47. , executor)
    48. );
    49. });
    50. try {
    51. //阻塞直到所有任务全部执行结束---如果有任务被取消,这里会抛出异常滴,需要捕获
    52. CompletableFuture.allOf(taskFutureList.toArray(new CompletableFuture[]{})).get();
    53. } catch (InterruptedException | ExecutionException e) {
    54. e.printStackTrace();
    55. }
    56. //发生了异常则进行回滚操作,否则提交
    57. if(ex.get()){
    58. System.out.println("发生异常,全部事务回滚");
    59. transactionStatusList.forEach(transactionManager::rollback);
    60. }else {
    61. System.out.println("全部事务正常提交");
    62. transactionStatusList.forEach(transactionManager::commit);
    63. }
    64. }
    65. private TransactionStatus openNewTransaction(DataSourceTransactionManager transactionManager) {
    66. //JdbcTransactionManager根据TransactionDefinition信息来进行一些连接属性的设置
    67. //包括隔离级别和传播行为等
    68. DefaultTransactionDefinition transactionDef = new DefaultTransactionDefinition();
    69. //开启一个新事务---此时autocommit已经被设置为了false,并且当前没有事务,这里创建的是一个新事务
    70. return transactionManager.getTransaction(transactionDef);
    71. }
    72. private DataSourceTransactionManager getTransactionManager() {
    73. return new DataSourceTransactionManager(dataSource);
    74. }
    75. }

    测试

    1. public void test(){
    2. List<Runnable> tasks=new ArrayList<>();
    3. tasks.add(()->{
    4. Per per = new Per();
    5. per.setName("t1");
    6. perService.save(per);
    7. });
    8. tasks.add(()->{
    9. Per per = new Per();
    10. per.setName("t2");
    11. perService.save(per);
    12. });
    13. multiplyThreadTransactionManager.runAsyncButWaitUntilAllDown(tasks, Executors.newCachedThreadPool());
    14. }

    执行结果

    1. java.lang.IllegalStateException: No value for key [HikariDataSource (HikariPool-1)] bound to thread
    2. at org.springframework.transaction.support.TransactionSynchronizationManager.unbindResource(TransactionSynchronizationManager.java:198) ~[spring-tx-5.3.10.jar:5.3.10]
    3. at org.springframework.jdbc.datasource.DataSourceTransactionManager.doCleanupAfterCompletion(DataSourceTransactionManager.java:371) ~[spring-jdbc-5.3.10.jar:5.3.10]
    4. at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:992) ~[spring-tx-5.3.10.jar:5.3.10]
    5. at org.springframework.transaction.suppoAbstractPlatformTransactionrt.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager

    结果报了这个错,这个错误信息室找不到绑定在线程上的key为HikariDataSource的资源,因为事务资源都是绑定在线程上的,当事务提交或者回滚时,他需要寻找绑定在当前线程上的资源,如果找不到,就会报错。

    原理剖析:

    首先我们找到绑定线程资源的关键方法org.springframework.transaction.support.TransactionSynchronizationManager#bindResource

    1. /**
    2. * Bind the given resource for the given key to the current thread.
    3. * @param key the key to bind the value to (usually the resource factory)
    4. * @param value the value to bind (usually the active resource object)
    5. * @throws IllegalStateException if there is already a value bound to the thread
    6. * @see ResourceTransactionManager#getResourceFactory()
    7. */
    8. public static void bindResource(Object key, Object value) throws IllegalStateException {
    9. Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
    10. Assert.notNull(value, "Value must not be null");
    11. Map<Object, Object> map = resources.get();
    12. // set ThreadLocal Map if none found
    13. if (map == null) {
    14. map = new HashMap<>();
    15. resources.set(map);
    16. }
    17. Object oldValue = map.put(actualKey, value);
    18. // Transparently suppress a ResourceHolder that was marked as void...
    19. if (oldValue instanceof ResourceHolder && ((ResourceHolder) oldValue).isVoid()) {
    20. oldValue = null;
    21. }
    22. if (oldValue != null) {
    23. throw new IllegalStateException(
    24. "Already value [" + oldValue + "] for key [" + actualKey + "] bound to thread");
    25. }
    26. }

    根据debug会发现,spring在开启事务时会自动为我们调用这个方法,绑定key为HikariDataSource,value为ConnectionHolder到threadlocal中。第二次sql执行时会绑定key为DefaultSqlSessionFactory,value为DefaultSqlSessionFactory。

    既然讲到了事务资源的绑定时机,下面就顺便讲一下这两种资源在何时释放。我们再回顾一下事务的执行流程及机制。spring处理事务的原理就是基于aop,每个需要实现事务的方法都要通过TransactionInterceptor这个拦截器,通过这个拦截器去实现事务增强。

    1. @Override
    2. @Nullable
    3. public Object invoke(MethodInvocation invocation) throws Throwable {
    4. // Work out the target class: may be {@code null}.
    5. // The TransactionAttributeSource should be passed the target class
    6. // as well as the method, which may be from an interface.
    7. Class targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
    8. // Adapt to TransactionAspectSupport's invokeWithinTransaction...
    9. //重点,这里注册了一个回调,最后会调回下面
    10. //父类实现
    11. return invokeWithinTransaction(invocation.getMethod(), targetClass, new CoroutinesInvocationCallback() {
    12. @Override
    13. @Nullable
    14. public Object proceedWithInvocation() throws Throwable {
    15. //原始方法
    16. return invocation.proceed();
    17. }
    18. @Override
    19. public Object getTarget() {
    20. return invocation.getThis();
    21. }
    22. @Override
    23. public Object[] getArguments() {
    24. return invocation.getArguments();
    25. }
    26. });
    27. }

    他最终会交给他的父类模板类org.springframework.transaction.interceptor.TransactionAspectSupport#invokeWithinTransaction实现,在来看一下这个类为我们处理了什么,直接看重点

    1. /**
    2. * General delegate for around-advice-based subclasses, delegating to several other template
    3. * methods on this class. Able to handle {@link CallbackPreferringPlatformTransactionManager}
    4. * as well as regular {@link PlatformTransactionManager} implementations and
    5. * {@link ReactiveTransactionManager} implementations for reactive return types.
    6. * @param method the Method being invoked
    7. * @param targetClass the target class that we're invoking the method on
    8. * @param invocation the callback to use for proceeding with the target invocation
    9. * @return the return value of the method, if any
    10. * @throws Throwable propagated from the target invocation
    11. */
    12. @Nullable
    13. protected Object invokeWithinTransaction(Method method, @Nullable Class targetClass,
    14. final InvocationCallback invocation) throws Throwable {
    15. // If the transaction attribute is null, the method is non-transactional.
    16. //说人话就是获取事务资源,装配事务管理器
    17. TransactionAttributeSource tas = getTransactionAttributeSource();
    18. final TransactionAttribute txAttr = (tas != null ? tas.getTransactionAttribute(method, targetClass) : null);
    19. final TransactionManager tm = determineTransactionManager(txAttr);
    20. PlatformTransactionManager ptm = asPlatformTransactionManager(tm);
    21. final String joinpointIdentification = methodIdentification(method, targetClass, txAttr);
    22. if (txAttr == null || !(ptm instanceof CallbackPreferringPlatformTransactionManager)) {
    23. // Standard transaction demarcation with getTransaction and commit/rollback calls.
    24. //事务相关信息,包括传播级别,什么异常下回滚等
    25. TransactionInfo txInfo = createTransactionIfNecessary(ptm, txAttr, joinpointIdentification);
    26. Object retVal;
    27. try {
    28. // This is an around advice: Invoke the next interceptor in the chain.
    29. // This will normally result in a target object being invoked.
    30. //就是他的子类注册的回调,真正的业务逻辑
    31. retVal = invocation.proceedWithInvocation();
    32. }
    33. catch (Throwable ex) {
    34. // target invocation exception
    35. //回滚
    36. completeTransactionAfterThrowing(txInfo, ex);
    37. throw ex;
    38. }
    39. finally {
    40. //清理事务信息
    41. cleanupTransactionInfo(txInfo);
    42. }
    43. if (retVal != null && vavrPresent && VavrDelegate.isVavrTry(retVal)) {
    44. // Set rollback-only in case of Vavr failure matching our rollback rules...
    45. TransactionStatus status = txInfo.getTransactionStatus();
    46. if (status != null && txAttr != null) {
    47. retVal = VavrDelegate.evaluateTryFailure(retVal, txAttr, status);
    48. }
    49. }
    50. //提交
    51. commitTransactionAfterReturning(txInfo);
    52. return retVal;
    53. }
    54. ...
    55. }

    继续往下,观察commitTransactionAfterReturning(txInfo)的实现,发现这一步是由事务管理器完成的。

    1. protected void commitTransactionAfterReturning(@Nullable TransactionInfo txInfo) {
    2. if (txInfo != null && txInfo.getTransactionStatus() != null) {
    3. if (logger.isTraceEnabled()) {
    4. logger.trace("Completing transaction for [" + txInfo.getJoinpointIdentification() + "]");
    5. }
    6. txInfo.getTransactionManager().commit(txInfo.getTransactionStatus());
    7. }
    8. }

    进而可以推断,rollback操作也是同样的道理,有兴趣的小伙伴可以自己debug一下,继续走下去,观察事务管理器为我们做了什么。

    1. @Override
    2. public final void commit(TransactionStatus status) throws TransactionException {
    3. if (status.isCompleted()) {
    4. throw new IllegalTransactionStateException(
    5. "Transaction is already completed - do not call commit or rollback more than once per transaction");
    6. }
    7. DefaultTransactionStatus defStatus = (DefaultTransactionStatus) status;
    8. if (defStatus.isLocalRollbackOnly()) {
    9. if (defStatus.isDebug()) {
    10. logger.debug("Transactional code has requested rollback");
    11. }
    12. processRollback(defStatus, false);
    13. return;
    14. }
    15. if (!shouldCommitOnGlobalRollbackOnly() && defStatus.isGlobalRollbackOnly()) {
    16. if (defStatus.isDebug()) {
    17. logger.debug("Global transaction is marked as rollback-only but transactional code requested commit");
    18. }
    19. processRollback(defStatus, true);
    20. return;
    21. }
    22. processCommit(defStatus);
    23. }

    到此,spring的整个事务流程就已经非常清晰了,我们想要实现多事务管理的方法也找到了,难就是去控制事务的资源。只要我们拿到了相应的事务资源,然后在创建自己的事务管理器控制事务何时提交或者回滚,这样我们就可以实现一个多线程同时提交回滚,类似于二阶段提交的操作,来达到多线程事务的统一。

    3.多线程事务管理器

    不多说,直接上代码看最终版本

    1. package com.controller;
    2. import lombok.Builder;
    3. import lombok.RequiredArgsConstructor;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.slf4j.MDC;
    6. import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    7. import org.springframework.stereotype.Component;
    8. import org.springframework.transaction.TransactionStatus;
    9. import org.springframework.transaction.support.DefaultTransactionDefinition;
    10. import org.springframework.transaction.support.TransactionSynchronization;
    11. import org.springframework.transaction.support.TransactionSynchronizationManager;
    12. import org.springframework.util.CollectionUtils;
    13. import javax.sql.DataSource;
    14. import java.util.*;
    15. import java.util.concurrent.*;
    16. import java.util.concurrent.atomic.AtomicBoolean;
    17. import java.util.concurrent.atomic.AtomicInteger;
    18. /**
    19. * 多线程事务管理
    20. */
    21. @Component
    22. @Slf4j
    23. @RequiredArgsConstructor
    24. public class MultiplyThreadTransactionManager {
    25. /**
    26. * 如果是多数据源的情况下,需要指定具体是哪一个数据源
    27. */
    28. private final DataSource dataSource;
    29. private final static ThreadLocal<Boolean> immediatelyCommitFlag = new ThreadLocal<>();
    30. private final static ThreadLocal<List<TransactionStatus>> transactionStatusListThreadLocal = new ThreadLocal<>();
    31. private final static ThreadLocal<List<TransactionResource>> transactionResourcesthreadLocal = new ThreadLocal<>();
    32. private final static ThreadLocal<Map<Object, Object>> mainNativeResourceThreadLocal = new ThreadLocal<>();
    33. /**
    34. * 多线程下事务执行
    35. *
    36. * @param tasks 任务列表
    37. * @param immediatelyCommit 是否需要立即提交
    38. */
    39. public List<CompletableFuture> runAsyncButWaitUntilAllDown(List<Runnable> tasks, Boolean immediatelyCommit) {
    40. Executor executor = Executors.newCachedThreadPool();
    41. DataSourceTransactionManager transactionManager = getTransactionManager();
    42. //是否发生了异常
    43. AtomicBoolean ex = new AtomicBoolean();
    44. List<CompletableFuture> taskFutureList = new CopyOnWriteArrayList<>();
    45. List<TransactionStatus> transactionStatusList = new CopyOnWriteArrayList<>();
    46. List<TransactionResource> transactionResources = new CopyOnWriteArrayList<>();
    47. //记录原生主事务资源
    48. //这一步可能在原生sql执行前,也可能在原生sql执行后,所以这个资源可能不够充分,需要在下面继续处理
    49. //如果返回的是原资源集合的引用,下面一步可以不用
    50. Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap();
    51. if (!CollectionUtils.isEmpty(resourceMap)) {
    52. mainNativeResourceThreadLocal.set(new HashMap<>(resourceMap));
    53. }
    54. Map<String, String> copyOfContextMap = MDC.getCopyOfContextMap();
    55. Executor finalExecutor = executor;
    56. AtomicInteger atomicInteger = new AtomicInteger(0);
    57. tasks.forEach(task -> {
    58. taskFutureList.add(CompletableFuture.runAsync(
    59. () -> {
    60. log.info("任务开始");
    61. try {
    62. //1.开启新事务
    63. TransactionStatus transactionStatus = openNewTransaction(transactionManager);
    64. log.info("开启新事务 successfully");
    65. transactionStatusList.add(transactionStatus);
    66. atomicInteger.incrementAndGet();
    67. System.out.println("atomicInteger.get()"+atomicInteger.incrementAndGet());
    68. System.out.println(transactionStatus);
    69. //2.异步任务执行
    70. task.run();
    71. log.info("异步任务执行 successfully");
    72. //3.继续事务资源复制,因为在sql执行是会产生新的资源对象
    73. transactionResources.add(TransactionResource.copyTransactionResource());
    74. } catch (Throwable throwable) {
    75. log.info("任务执行异常"+throwable.getMessage());
    76. log.error("任务执行异常",throwable);
    77. //其中某个异步任务执行出现了异常,进行标记
    78. ex.set(Boolean.TRUE);
    79. //其他任务还没执行的不需要执行了
    80. taskFutureList.forEach(completableFuture -> completableFuture.cancel(true));
    81. }
    82. }
    83. , finalExecutor)
    84. );
    85. });
    86. try {
    87. //阻塞直到所有任务全部执行结束---如果有任务被取消,这里会抛出异常滴,需要捕获
    88. CompletableFuture.allOf(taskFutureList.toArray(new CompletableFuture[]{})).get();
    89. } catch (InterruptedException | ExecutionException e) {
    90. log.info("任务被取消");
    91. log.error("任务被取消",e);
    92. }
    93. //发生了异常则进行回滚操作,否则提交
    94. if (ex.get()) {
    95. log.info("发生异常,全部事务回滚");
    96. for (int i = 0; i < transactionStatusList.size(); i++) {
    97. transactionResources.get(i).autoWiredTransactionResource();
    98. Map<Object, Object> rollBackResourceMap = TransactionSynchronizationManager.getResourceMap();
    99. log.info("回滚前事务资源size{},本身{}",rollBackResourceMap.size(),rollBackResourceMap);
    100. transactionManager.rollback(transactionStatusList.get(i));
    101. transactionResources.get(i).removeTransactionResource();
    102. }
    103. } else {
    104. if (immediatelyCommit) {
    105. log.info("全部事务正常提交");
    106. for (int i = 0; i < transactionStatusList.size(); i++) {
    107. //transactionResources.get(i).autoWiredTransactionResource();
    108. Map<Object, Object> commitResourceMap = TransactionSynchronizationManager.getResourceMap();
    109. log.info("提交前事务资源size{},本身{}",commitResourceMap.size(),commitResourceMap);
    110. transactionManager.commit(transactionStatusList.get(i));
    111. transactionResources.get(i).removeTransactionResource();
    112. }
    113. } else {
    114. //缓存全部待提交数据
    115. immediatelyCommitFlag.set(immediatelyCommit);
    116. transactionResourcesthreadLocal.set(transactionResources);
    117. transactionStatusListThreadLocal.set(transactionStatusList);
    118. }
    119. }
    120. //交还给主事务
    121. if (immediatelyCommit) {
    122. mainTransactionResourceBack(!ex.get());
    123. }
    124. return taskFutureList;
    125. }
    126. public void multiplyThreadTransactionCommit() {
    127. try {
    128. Boolean immediatelyCommit = immediatelyCommitFlag.get();
    129. if (immediatelyCommit) {
    130. throw new IllegalStateException("immediatelyCommit cant call multiplyThreadTransactionCommit");
    131. }
    132. //提交
    133. //获取存储的事务资源和状态
    134. List<TransactionResource> transactionResources = transactionResourcesthreadLocal.get();
    135. List<TransactionStatus> transactionStatusList = transactionStatusListThreadLocal.get();
    136. if (CollectionUtils.isEmpty(transactionResources) || CollectionUtils.isEmpty(transactionStatusList)) {
    137. throw new IllegalStateException("transactionResources or transactionStatusList is empty");
    138. }
    139. //重新提交
    140. DataSourceTransactionManager transactionManager = getTransactionManager();
    141. log.info("全部事务正常提交");
    142. for (int i = 0; i < transactionStatusList.size(); i++) {
    143. transactionResources.get(i).autoWiredTransactionResource();
    144. Map<Object, Object> commitResourceMap = TransactionSynchronizationManager.getResourceMap();
    145. log.info("提交前事务资源size{},本身{}",commitResourceMap.size(),commitResourceMap);
    146. transactionManager.commit(transactionStatusList.get(i));
    147. transactionResources.get(i).removeTransactionResource();
    148. }
    149. } catch (Exception e) {
    150. mainTransactionResourceBack(false);
    151. log.error("multiplyThreadTransactionCommit fail", e);
    152. } finally {
    153. transactionResourcesthreadLocal.remove();
    154. transactionStatusListThreadLocal.remove();
    155. immediatelyCommitFlag.remove();
    156. }
    157. //交还给主事务
    158. mainTransactionResourceBack(true);
    159. }
    160. //主线程事务资源返还
    161. public void mainTransactionResourceBack(Boolean subTransactionSuccess) {
    162. if (CollectionUtils.isEmpty(mainNativeResourceThreadLocal.get())) {
    163. //清除数据
    164. mainNativeResourceThreadLocal.remove();
    165. return;
    166. }
    167. Map<Object, Object> nativeResource = new HashMap<>(mainNativeResourceThreadLocal.get());
    168. Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap();
    169. log.info("当前线程资事务源size{}--------------------------------{}",resourceMap.size(), resourceMap);
    170. log.info("原生线程事务资源size{}--------------------------------{}",nativeResource.size(), nativeResource);
    171. //已经被绑定的资源不能重复绑定
    172. if (!CollectionUtils.isEmpty(resourceMap)) {
    173. for (Object o : resourceMap.keySet()) {
    174. if (nativeResource.containsKey(o)) {
    175. nativeResource.remove(o);
    176. }
    177. }
    178. }
    179. nativeResource.forEach((k,v)->{
    180. if (!(k instanceof DataSource)){
    181. log.info("nativeResource 没有 DataSource");
    182. }
    183. });
    184. //交还不能绑定factory
    185. nativeResource.forEach((k,v)->{
    186. if (k instanceof DataSource){
    187. TransactionSynchronizationManager.bindResource(k,v);
    188. }
    189. });
    190. Map<Object, Object> finResource = TransactionSynchronizationManager.getResourceMap();
    191. log.info("主线程最终事务源size{}--------------------------------{}",finResource.size(), finResource);
    192. //防止未激活事务
    193. if (!TransactionSynchronizationManager.isSynchronizationActive()) {
    194. TransactionSynchronizationManager.initSynchronization();
    195. }
    196. //清除数据
    197. mainNativeResourceThreadLocal.remove();
    198. if (!subTransactionSuccess) {
    199. throw new RuntimeException("子事务失败,需要回滚");
    200. }
    201. }
    202. private TransactionStatus openNewTransaction(DataSourceTransactionManager transactionManager) {
    203. //JdbcTransactionManager根据TransactionDefinition信息来进行一些连接属性的设置
    204. //包括隔离级别和传播行为等
    205. DefaultTransactionDefinition transactionDef = new DefaultTransactionDefinition();
    206. //开启一个新事务---此时autocommit已经被设置为了false,并且当前没有事务,这里创建的是一个新事务
    207. return transactionManager.getTransaction(transactionDef);
    208. }
    209. private DataSourceTransactionManager getTransactionManager() {
    210. return new DataSourceTransactionManager(dataSource);
    211. }
    212. /**
    213. * 保存当前事务资源,用于线程间的事务资源COPY操作
    214. */
    215. @Builder
    216. private static class TransactionResource {
    217. //事务结束后默认会移除集合中的DataSource作为key关联的资源记录
    218. private Map<Object, Object> resources = new HashMap<>();
    219. //下面五个属性会在事务结束后被自动清理,无需我们手动清理
    220. private Set<TransactionSynchronization> synchronizations = new HashSet<>();
    221. private String currentTransactionName;
    222. private Boolean currentTransactionReadOnly;
    223. private Integer currentTransactionIsolationLevel;
    224. private Boolean actualTransactionActive;
    225. public static TransactionResource copyTransactionResource() {
    226. return TransactionResource.builder()
    227. //返回的是不可变集合,这里为了更加灵活,copy出一个集合过来
    228. .resources(new HashMap<>(TransactionSynchronizationManager.getResourceMap()))
    229. //如果需要注册事务监听者,这里记得修改--我们这里不需要,就采用默认负责--spring事务内部默认也是这个值
    230. .synchronizations(new LinkedHashSet<>())
    231. .currentTransactionName(TransactionSynchronizationManager.getCurrentTransactionName())
    232. .currentTransactionReadOnly(TransactionSynchronizationManager.isCurrentTransactionReadOnly())
    233. .currentTransactionIsolationLevel(TransactionSynchronizationManager.getCurrentTransactionIsolationLevel())
    234. .actualTransactionActive(TransactionSynchronizationManager.isActualTransactionActive())
    235. .build();
    236. }
    237. //装配事务资源,为提交/回滚做储备
    238. public void autoWiredTransactionResource() {
    239. //获取当前线程事务资源
    240. Map<Object, Object> resourceMap = TransactionSynchronizationManager.getResourceMap();
    241. for (Object o : resourceMap.keySet()) {
    242. if (resourceMap.containsKey(o)) {
    243. //移除重复事务资源key,避免绑定报错
    244. resources.remove(o);
    245. }
    246. }
    247. boolean synchronizationActive = TransactionSynchronizationManager.isSynchronizationActive();
    248. //绑定事务资源,注意 绑定是绑定到当前主线程上,记得最后释放交换主线程,再由主线程收回原有事务自选
    249. resources.forEach(TransactionSynchronizationManager::bindResource);
    250. //如果需要注册事务监听者,这里记得修改--我们这里不需要,就采用默认负责--spring事务内部默认也是这个值
    251. //避免重复激活或者事务未激活
    252. if (!synchronizationActive) {
    253. TransactionSynchronizationManager.initSynchronization();
    254. }
    255. TransactionSynchronizationManager.setActualTransactionActive(actualTransactionActive);
    256. TransactionSynchronizationManager.setCurrentTransactionName(currentTransactionName);
    257. TransactionSynchronizationManager.setCurrentTransactionIsolationLevel(currentTransactionIsolationLevel);
    258. TransactionSynchronizationManager.setCurrentTransactionReadOnly(currentTransactionReadOnly);
    259. }
    260. public void removeTransactionResource() {
    261. Map<Object, Object> resourceMap = new HashMap<>(TransactionSynchronizationManager.getResourceMap());
    262. //事务结束后默认会移除集合中的DataSource作为key关联的资源记录
    263. //DataSource如果重复移除,unbindResource时会因为不存在此key关联的事务资源而报错
    264. resources.keySet().forEach(key -> {
    265. if (resourceMap.containsKey(key)) {
    266. TransactionSynchronizationManager.unbindResource(key);
    267. }
    268. });
    269. }
    270. }
    271. }

    验证

    1. @Transactional
    2. public String test(Integer par) {
    3. log.info("get(" + par + ")");
    4. if (par == 3 || par == 5 || par == 6) {
    5. Per per2 = new Per();
    6. per2.setName("t3");
    7. per2.setGrou(Thread.currentThread().getName());
    8. perService.save(per2);
    9. }
    10. List<Runnable> list = new ArrayList<>();
    11. list.add(() -> {
    12. Per per = new Per();
    13. per.setName("t1");
    14. per.setGrou(Thread.currentThread().getName());
    15. log.info("任务开始save");
    16. perService.save(per);
    17. log.info("任务完成save");
    18. if (par == 1) {
    19. throw new RuntimeException();
    20. }
    21. });
    22. list.add(() -> {
    23. Per per1 = new Per();
    24. per1.setName("t2");
    25. per1.setGrou(Thread.currentThread().getName());
    26. log.info("任务开始save");
    27. perService.save(per1);
    28. log.info("任务完成save");
    29. if (par == 2) {
    30. throw new RuntimeException();
    31. }
    32. });
    33. log.info("runAsyncButWaitUntilAllDown start");
    34. multiplyThreadTransactionManager.runAsyncButWaitUntilAllDown(list, false);
    35. if (par == 4 || par == 5 || par == 6) {
    36. Per per3 = new Per();
    37. per3.setName("t4");
    38. per3.setGrou(Thread.currentThread().getName());
    39. perService.save(per3);
    40. if (par == 6) {
    41. throw new RuntimeException();
    42. }
    43. }
    44. log.info("multiplyThreadTransactionCommit start");
    45. multiplyThreadTransactionManager.multiplyThreadTransactionCommit();
    46. return "ss";
    47. }

    有兴趣的小伙伴可以做进一步测试。

    在本公司项目组中利用这个机制优化现有的业务,性能提升了约70%。

    比起网上常见的多线程事务管理器,主要做了如下增强

    1.支持在已存在事务下运行。

    在很多场景下,我们可能会遇到多线程事务外还存在其他事物的场景下,我们需要支持兼容多种事务环境。

    2.支持自定义提交时机。

    有时候我们不希望事务立马提交,希望他能够和外围事务保持一致,这时候可以将runAsyncButWaitUntilAllDown的immediatelyCommit参数写成false,并手动调用multiplyThreadTransactionCommit方法去主动提交。

    我们需要注意的地方,任何事都是有舍有得的,耗时的显著降低是因为利用了更多的资源,比如线程资源和数据库连接资源,尤其是数据库连接资源,更是额外宝贵,我们一定要合理评估我们的每一项决策是否有意义,风险和回报是否成正比。

    还有一点需要注意,在极高并发的情况下,多线程事务容易造成死锁,因为当主事务开启的情况下,他要为他下面的子线程事务开启连接,当连接不够时就容易造成循环等待。一个比较好的做法是提前获得所有连接,并设置一个合理的超时时间

    如果有小伙伴遇到了其他相关疑问,或者使用此代码发现了问题,欢迎留言讨论,共同进步。

    文章转载自:doFix

    原文链接:https://www.cnblogs.com/fix200/p/18066537

    体验地址:引迈 - JNPF快速开发平台_低代码开发平台_零代码开发平台_流程设计器_表单引擎_工作流引擎_软件架构

  • 相关阅读:
    Andriod开发R文件爆红相关解决方法及排查方案
    Linkers of Addition
    SpringBoot 集成 elasticsearch
    vmware安装linux操作系统
    四种自动化测试模型实例及优缺点
    【ES6】阮一峰ES6学习(五)Set和Map联系及区别
    数据库系统
    探索ABP的EventHub解决方案
    面试总结之JVM入门
    Cadence Allegro焊盘设计经验原则
  • 原文地址:https://blog.csdn.net/kfashfasf/article/details/136652416