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 ...
随机推荐
- 突破限制,CSS font-variation 可变字体的魅力
今天,在 CodePen 上看到一个很有意思的效果 -- GSAP 3 ETC Variable Font Wave,借助了 JS 动画库 GSAP 实现,一起来看看: 我寻思着能否使用 CSS 复刻 ...
- 如何在3D场景中在模型上面绘制摄取点
有些时候,我们在屏幕上面绘制一个摄取点,在单屏玩游戏的模式下,我们并不能觉得有什么不妥.但是最近VR的热火朝天,我们带上眼镜看双屏的时候,总觉得这个摄取点看着很不舒服. 这个问题该怎么解决?在这里我首 ...
- [Unity] 在软件标题栏显示工作路径
(一)问题 项目开发中常会有开多个分支,同时启动多个 Unity 程序的情况,来回切换的时候就容易混淆,有时候还需要用 Show In Explorer 或者其他标志来确认当前使用的是哪个分支. 于是 ...
- webpack5学习
目录 1. Why Webpack? 2. Webpack上手 2.1 Webpack功能 2.2 需要安装的包 2.3 简易命令 3. Webpack配置文件 3.1 局部webpack打包 3.2 ...
- Keepalived非抢占模式配置
一.前言 HA的实际运行过程中,当主机发生异常,且后期恢复正常后,存在抢占或非抢占两种情况. 结合实际需求,可能有很多用户需要非抢占的HA工作模式.keepalived能够很好的支持这一需求. 二.k ...
- 【基础知识】cache 管线(Pipeline)的建立便可以提升cpu的性能,为什么还要去发展多核的cpu?
多管线 (Pipeline)的确可以提高主频,比如搭配 NetBurs架构的Pentium4,它拥有20级的管线技术,虽然可以轻易提高主频,但是效率会降低.而且随着频率的上升,功率也大幅上升温度问题也 ...
- Qt:打印输出到控制台,类似C++的cout
1. #include<qDebug> 2. qDebug<<"Hello,world!"; 补充,如果不是控制台文件,比如是窗口应用程序,需要在pro文件 ...
- ACM训练,大理石在哪儿?
int p = lower_bound(a, a+num, x) - a; //在已排序数组a中查找大于或等于x的第一个位置 lower_bound( )返回的是一个迭代器,-a相当于减去a的首地址, ...
- LeetCode-048-旋转图像
旋转图像 题目描述:给定一个 n × n 的二维矩阵 matrix 表示一个图像.请你将图像顺时针旋转 90 度. 你必须在 原地 旋转图像,这意味着你需要直接修改输入的二维矩阵.请不要 使用另一个矩 ...
- .NET的两种部署模式,了解一下
前言 以往部署程序一直是习惯性先安装运行时环境,然后再将发布打包好的程序运行起来:但当多个程序依赖不同版本框架平台时,如果部署在同一台机器上,那就需要在同一台机器上安装多个版本的运行时,总感觉有点不太 ...