一、自定义类 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报错问题的更多相关文章

  1. Springboot数据库连接池报错的解决办法

    Springboot数据库连接池报错的解决办法 这个异常通常在Linux服务器上会发生,原因是Linux系统会主动断开一个长时间没有通信的连接 那么我们的问题就是:数据库连接池长时间处于间歇状态,导致 ...

  2. CodeIgniter 3.0+ 部署linux环境 session报错

    codeigniter Message: mkdir(): Invalid path Filename: drivers/Session_files_driver.php 看起来像权限问题,在默认情况 ...

  3. Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans

    Springboot 启动文件报错,原因是@ComponentScan写成了@ComponentScans

  4. 【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 ...

  5. 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 ...

  6. 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 创建 ...

  7. Springboot整合Elasticsearch报错availableProcessors is already set to [4], rejecting [4]

    Springboot整合Elasticsearch报错 今天使用SpringBoot整合Elasticsearch时候,相关的配置完成后,启动项目就报错了. nested exception is j ...

  8. SpringBoot集成MybatisPlus报错

    SpringBoot集成MybatisPlus报错 启动的时候总是报如下错误: java.lang.annotation.AnnotationFormatError: Invalid default: ...

  9. Springboot 之 启动报错-Cannot determine embedded database driver class for database type NONE

    Springboot 之 启动报错-数据库 springboot项目在启动时,报如下错误: Error starting ApplicationContext. To display the auto ...

随机推荐

  1. [数分笔记]Dedekind切割定理的证明

    1.定理内容 Dedekind切割定理:设是实数集的一个切割,则或者有最大数,或者有最小数. 2.证明过程 设是中所有有理数所构成的集合,是中所有有理数所构成的集合 从而构成一个有理数集的切割 有三种 ...

  2. Centos7 增加swap分区的内存大小

    Centos7 增加swap分区的内存大小 对 swap 空间的适当大小实际上取决于您的个人偏好和您的应用程序要求.通常,等于或双倍于系统内存的量是一个很好的选择 添加swap分区使用dd命令创建/h ...

  3. 超强可视化图表工具:Smartbi!!

    要制作出专业的可视化图表,还是需要一定的学习成本的,并且需要大量的时间.并且即使是制作出来,配色也是一大难题,对于一般人而言,通常会通过两种方式实现可视化大屏的制作: 1.写代码 大部分人可能会选择大 ...

  4. c# 编程学习(四)

    逻辑AND(逻辑与)操作符(用&&表示)和逻辑OR(逻辑或) 操作符(用||表示).这两个操作符统称条件逻辑操作符.只有作为操作数的两个布尔表达式都为 true.操作符&&am ...

  5. kyverno VS gateKeeper

    kyverno VS gateKeeper 概述 这两组开源工具都是是基于kubernetes 的webhook机制,支持validatingwebhook和mutatingwebhook.整体思路上 ...

  6. mysql集群--基于centos7

    1 MySQL主从备份 主机:192.168.43.8 从机:192.168.43.6 条件:主机和从机都安装了mysql,开启了二进制日志 安装mysql (mysql 和 mysql-server ...

  7. docker入门-Dockerfile入门

    1.dockerfile 构建基础命令 2. 构建镜像命令 Usage: docker image build [OPTIONS] PATH | URL | -Options:-t, --tag li ...

  8. JZ-045-扑克牌顺子

    扑克牌顺子 题目描述 LL今天心情特别好,因为他去买了一副扑克牌,发现里面居然有2个大王,2个小王(一副牌原本是54张_)...他随机从中抽出了5张牌,想测测自己的手气,看看能不能抽到顺子,如果抽到的 ...

  9. MaRVIN

    [ResourceRegistration] 加给Resource类 [ResourceReference(--)] 加给Resource类中引动到的Resource类,引用多个的话用IReferen ...

  10. laravel7 h-ui模板点改

    1:html页面 <td> @if($item->fang_status == 0) <span onclick="changeFangStatus(this,{{$ ...