解决Shiro+SpringBoot异步任务长时间运行导致的UnknownSessionException错误问题

本文探讨了Springboot中异步任务运行时长超过Shiro默认超时时间导致的Session异常,提出了一种通过Controller获取Session并手动刷新的方法,并指出其潜在的BUG。寻求更优解决方案。
摘要由CSDN通过智能技术生成

当Springboot的异步任务运行时长超过了Shiro设置的超时时间后,会造成Session异常,最终导致数据无法插入到数据库等其他问题;

2021-07-06 16:03:21.675  WARN 20823 --- [         task-2] c.l.a.v.service.impl.AsyncServiceImpl    : [OUDWRN][1999/2000]转储数据失败:EscrowVideo{title='null', desc='" #fyp"'}; 原因:There is no session with id [1acf90c0-7c56-4c3e-8263-9b10321d13ab]
org.apache.shiro.session.UnknownSessionException: There is no session with id [1acf90c0-7c56-4c3e-8263-9b10321d13ab]
        at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170)
        at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236)
        at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSession(DefaultSessionManager.java:222)
        at org.apache.shiro.session.mgt.AbstractValidatingSessionManager.doGetSession(AbstractValidatingSessionManager.java:118)
        at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupSession(AbstractNativeSessionManager.java:148)
        at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupRequiredSession(AbstractNativeSessionManager.java:152)
        at org.apache.shiro.session.mgt.AbstractNativeSessionManager.getAttribute(AbstractNativeSessionManager.java:249)
        at org.apache.shiro.session.mgt.DelegatingSession.getAttribute(DelegatingSession.java:141)
        at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
        at org.apache.shiro.subject.support.DelegatingSubject.getRunAsPrincipalsStack(DelegatingSubject.java:473)
        at org.apache.shiro.subject.support.DelegatingSubject.getPrincipals(DelegatingSubject.java:157)
        at org.apache.shiro.subject.support.DelegatingSubject.getPrincipal(DelegatingSubject.java:153)
        at com.linln.component.shiro.config.AuditorConfig.getCurrentAuditor(AuditorConfig.java:27)
        at org.springframework.data.auditing.AuditingHandler.lambda$touchAuditor$6(AuditingHandler.java:193)
        at java.util.Optional.map(Optional.java:215)
        at org.springframework.data.auditing.AuditingHandler.touchAuditor(AuditingHandler.java:191)
        at org.springframework.data.auditing.AuditingHandler.lambda$touch$0(AuditingHandler.java:165)
        at java.util.Optional.map(Optional.java:215)
        at org.springframework.data.auditing.AuditingHandler.touch(AuditingHandler.java:163)
        at org.springframework.data.auditing.AuditingHandler.markCreated(AuditingHandler.java:131)
        at org.springframework.data.jpa.domain.support.AuditingEntityListener.touchForCreate(AuditingEntityListener.java:92)
        at sun.reflect.GeneratedMethodAccessor159.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.hibernate.jpa.event.internal.ListenerCallback.performCallback(ListenerCallback.java:35)
        at org.hibernate.jpa.event.internal.CallbackRegistryImpl.callback(CallbackRegistryImpl.java:97)
        at org.hibernate.jpa.event.internal.CallbackRegistryImpl.preCreate(CallbackRegistryImpl.java:57)
        at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:112)
        at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192)
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135)
        at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:62)
        at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:799)
        at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)
        at sun.reflect.GeneratedMethodAccessor161.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:308)
        at com.sun.proxy.$Proxy126.persist(Unknown Source)
        at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:489)
        at sun.reflect.GeneratedMethodAccessor156.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
        at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:138)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:93)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
        at com.sun.proxy.$Proxy149.save(Unknown Source)
        at com.linln.models.videnter.server.impl.VirkarServerImpl.save(VirkarServerImpl.java:71)
        at com.linln.models.videnter.server.impl.VirkarServerImpl.handlerFile(VirkarServerImpl.java:78)
        at com.linln.models.videnter.server.impl.VirkarServerImpl$$FastClassBySpringCGLIB$$3f874d6e.invoke(<generated>)
        at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218)
        at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:749)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
        at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:688)
        at com.linln.models.videnter.server.impl.VirkarServerImpl$$EnhancerBySpringCGLIB$$43dc8bf4.handlerFile(<generated>)
        at com.linln.admin.videnter.service.impl.AsyncServiceImpl.pullEscrowVideo(AsyncServiceImpl.java:61)
        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:498)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
        at org.springframework.aop.interceptor.AsyncExecutionInterceptor.lambda$invoke$0(AsyncExecutionInterceptor.java:115)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        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)

org.apache.shiro.session.UnknownSessionException: There is no session with id [1acf90c0-7c56-4c3e-8263-9b10321d13ab]

在研究了好长时间后,找到了一个简单暴力的方式解决Session超时问题,代码如下:

Controller类:

在方法中获取当前Session,传入异步方法中;

/**
 * 
 */
@Controller
@RequestMapping("/basepath/")
@EnableAsync
public class UploadVideoController {
    /**
     * 异步服务
     */
    private final AsyncService asyncService;
    /**
     * 保存数据
     */
    @PostMapping("/task/now")
    @RequiresPermissions("videnter:video:upload:task")
    @ResponseBody
    public String doTask() {
        Subject subject = SecurityUtils.getSubject();
        if (subject == null) {
            return "无法获取登陆信息";
        }
        Session session = subject.getSession();
        if (session == null) {
            return "无法获取Session信息!";
        }
        asyncService.doJob(session);
        return "OK";
    }
}

Server类:

在工作流程开始或结束后,判断Session是否临近到期(小于一定时间),如果快到期了,手动更新一下最后访问时间(session.touch();)即可;

@Service
public class AsyncServiceImpl implements AsyncService {
    @Async
    @Override
    public void doJob(Session session){
        while(true){
            //如果Session到期时间小于10分钟,则手动为SESSION续命
            if (Math.abs(System.currentTimeMillis() - session.getLastAccessTime().getTime()) < 600L) {
                session.touch();
            }
            .........
        }
    }
}

这样虽然能解决问题,但是会引起一个BUG

如果你有更好的解决办法请留言告诉我,感激不尽!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值