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(live);
serviceExecutor.execute(() -> editLivePvBasic(live.getId()), 5 * 1000);
}
@Override
public void editLivePvBasic(String liveId) {
Live live = liveDao.get(liveId);
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 {
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);
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);
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) {
Map<Object, Object> map = resources.get();
if (map == null) {
return null;
}
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(live);
serviceExecutor.executeInTx(() -> editLivePvBasic(live.getId()), 5 * 1000);
}
@Override
public void editLivePvBasic(String liveId) {
Live live = liveDao.get(liveId);
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);
}
}
|