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 ...
随机推荐
- 使用Flask开发简单接口
作为测试人员,在工作或者学习的过程中,有时会没有可以调用的现成的接口,导致我们的代码没法调试跑通的情况. 这时,我们使用python中的web框架Flask就可以很方便的编写简单的接口,用于调用或调试 ...
- 防世界之Web_NewsCenter
题目: 打开实验环境一看,就一个搜索框,emmm试下有没有SQL注入点,SQL注入步骤传送门https://www.cnblogs.com/shacker/p/15917173.html 爆出数据, ...
- Python 中线程和进程
目录 线程和进程 一. 什么是进程 / 线程 1. 引论 2. 线程 3. 进程 4. 区别 5. 使用 二. 多线程使用 1. 常用方法 2. 常用参数 3. 多线程的应用 3.1 重写线程法 3. ...
- [题解]Mail.Ru Cup 2018 Round 1 - B. Appending Mex
[题目] B. Appending Mex [描述] Ildar定义了一种方法,可以由一个数组产生一个数.具体地,从这个数组中任选一个子集,不在这个子集中的最小的非负整数称为mex,就是由这个数组得到 ...
- C语言字符串输入输出函数(gets()函数、puts()函数、fgets()函数、fputs()函数)
scanf("%s", str) 不能读取空白字符,遇到第一个空白字符就停止读取. gets(str) 读取整行输入,直至遇到换行符,丢弃换行符储存其余字符,并在末尾添加 \0.与 ...
- 【C# 线程】线程局部存储(TLS) 实战部分 ThreadStatic|LocalDataStoreSlot|ThreadLocal<T>
往袋子里面装苹果 错误案例示范 关于C#多线程的文章,大部分都在讨论线程的起停或者是多线程同步问题.多线程同步就是在不同线程中访问同一个变量(一般是线程工作函数外部的变量),众所周知在不使用线程同步的 ...
- ceph 问题总结已解决
waiting for a volume to be created, either by external provisioner "ceph.com/rbd" or manua ...
- Python:Scrapy(二) 实例分析与总结、写一个爬虫的一般步骤
学习自:Scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250 - 知乎 Python Scrapy 爬虫框架实例(一) - Blue·Sky - 博客园 1.声明Item 爬虫爬取的目标是从非 ...
- tensorflow源码解析之common_runtime-direct_session
目录 核心概念 direct_session direct_session.h direct_session.cc 1. 核心概念 读过之前文章的读者应该还记得,session是一个执行代理.我们把计 ...
- 背包四讲 (AcWing算法基础课笔记整理)
背包四讲 背包问题(Knapsack problem)是一种组合优化的NP完全问题.问题可以描述为:给定一组物品,每种物品都有自己的重量和价格,在限定的总重量内,我们如何选择,才能使得物品的总价格最高 ...