ThreadLocal优化

测试类证明一下ThreadLocal存储的数据是线程程安全的

java 复制代码
    package com.lin.springboot01;

    import org.junit.jupiter.api.Test;

    public class testThreadLocal {
        @Test
        public void testThreadLocalSetAndGet(){
            //提供一个ThreadLocal对象
            ThreadLocal t1 = new ThreadLocal();
            new Thread(()->{
                t1.set("张三");
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
            },"绿色").start();

            new Thread(()->{
                t1.set("李四");
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
                System.out.println(Thread.currentThread().getName()+":"+t1.get());
            },"黄色").start();
        }

    }

接上一篇获取用户详细信息,用ThreadLocal进行优化

ThreadLocalUtil:工具类

java 复制代码
package com.lin.springboot01.utils;

public class ThreadLocalUtil {
    //提供ThreadLocal对象
    private static final ThreadLocal THREAD_LOCAL = new ThreadLocal();

    //根据键获取值
    public static <T> 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();
    }
}

LoginInterceptor:ThreadLocalUtil.set(claims)将数据存储到ThreadLocal中

java 复制代码
package com.lin.springboot01.interceptors;

import com.lin.springboot01.pojo.Result;
import com.lin.springboot01.utils.JwtUtil;
import com.lin.springboot01.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) {
            //解析失败,httpServletResponse响应码设置为401
            response.setStatus(401);
            return false;
        }
    }

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

UserController:改用ThreadLocalUtil获取用户name,在把参数传给findByName方法

java 复制代码
    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name="Authorization") String token*/){
       /* Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByName(username);
        return Result.success(user);
    }
相关推荐
王桑.17 分钟前
IO流高级流--转换流
java
2301_7951672025 分钟前
Python 高手编程系列八:缓存
开发语言·python·缓存
8***293135 分钟前
Go基础之环境搭建
开发语言·后端·golang
qq_124987075340 分钟前
基于SpringBoot技术的企业请假审批管理系统的设计与实现(源码+论文+部署+安装)
java·spring boot·后端·信息可视化·毕业设计
Yue丶越1 小时前
【C语言】自定义类型:联合体与枚举
c语言·开发语言
BBB努力学习程序设计1 小时前
Java方法详解:提升代码复用性与可读性的利器
java
BBB努力学习程序设计1 小时前
Java运算符完全指南:让代码学会“计算”和“判断”
java
q***73551 小时前
SpringBoot中使用TraceId进行日志追踪
spring boot·后端·状态模式
csbysj20201 小时前
DOM 节点
开发语言
用户84913717547162 小时前
ThreadLocal 源码深度解析:JDK 设计者的“妥协”与“智慧”
java·后端