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();
    }

 

posted @ 2021-02-25 16:32  生活这把杀猪刀  阅读(789)  评论(1编辑  收藏  举报