子线程获取不到hibernate session问题

Could not obtain transaction-synchronized Session for current thread

问题出现的场景

最近在优化项目 “修改直播状态——同步状态到另一个服务”这个业务时,因为这两个步骤是顺序的,所以我打算抽取成一个service方法去处理

以下是LiveWriteServiceImpl.java优化后的代码

	@Override
    public void statusDisable(PushPool pushPool) {
        Live live = liveDao.get(pushPool.getParentLive().getId());
        live.setStatus(Status.DISABLE); // 直播设置为禁用
        live.setSkipUpdate(true); // 跳过update方法
        update(live);
        
        // 保存/更新pv服务
        serviceExecutor.execute(() -> editLivePvBasic(live.getId()), 5 * 1000); 
    }

	@Override
    public void editLivePvBasic(String liveId) {
        Live live = liveDao.get(liveId);
        // .... 省略更新数据到pv服务的逻辑 ....
        
        // 更新发送pv服务为true
        live.setSendPv(true);
        live.setSkipUpdate(true);
        update(live);
        }
    }

但是在测试的过程中,出现以下异常:Could not obtain transaction-synchronized Session for current thread,类似日志如下

org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
	at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:137)
	at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:464)
	at cn.com.ava.hibernate.dao.BaseDaoImpl.getCurrentSession(BaseDaoImpl.java:121)
	at cn.com.ava.hibernate.dao.BaseDaoImpl.get(BaseDaoImpl.java:170)
	at cn.com.ava.hibernate.dao.BaseDaoImpl$$FastClassBySpringCGLIB$$597e9197.invoke(<generated>)
	at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
	at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:746)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
	at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
	at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
	at cn.com.ava.cloud.yun.alive.module.biz.live.dao.LiveDaoImpl$$EnhancerBySpringCGLIB$$325ee6b6.get(<generated>)
	at cn.com.ava.hibernate.service.BaseServiceImpl.get(BaseServiceImpl.java:250)
	at cn.com.ava.cloud.yun.alive.module.biz.live.service.LiveWriteServiceImpl.antherUpdate(LiveWriteServiceImpl.java:659)
	at cn.com.ava.cloud.yun.alive.module.biz.live.service.LiveWriteServiceImpl.lambda$testCouldNotGetSession2$5(LiveWriteServiceImpl.java:655)
	at cn.com.ava.hibernate.service.ServiceExecutor.doInLog(ServiceExecutor.java:170)
	at cn.com.ava.hibernate.service.ServiceExecutor.access$000(ServiceExecutor.java:30)
	at cn.com.ava.hibernate.service.ServiceExecutor$1.run(ServiceExecutor.java:81)
	at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
	at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
	at java.util.concurrent.FutureTask.run(FutureTask.java)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
	at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:748)

出现问题的原因
Hibernate的session

Hibernate的session是和 线程/事务挂钩的

Session的生命周期由事务的开始和结束绑定(长事务可能跨越多个数据库事务)

每个线程/事务都应该从 SessionFactory 获取自己的实例

一个事务对应一个session,而session是存放在当前线程的‘ThreadLoacal<Map>线程本地变量表中

原因

而上面的代码会出现以下现象:一个事务跨越了父线程和子线程,当子线程去自己的本地变量表查找当前事务的session时,查找到为null,导致抛出异常

排查过程

实体的增删改查,都需要获取到当前事务的session

	BaseDaoImpl.java
	public Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }

	SessionFactoryImpl.java
    public Session getCurrentSession() throws HibernateException {
        if (this.currentSessionContext == null) {
            throw new HibernateException("No CurrentSessionContext configured!");
        } else {
            return this.currentSessionContext.currentSession();
        }
    }

​ 我们应用使用到的currentSessionContext是:org.springframework.orm.hibernate5.SpringSessionContext

spring:
  jpa:
    properties:
      hibernate:
        current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext
SpringSessionContext.java
public Session currentSession() throws HibernateException {
    	// 进入TransactionSynchronizationManager.getResource
		Object value = TransactionSynchronizationManager.getResource(this.sessionFactory);
		if (value instanceof Session) {
			return (Session) value;
		}
		else if (value instanceof SessionHolder) {
			SessionHolder sessionHolder = (SessionHolder) value;
			Session session = sessionHolder.getSession();
			if (!sessionHolder.isSynchronizedWithTransaction() &&
					TransactionSynchronizationManager.isSynchronizationActive()) {
				TransactionSynchronizationManager.registerSynchronization(
						new SpringSessionSynchronization(sessionHolder, this.sessionFactory, false));
				sessionHolder.setSynchronizedWithTransaction(true);
				// Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
				// with FlushMode.MANUAL, which needs to allow flushing within the transaction.
				FlushMode flushMode = SessionFactoryUtils.getFlushMode(session);
				if (flushMode.equals(FlushMode.MANUAL) &&
						!TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
					session.setFlushMode(FlushMode.AUTO);
					sessionHolder.setPreviousFlushMode(flushMode);
				}
			}
			return session;
		}

		if (this.transactionManager != null && this.jtaSessionContext != null) {
			// 省略
		}

		if (TransactionSynchronizationManager.isSynchronizationActive()) {
            // 省略
			return session;
		}
		else {
			throw new HibernateException("Could not obtain transaction-synchronized Session for current thread");
		}
	}

下面的代码体现出:session是存放在当前线程的‘ThreadLoacal<Map>线程本地变量表中

TransactionSynchronizationManager.java
	public static Object getResource(Object key) {
		Object actualKey = TransactionSynchronizationUtils.unwrapResourceIfNecessary(key);
		// 进入doGetResource方法
		Object value = doGetResource(actualKey);
		if (value != null && logger.isTraceEnabled()) {
            // 省略
		}
		return value;
	}


	private static final ThreadLocal<Map<Object, Object>> resources =
			new NamedThreadLocal<>("Transactional resources");

	private static Object doGetResource(Object actualKey) {
        // 这里的resources是 Spring继承实现了一个有命名功能的ThreadLocal,本质也是一个ThreadLocal
		Map<Object, Object> map = resources.get();
		if (map == null) {
			return null;
		}
        
        // 这里从ThreadLocal获取到的value,即session或者封装了session的数据
        // actualKey实际是上面传下来的(当前应用的)sessionFactory实例
		Object value = map.get(actualKey);
        
		if (value instanceof ResourceHolder && ((ResourceHolder) value).isVoid()) {
            // 省略
		}
		return value;
	}
ThreadLocal.java
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

如何进行解决

在子线程中,新开一个事务去解决,这样的话,子线程就能通过自己的事务创建一个属于自己的session,保存在自己的ThreadLocal线程本地变量表中

	@Override
    public void statusDisable(PushPool pushPool) {
        Live live = liveDao.get(pushPool.getParentLive().getId());
        live.setStatus(Status.DISABLE); // 直播设置为禁用
        live.setSkipUpdate(true); // 跳过update方法
        update(live);
        
        // 保存/更新pv服务
		// 使用executeInTx,线程池中新开了一个事务执行
        serviceExecutor.executeInTx(() -> editLivePvBasic(live.getId()), 5 * 1000); 
    }

	@Override
    public void editLivePvBasic(String liveId) {
        Live live = liveDao.get(liveId);
        // .... 省略更新数据到pv服务的逻辑 ....
        
        // 更新发送pv服务为true
        live.setSendPv(true);
        live.setSkipUpdate(true);
        update(live);
        }
    }
serviceExecutor.java
    public void execute(final Runnable runnable, long delay) {
        this.delayExecutor.schedule(new TimerTask() {
            public void run() {
                ServiceExecutor.this.doInLog(runnable);
            }
        }, Math.max(delay, 100L), TimeUnit.MILLISECONDS);
    }

    public void executeInTx(final Runnable runnable, long delay) {
        this.delayExecutor.schedule(new TimerTask() {
            public void run() {
                ServiceExecutor.this.doInTx(runnable);
            }
        }, Math.max(delay, 100L), TimeUnit.MILLISECONDS);
    }

    private void doInTx(final Runnable runnable) {
        (new TransactionTemplate(this.platformTransactionManager)).execute(new TransactionCallbackWithoutResult() {
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                ServiceExecutor.this.doInLog(runnable);
            }
        });
    }

    private void doInLog(Runnable runnable) {
        try {
            runnable.run();
        } catch (Throwable var3) {
            LOG.error(var3.getMessage(), var3);
        }

    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值