在spring中多线程访问hibernate

发布于 2022-09-13 00:17:03 字数 7828 浏览 40 评论 0

在spring+hibernate环境下,存在下面的代码

下面是用于获取bean的工具类

@Component
public class BeanContext implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanContext.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) throws BeansException {
        notEmpty(Collections.singleton(name),"bean name is required!");
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clz) throws BeansException {
        return (T)applicationContext.getBean(clz);
    }

}

下面是用于在线程中获取信息的接口和实现

public interface IListenter {
    Message getMessage() throws Exception;
}

public abstract class Listenter implements IListenter {
    private LogService logService = null;

    public Listenter(Bean bean) {
        this.bean = bean;
        if (null == logService){
            logService = BeanContext.getBean(LogService.class);
        }
    }

    protected void saveMsgLog(String msgnum, String recemsg) {
        try {
            if(null != logService){
                //保存到数据库中,也就是这里会报错
                logService.saveMessage(msgnum, recemsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    ...
}

public class ServiceListener extends Listenter implements Runnable {

    public void run() {
        while(true){
            Message m = getMessage();
            saveMsgLog(m.msgnumber, m.recemsg);
        }
    }
}

下面是保存信息的server

@Service("logServer")
public class LogServiceImpl implements LogService {
    @Autowired
    private BaseDao baseDao;

    public void saveMessage(String msgNumber, String msgStr) {
        StringBuffer insertSql = new StringBuffer("insert into message (***) ");
        //省略部分。。。。
        try {
            baseDao.executeBySql(insertSql.toString(), objects);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在多线程中执行到

logService.saveRecvMessageLog(msgnum, recemsg);

抛出了异常

[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R Exception in thread "pool-1-thread-5" java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext
[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R     at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:170)
[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R     at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:968)
[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R     at com.dd.thread.CardVerification.run(CardVerification.java:46)
[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R     at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1061)
[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R     at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:575)
[21-6-18 11:02:16:579 CST] 000000ef SystemErr     R     at java.lang.Thread.run(Thread.java:736)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:544)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:457)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:276)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at com.dd.service.impl.LogServiceImpl$$EnhancerBySpringCGLIB$$6eef68de.saveRecvMessageLog(<generated>)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at com.dd.thread.Listenter.saveMsgLog(Listenter.java:129)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at com.dd.thread.ServiceListener.run(ServiceListener.java:77)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1061)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:575)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at java.lang.Thread.run(Thread.java:736)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R Caused by: org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.service.jdbc.connections.spi.ConnectionProvider]
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:126)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.internal.AbstractSessionImpl.getJdbcConnectionAccess(AbstractSessionImpl.java:261)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.<init>(JdbcCoordinatorImpl.java:97)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.<init>(TransactionCoordinatorImpl.java:87)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:254)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1609)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:973)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     at org.springframework.orm.hibernate4.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:436)
[21-6-18 14:21:56:744 CST] 000000d7 SystemErr     R     ... 15 more

求助各位大佬!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文