- ThreadLocal提供线程的局部变量(set和get方法)
- 线程之间互不影响
//测试类
package com.di.bigevent;
import org.junit.jupiter.api.Test;
public class ThreadLocalTest {
@Test
public void testThreadLocalSetAndGet(){
ThreadLocal tl = new ThreadLocal();
new Thread(()->{
tl.set("李星云");
System.out.println(Thread.currentThread().getName()+": "+ tl.get());
},"蓝色").start();
new Thread(()->{
tl.set("袁天罡");
System.out.println(Thread.currentThread().getName()+": "+ tl.get());
},"绿色").start();
}
}
//拦截器类
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();
}
}
//Controller
@GetMapping("userInfo")
public Result<Object> 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.findByUserName(username);
return Result.success(user);
}
//util
package com.di.bigevent.utils;
/**
* ThreadLocal 工具类
*/
@SuppressWarnings("all")
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();
}
}
标签:13,set,String,get,##,2024,ThreadLocal,import,public
From: https://www.cnblogs.com/muzhaodi/p/18071466