【发布时间】: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 个线程。
- 如果我同时使用@Async 和@Transactional(我不应该这样做),那么 多线程发生。但回滚不起作用。
【问题讨论】:
标签: spring multithreading spring-boot hibernate exception