gpt4 book ai didi

java - 将服务层传递给线程的正确方法

转载 作者:行者123 更新时间:2023-11-30 01:38:36 25 4
gpt4 key购买 nike

我的服务层方法是事务性的,当我使用 ExecutorService 并将任务提交给线程时,我无法将 servicelayer 作为参数传递给每个线程,因为我收到错误

Dec 14, 2009 10:40:18 AM com.companyx.applicationtest.applicationtestcompanyx.services.threadtestRunnable run
SEVERE: null
org.hibernate.HibernateException: No Hibernate Session bound to thread, and conf
iguration does not allow creation of non-transactional one here
at org.springframework.orm.hibernate3.SpringSessionContext.currentSessio
n(SpringSessionContext.java:63)
at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactor
yImpl.java:542)

我的服务层

ExecutorService executor = Executors.newFixedThreadPool(10);
for (final Object item : CollectionsTest{
executor.submit(new threadtestRunnable((Long)item,collectionAfterfiltered,this)); //'this' is service layer
}
  1. 我应该像这样将服务层传递给每个线程吗?
  2. 正确的方法是什么,我需要每个线程调用服务层中的方法? (我使用的是 Spring )

最佳答案

一般来说,正如评论中所说,事务不应该在多个线程中运行。但是,在某些情况下这是可以接受的。

  • 您需要与网络服务进行一些异步通信(不让用户等待结果),并在结果到来时存储结果
  • 您需要在多个线程中进行只读事务。

如果您使用 new 创建线程,它不是 spring 上下文的一部分。因此,当创建线程的方法完成时,您的事务拦截器将关闭事务(以及最终的 session ),并且您将得到上述异常。

(有关更多详细信息 - Spring docs,请参阅“查找注入(inject)”)

您需要在 spring 上下文中创建线程。因为您可能是从 singleton 创建它们的bean,这是罕见的创建prototype的情况来自 singleton 的 bean bean 。因此,为了在 spring 上下文中创建线程,您可以使用:

 <bean id="mainBean"
class="com.my.MyClass">
<lookup-method name="createThread" bean="myThreadBean"/>
</bean>

您还应该映射您的 ThreadtestRunnable applicationContext.xml中的类(class)或者将其注释为 @Component("myThreadBean") .

然后定义一个abstract名为 createThread 的主 bean 上的方法并返回你的线程类。使用 @Transactional 注释您的运行方法(或者定义适当的aop规则),然后尝试一下。也许您需要设置 propagation=Propagation.REQUIRES_NEW"在你的@Transactional 。如果有任何问题,请返回此处。

关于java - 将服务层传递给线程的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1898696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com