1.20

一.今天做了什么
利用多线程优化代码
package com.di.bigevent.interceptors;

import com.di.bigevent.utils.JwtUtil;
import com.di.bigevent.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    //令牌验证
    String token = request.getHeader("Authorization");

    try{
        Map<String,Object> claims = JwtUtil.parseToken(token);

        //把业务数据存放到ThreadLocal中
        ThreadLocalUtil.set(claims);
        //放行
        return true;
    }
    catch(Exception e){
        response.setStatus(401);
        //不放行
        return false;
    }
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    //清空ThreadLocal中的数据
    ThreadLocalUtil.remove();
}

}
package com.di.bigevent.utils;

/**

  • ThreadLocal 工具类
    */
    @SuppressWarnings("all")
    public class ThreadLocalUtil {
    //提供ThreadLocal对象,
    private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();

    //根据键获取值
    public static T get(){
    return (T) THREAD_LOCAL.get();
    }

    //存储键值对
    public static void set(Object value){
    THREAD_LOCAL.set(value);
    }

    //清除ThreadLocal 防止内存泄漏
    public static void remove(){
    THREAD_LOCAL.remove();
    }
    }

posted @ 2024-03-01 13:41  chrisrmas、  阅读(3)  评论(0编辑  收藏  举报