springboot 定时任务 session报错问题
一、自定义类 LocalVariable
package com.lh.mes.base.thread;
import java.util.Optional;
public class LocalVariable {
private LocalVariable() {
}
private static final ThreadLocal<String> PRINCIPAL_ID = new ThreadLocal<>();
/**
* 添加用户id
* @param principalId 用户id
*/
public static void setPrincipalId(String principalId) {
PRINCIPAL_ID.set(principalId);
}
/**
* 获取用户id
* @return 用户id
*/
public static String getPrincipalId() {
return PRINCIPAL_ID.get();
}
public static Optional<String> getPrincipalIdOptional() {
return Optional.ofNullable(getPrincipalId());
}
}
二、拦截器保存想要保存的值
package com.lh.mes.base.interceptor; import com.lh.mes.base.annotation.Authorization;
import com.lh.mes.base.constant.AuthorizationConstants;
import com.lh.mes.base.thread.LocalVariable;
import com.lh.mes.base.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import springfox.documentation.swagger.web.ApiResourceController;
import springfox.documentation.swagger2.web.Swagger2Controller; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method; /**
* token 拦截器
* @author Niles
*/
@Slf4j
@Component
public class AccessTokenInterceptor implements HandlerInterceptor { /** redis 数据库操作模板类*/
@Autowired
private RedisTemplate<String, String> redisTemplate; @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//如果不是映射到方法直接通过
if (!(handler instanceof HandlerMethod)
|| ((HandlerMethod) handler).getBean() instanceof ApiResourceController
|| ((HandlerMethod) handler).getBean() instanceof Swagger2Controller) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
Authorization authorization = method.getAnnotation(Authorization.class);
if (authorization != null && !authorization.required()) {
//过滤不拦截的方法
return true;
}
//从header中得到token
String token = request.getHeader(AuthorizationConstants.AUTHORIZATION);
if (!StringUtils.hasText(token)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return false;
}
Claims claims;
try {
claims = TokenUtil.parseJWT(token);
} catch (ExpiredJwtException expiredJwtException) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
log.warn("token 过期了");
return false;
} catch (Exception exception) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
log.warn("无效 token");
return false;
}
String principalId = claims.getId();
if (!redisTemplate.opsForSet().isMember(AuthorizationConstants.REDIS_TOKEN_KEY + principalId, token)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
log.info("用户不存在或已失效,请重新登录");
return false;
}
LocalVariable.setPrincipalId(principalId);
return true;
} }
三、获取保存的值
/**
* 获取当前登录用户id
*
* @return 当前登录用户id
*/
@Override
public String getCurrentPrincipalId() {
return LocalVariable.getPrincipalId();
}
springboot 定时任务 session报错问题的更多相关文章
- Springboot数据库连接池报错的解决办法
Springboot数据库连接池报错的解决办法 这个异常通常在Linux服务器上会发生,原因是Linux系统会主动断开一个长时间没有通信的连接 那么我们的问题就是:数据库连接池长时间处于间歇状态,导致 ...
- CodeIgniter 3.0+ 部署linux环境 session报错
codeigniter Message: mkdir(): Invalid path Filename: drivers/Session_files_driver.php 看起来像权限问题,在默认情况 ...
- Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans
Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans
- 【spring boot】使用定时任务@Scheduled 报错:Encountered invalid @Scheduled method 'dealShelf': Cron expression must consist of 6 fields (found 7 in "0 30 14 * * ? *")
在spring boot中使用使用定时任务@Scheduled 报错: org.springframework.beans.factory.BeanCreationException: Error c ...
- springboot测试启动报错java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
springboot测试启动报错: java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you ne ...
- springboot项目启动报错Failed to configure a DataSource: 'url' attribute is not specified and no embedde
springboot项目启动报错Failed to configure a DataSource: 'url' attribute is not specified and no embedde 创建 ...
- Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]
Springboot整合Elasticsearch报错 今天使用SpringBoot整合Elasticsearch时候,相关的配置完成后,启动项目就报错了. nested exception is j ...
- SpringBoot集成MybatisPlus报错
SpringBoot集成MybatisPlus报错 启动的时候总是报如下错误: java.lang.annotation.AnnotationFormatError: Invalid default: ...
- Springboot 之 启动报错-Cannot determine embedded database driver class for database type NONE
Springboot 之 启动报错-数据库 springboot项目在启动时,报如下错误: Error starting ApplicationContext. To display the auto ...
随机推荐
- 攻防世界之Web_php_include
题目: 解题思路: 直接给出源码,由代码可知此题应该为文件包含,而且应该利用php伪协议 strstr() 函数搜索字符串在另一字符串中是否存在,如果是,返回该字符串及剩余部分,否则返回FALSE 可 ...
- 第一次打开pycharm运行python文件报错”No Python interpreter selected“问题的解决办法
前面没有细讲,这里细述一下安装pycharm后,第一次打开pycharm运行python文件报错"No Python interpreter selected"问题的解决办法. 出 ...
- C#值类型回收
函数调用在执行时,首先要在栈中为形参和局部变量分配存储空间,然后还要将实参的值复制给形参,接下来还要将函数的返回地址(该地址指明了函数执行结束后,程序应该回到哪里继续执行)放入栈中,最后才跳转到函数内 ...
- java内存区域模型和详解
一,概述 java虚拟机运行时数据区模型图: 主要包括:程序计数器,java虚拟机栈,本地方法栈,java 堆,方法区(元空间). 其中堆和方法区由所有线程共享的数据区:程序计数器,java虚拟机栈, ...
- 跨越DDD从理论到工程落地的鸿沟
摘要:本文从DDD的核心概念讲起,重点放在如何把理论落地成代码,期望给那些正在探索DDD的同学一些指引和启发. 本文分享自华为云社区<跨越DDD从理论到工程落地的鸿沟>,作者:敏捷小智. ...
- 【有奖调研】来,聊聊TTS音色定制这件事儿
音色个性化定制,一个能让文字转语音服务(TTS)在用户交互过程中注入温度的技术. 文能在营销及内容交付中让品牌保持一致性,武能让开发者"音"量加持,创新开发. 这个100%钢铁纯技 ...
- JZ-041-和为 S 的连续正数序列
和为 S 的连续正数序列 题目描述 小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100.但是他并不满足于此,他在想究竟有多少种连续的正数序列 的和为100( ...
- salesforce零基础学习(一百一十二)项目中的零碎知识点小总结(四)
本篇参考: https://trailblazer.salesforce.com/issues_view?id=a1p4V0000003znDQAQ https://salesforce.stacke ...
- Python:pyglet学习(1):想弄点3D,还发现了pyglet
某一天,我突然喜欢上了3D,在一些scratch教程中见过一些3D引擎,找了一个简单的,结果z轴太大了,于是网上一搜,就发现了pyglet 还是先讲如何启动一个窗口 先看看官网: Creating a ...
- centeros 命令
一.查看系统时间.硬件时间 # date // 查看系统时间 #hwclock // 查看硬件时间 二.时间服务器上的时间同步的方法 安装ntpdate工具 # yum -y install ntp ...