【问题标题】:How to use @Async and @Transactional for rolling back in multi threading?如何使用@Async 和@Transactional 在多线程中回滚?
【发布时间】:2022-01-07 03:16:04
【问题描述】:

我的要求是回滚多线程系统中的所有事务 如果其中一个线程遇到异常。

package com.demo.multithread; 

@Repository
@Configuration
public class DemoService {

    @Autowired
    private EntityManager entityManager;
    
    @Bean
    @Transactional(rollbackFor = {Exception.class,Error.class})
    public void callProcedure()
    {
        StoredProcedureQuery query = entityManager.createNamedStoredProcedureQuery("MyProcedure");
        query.execute();
    }
}

下面是我如何使用 Async。

package com.demo.multithread; 

@Repository
@Configuration
@EnableAsync
public class DemoDAO 
{
@Autowired
public DemoService demoService;

@Bean(name = "threadPoolTaskExecutor")
    public ExecutorService executorService() 
    {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("myThread-");
        executor.initialize();
        System.out.println("Returning from executor service");
        return executor.getThreadPoolExecutor();
    }

@Async(value ="threadPoolTaskExecutor")
     public void asyncMethodWithConfiguredExecutor() throws InterruptedException 
     {
        System.out.println("Thread ID~" + Thread.currentThread().getId()+ " is running and thread name is ~"+Thread.currentThread().getName());
        demoService.callProcedure();
     }
}

问题是:

  1. 没有发生多线程。
  2. 在启动时只创建了 1 个线程。
  3. 如果我同时使用@Async 和@Transactional(我不应该这样做),那么 多线程发生。但回滚不起作用。

【问题讨论】:

    标签: spring multithreading spring-boot hibernate exception


    【解决方案1】:

    当@Async 方法启动时,它会在一个新线程上运行,这就是@Transaction 不起作用的原因。 @Async 方法调用不能回滚,但是没有异步调用,你可以进行回滚。

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2023-03-10
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2013-02-05
      • 2013-11-24
      相关资源
      最近更新 更多