在Spring 4中,如何在主线程之外创建@Transactional?

时间:2017-06-14 18:59:39

标签: spring multithreading hibernate spring-transactions transactional

我使用Spring 4.3.8.RELEASE和Hibernate 5.1。我在我的上下文中设置了一个线程池

<bean id="myprojectThreadFactory" class="org.springframework.scheduling.concurrent.CustomizableThreadFactory">
    <constructor-arg value="myproject-"/>
</bean>
<bean id="myprojectTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="threadFactory" ref="myprojectThreadFactory"/>
    <property name="corePoolSize" value="${myproject.core.thread.pool.size}" />
    <property name="maxPoolSize" value="${myproject.max.thread.pool.size}" />
</bean>

但是如何在我的主线程之外的任务线程中创建一个事务呢?我正在尝试这个

        // Cue up threads to execute
        for (final Organization org : allOrgs)
        {
            m_threadExecutor.execute(new Thread(new Runnable(){
                @Override
                @Transactional(propagation=Propagation.REQUIRES_NEW)
                public void run()
                {
                    System.out.println("started.");
                    processData(org.getId());
                    System.out.println("finished.");
                }
            }));

但这导致了以下异常

Exception in thread "myproject-1" Exception in thread "myproject-2" org.hibernate.SessionException: Session is closed!
    at org.hibernate.internal.AbstractSessionImpl.errorIfClosed(AbstractSessionImpl.java:132)
    at org.hibernate.internal.SessionImpl.setCacheMode(SessionImpl.java:1511)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1109)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1033)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy68.find(Unknown Source)
    at org.mainco.subco.core.repo.GenericDao.find(GenericDao.java:123)
    at org.mainco.subco.organization.repo.OrganizationDaoImpl.find(OrganizationDaoImpl.java:61)
    at org.mainco.subco.organization.service.OrganizationServiceImpl.getDescendantOrganizations(OrganizationServiceImpl.java:283)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy75.getDescendantOrganizations(Unknown Source)
    at org.mainco.subco.myproject.repo.myprojectClassDaoImpl.findBymyprojectOrg(myprojectClassDaoImpl.java:89)
    at org.mainco.subco.myproject.service.myprojectClassServiceImpl.find(myprojectClassServiceImpl.java:300)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy91.find(Unknown Source)
    at org.mainco.subco.myproject.quartz.ImportClassesWorker.preProcessData(ImportClassesWorker.java:56)
    at org.mainco.subco.myproject.quartz.AbstractImportDataWorker.processData(AbstractImportDataWorker.java:126)
    at org.mainco.subco.myproject.quartz.AbstractImportDataWorker.access$0(AbstractImportDataWorker.java:123)
    at org.mainco.subco.myproject.quartz.AbstractImportDataWorker$1.run(AbstractImportDataWorker.java:110)
    at java.lang.Thread.run(Thread.java:745)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

2 个答案:

答案 0 :(得分:1)

使用TransactionTemplate作为逻辑。像这样的东西

final TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
   taskExecutor.execute(new Runnable() {
        @Override
        public void run() {
            transactionTemplate.execute(new TransactionCallbackWithoutResult() {
                @Override
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                System.out.println("started.");
                processData(org.getId());
                System.out.println("finished.");
                }
            });
        }
    });  

答案 1 :(得分:0)

Spring对您的Runnable实例一无所知。因此,在run方法上添加注释没有任何意义。相反,您要做的是将@Transactional放在processData方法上。但请注意它应该是Spring bean的方法

<强>更新 只是尝试使用@Transactional@Async标记商业方法,它对我有用。我使用了弹簧4.3.9.RELEASE和hibernate 5.0.12.Final附带的版本1.5.4.RELEASE的spring-boot。对于我的@Async配置,我刚使用了@EnableAsync。这就是我所拥有的:

@Test
@Transactional
public void test() throws InterruptedException {
    beanA.testMethodA();

    //Sleeping, since after test is completed application is down which leaves @Async transaction not completed.
    Thread.sleep(3000);

    System.out.println("Thread in test method: "  + Thread.currentThread().getName());
    System.out.println("Transaction in test method: "  + TransactionSynchronizationManager.getCurrentTransactionName());
}

这是BeanA的一种方法。它具有默认传播级别的事务性,这使得它受到测试启动的事务的限制:

@Override
@Transactional
public void testMethodA() {
    beanB.testMethodB();

    System.out.println("Thread in method A: " + Thread.currentThread().getName());
    System.out.println("Transaction in method A: " + TransactionSynchronizationManager.getCurrentTransactionName());
}

最后一部分 - BeanB的方法,标记为@Async@Transactional。它确实在单独的线程和单独的事务中运行:

@Async
@Transactional
@Override
public void testMethodB() {
    System.out.println("Thread in method B: "  + Thread.currentThread().getName());
    System.out.println("Transaction in method B: "  + TransactionSynchronizationManager.getCurrentTransactionName());
}

运行测试后,我得到以下输出:

Thread in test method: main
Transaction in test method: com.example.stackoverflow.TransactionTest.test

Thread in method A: main
Transaction in method A: com.example.stackoverflow.TransactionTest.test

Thread in method B: SimpleAsyncTaskExecutor-1
Transaction in method B: com.example.stackoverflow.BeanBImpl.testMethodB

注意最后两个陈述。标记为@Async@Transactional的方法在其自己的事务及其自己的线程中运行。