網站首頁 編程語言 正文
ThreadLocal使用,配合攔截器HandlerInterceptor使用
ThreadLocal
的使用場景通常涉及多線程環境下需要為每個線程保留獨立狀態的情況。它提供了一種簡單的方式來管理線程本地變量,使得每個線程都可以獨立地訪問和修改自己的變量副本,而不會影響其他線程的副本。
包括的方法
ThreadLocal
的主要方法包括:
-
get()
:獲取當前線程的變量副本。 -
set(value)
:設置當前線程的變量副本為給定的值。 -
remove()
:移除當前線程的變量副本。
項目中創建
定義BaseContext
類,分別設置獲取當前內容、設置當前內容、移出當前內容。
public class BaseContext {
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static Long getCurrentId() {
return threadLocal.get();
}
public static void setCurrentId(Long currentId) {
threadLocal.set(currentId);
}
public static void removeCurrentId(Long id) {
threadLocal.remove();
}
}
需要注意的是,
ThreadLocal
使用完畢后應該及時調用remove()
方法來清除當前線程的變量副本,以避免內存泄漏問題。另外,由于ThreadLocal
使用了線程封閉的設計思想,因此在使用時應當謹慎考慮其適用性,并避免濫用。
在項目中簡單使用
在發送請求時,攜帶id,最后在service層獲取。
@RestController
@RequestMapping("/test")
@Tag(name = "測試設置ThreadLocal")
@Slf4j
public class DemoThreadLocal {
@Autowired
DemoThreadLocalService demoThreadLocalService;
@Operation(summary = "設置userID", description = "測試方法")
@GetMapping("userId={id}")
public String setUserId(@PathVariable Long id) {
BaseContext.setCurrentId(id);
demoThreadLocalService.demoThreadLocalUserId();
return "userId";
}
}
service接口。
public interface DemoThreadLocalService {
void demoThreadLocalUserId();
}
service實現類中獲取id。
@Service
@Slf4j
public class DemoThreadLocalServiceImpl implements DemoThreadLocalService {
@Override
public void demoThreadLocalUserId() {
// 獲取當前id
Long currentId = BaseContext.getCurrentId();
log.info("當前id為:{}", currentId);
// 使用完后移出
BaseContext.removeCurrentId(currentId);
}
}
配合攔截器使用
第一步:配置攔截器
-
新建
interceptor
包和TokenUserInterceptor
類,實現HandlerInterceptor
;并交給spring管理。 -
實現
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
方法。 -
我是將token放在header中的,當然也可以放在cookies中。
-
判斷當前token是否為空,如果為空返回false,不往下執行。
-
做到這步還沒結束,因為這樣寫還不會生效。
-
新建
config
包,創建WebMvcConfiguration
并實現WebMvcConfigurationSupport
@Component
@Slf4j
public class TokenUserInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 設置userId
String token = request.getHeader("token");
System.out.println("--------------" + token + "--------------");
if (token != null && !token.isEmpty()) {
BaseContext.setCurrentId(Long.valueOf(token));
return true;
} else {
return false;
}
}
}
第二步:配置MVC設置
匹配路徑
WebMvcConfiguration內容如下。配置攔截器這樣才會生效。需要攔截/test
下所有請求,如圖所示,攔截器識別不了通配符所以要使用addPathPatterns
去匹配。
其中的方式是:protected void addInterceptors(InterceptorRegistry registry)
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Autowired
TokenUserInterceptor tokenUserInterceptor;
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(tokenUserInterceptor).addPathPatterns("/test/**");
}
}
需要注意的是,當前只是傳入一個也可以傳入多個。當匹配后即可實現攔截效果,檢測header中是否包含token。
示例,為了演示效果就隨便寫了下。
protected void addInterceptors(InterceptorRegistry registry) {
String[] list = {};
registry.addInterceptor(tokenUserInterceptor)
.addPathPatterns("/test/**").addPathPatterns("/test2").addPathPatterns("/test3")
.addPathPatterns("asa", "sas","sas")
.addPathPatterns(list);
}
在knif4j中測試,成功輸出。
排出路徑
排出哪些路徑是不需要攔截的。
protected void addInterceptors(InterceptorRegistry registry) {
String[] list = {};
registry.addInterceptor(tokenUserInterceptor)
.addPathPatterns("/test/**").excludePathPatterns("/test2").excludePathPatterns("/test3")
.excludePathPatterns("asa", "sas", "sas")
.excludePathPatterns(list);
}
第三步:Controller層中
controller層,在路徑中不傳入id,通過攔截器獲取heade
r中token
。這一層并不需要做什么,只是為了寫一個接口讓MVC攔截。
@RestController
@RequestMapping("/test")
@Tag(name = "測試設置ThreadLocal")
@Slf4j
public class DemoThreadLocal {
@Autowired
DemoThreadLocalService demoThreadLocalService;
@Operation(summary = "攔截器中設置UserId", description = "測試方法")
@GetMapping("userId")
public String userId() {
demoThreadLocalService.demoThreadLocalUserId();
return "userId";
}
}
第四步:查看內容
service和上面一樣。
@Service
@Slf4j
public class DemoThreadLocalServiceImpl implements DemoThreadLocalService {
@Override
public void demoThreadLocalUserId() {
// 獲取當前id
Long currentId = BaseContext.getCurrentId();
log.info("當前id為:{}", currentId);
// 使用完后移出
BaseContext.removeCurrentId(currentId);
}
}
emoThreadLocalUserId() {
// 獲取當前id
Long currentId = BaseContext.getCurrentId();
log.info("當前id為:{}", currentId);
// 使用完后移出
BaseContext.removeCurrentId(currentId);
}
}
原文鏈接:https://blog.csdn.net/weixin_46533577/article/details/136608293
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-06-18 Python實現兩種稀疏矩陣的最小二乘法_python
- 2022-08-13 uni-app發送請求封裝
- 2023-01-03 Android?自定義Livedata使用示例解析_Android
- 2023-05-06 react中定義變量并使用方式_React
- 2022-12-11 React?state狀態屬性用法講解_React
- 2022-07-15 C#中字符串與字節數組的轉換方式_C#教程
- 2023-03-04 Golang設計模式之組合模式講解_Golang
- 2022-06-16 詳解Flutter中網絡框架dio的二次封裝_Android
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支