SpringBoot中的ThreadLocal保存請求用戶信息的實例demo
更新時間:2024年05月30日 09:39:35 作者:奮--斗
線程局部變量,創(chuàng)建一個線程變量后,針對這個變量可以讓每個線程擁有自己的變量副本,每個線程是訪問的自己的副本,與其他線程的相互獨立,本文介紹SpringBoot中的ThreadLocal保存請求用戶信息,需要的朋友可以參考下
一、ThreadLocal概述
線程局部變量,創(chuàng)建一個線程變量后,針對這個變量可以讓每個線程擁有自己的變量副本,每個線程是訪問的自己的副本,與其他線程的相互獨立。
二、具體代碼demo實現
(1)創(chuàng)建user實例對象
@Data
public class UserDTO {
private Long userId;
private String UserName;
}(2)創(chuàng)建UserThreadLocal對象
public class UserThreadLocal {
private UserThreadLocal(){};
private static final ThreadLocal<UserDTO> USER_DTO_THREAD_LOCAL = new ThreadLocal<>();
/**
* 清除信息
*/
public static void clear(){
USER_DTO_THREAD_LOCAL.remove();
}
/**
* 保存用戶信息
* @param userDTO
*/
public static void set(UserDTO userDTO){
USER_DTO_THREAD_LOCAL.set(userDTO);
}
public static UserDTO getCurrentUser(){
return USER_DTO_THREAD_LOCAL.get();
}
}(3)創(chuàng)建用戶攔截器
@Component
public class UserInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//此處實際應該根據header的token解析出用戶本處為了簡單,直接虛構一個用戶
UserDTO userDTo = new UserDTO();
userDTo.setUserId(10001L);
userDTo.setUserName("張三");
UserThreadLocal.set(userDTo);
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserThreadLocal.clear();
}
}(4) 注冊用戶攔截器
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new UserInterceptor());
}
}(5)編寫測試接口
@RequestMapping("test")
@RestController
public class TestController {
@GetMapping("get")
public UserDTO getUser(){
UserDTO currentUser = UserThreadLocal.getCurrentUser();
System.out.println(currentUser);
return currentUser;
}
}(6)效果展示

到此這篇關于SpringBoot之ThreadLocal保存請求用戶信息的文章就介紹到這了,更多相關SpringBoot ThreadLocal保存請求用戶信息內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- springboot在filter中如何用threadlocal存放用戶身份信息
- springboot登錄攔截器+ThreadLocal實現用戶信息存儲的實例代碼
- SpringBoot ThreadLocal 簡單介紹及使用詳解
- SpringBoot+ThreadLocal+AbstractRoutingDataSource實現動態(tài)切換數據源
- Springboot公共字段填充及ThreadLocal模塊改進方案
- SpringBoot ThreadLocal實現公共字段自動填充案例講解
- SpringBoot通過ThreadLocal實現登錄攔截詳解流程
- springboot 使用ThreadLocal的實例代碼
- SpringBoot中使用?ThreadLocal?進行多線程上下文管理及注意事項小結

