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_ics_05
题目: 题目描述:其他破坏者会利用工控云管理系统设备维护中心的后门入侵系统 题目场景: 1.进入云平台设备中心界面,查看以下源码发现?page= ,(点下云平台设备维护中心url里也能出?page ...
- 【C# 基础概念】命名空间
命名空间 C#10 新功能==================== 命名空间格式:声明所有后续声明都是已声明的命名空间的成员: //C#10 命名空间的新写法,这种方式一个文件只能有一个命名空间. / ...
- petite-vue源码剖析-从静态视图开始
代码库结构介绍 examples 各种使用示例 scripts 打包发布脚本 tests 测试用例 src directives v-if等内置指令的实现 app.ts createApp函数 blo ...
- Windows端口开启关闭
转至:https://www.cnblogs.com/shenyiyangle/p/10503754.html netstat-a #显示所有活动的TCP连接以及计算机监听的TCP和UDP端口. ne ...
- 如何在shell脚本里使用sftp批量传送文件(二)
原文链接:http://bbs.chinaunix.net/archiver/tid-508290.html 主要步骤如下: 1.为运行shell脚本的本地用户生成密钥对2.将其中的公钥分发到sftp ...
- 关于linux下,ls vi等命令失效的解决方法(配置下环境变量出现问题)
转至:https://www.cnblogs.com/afeiiii/p/13824530.html 配置完环境变量source之后,linux的ls vi命令均失效,报错如下: 解决方法 1.输入 ...
- 使用kind快速搭建本地k8s集群
Kind是什么? k8s集群的组成比较复杂,如果纯手工部署的话易出错且时间成本高.而本文介绍的Kind工具,能够快速的建立起可用的k8s集群,降低初学者的学习门槛. Kind是Kubernetes I ...
- 矩池云上安装yolov5并测试教程
官方仓库:https://github.com/ultralytics/yolov5 官方文档:https://docs.ultralytics.com/quick-start/ 此案例我是租用了k8 ...
- laravel 返回统一的json数据
laravel 在Api接口开发中,可以使用 response()->json(["code"=>200,"msg"=>"ok&qu ...
- tp5文件上传实现缩略图+水印的功能(参考)
public function AddNews(){ $data = Request::instance()->param(); //接收文件 $file = request()->fil ...