ThreadLocal使用,配合拦截器HandlerInterceptor使用

2024-03-11 09:28

本文主要是介绍ThreadLocal使用,配合拦截器HandlerInterceptor使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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 {@AutowiredDemoThreadLocalService 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 {@Overridepublic void demoThreadLocalUserId() {// 获取当前idLong currentId = BaseContext.getCurrentId();log.info("当前id为:{}", currentId);// 使用完后移出BaseContext.removeCurrentId(currentId);}
}

在这里插入图片描述

配合拦截器使用

第一步:配置拦截器

  1. 新建interceptor包和TokenUserInterceptor类,实现HandlerInterceptor;并交给spring管理。

  2. 实现public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception方法。

  3. 我是将token放在header中的,当然也可以放在cookies中。

    • 在这里插入图片描述
  4. 判断当前token是否为空,如果为空返回false,不往下执行。

  5. 做到这步还没结束,因为这样写还不会生效。

  6. 新建config包,创建WebMvcConfiguration 并实现WebMvcConfigurationSupport

@Component
@Slf4j
public class TokenUserInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 设置userIdString 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 {@AutowiredTokenUserInterceptor 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,通过拦截器获取header中token。这一层并不需要做什么,只是为了写一个接口让MVC拦截。

@RestController
@RequestMapping("/test")
@Tag(name = "测试设置ThreadLocal")
@Slf4j
public class DemoThreadLocal {@AutowiredDemoThreadLocalService demoThreadLocalService;@Operation(summary = "拦截器中设置UserId", description = "测试方法")@GetMapping("userId")public String userId() {demoThreadLocalService.demoThreadLocalUserId();return "userId";}
}

第四步:查看内容

service和上面一样。

@Service
@Slf4j
public class DemoThreadLocalServiceImpl implements DemoThreadLocalService {@Overridepublic void demoThreadLocalUserId() {// 获取当前idLong currentId = BaseContext.getCurrentId();log.info("当前id为:{}", currentId);// 使用完后移出BaseContext.removeCurrentId(currentId);}
}
emoThreadLocalUserId() {// 获取当前idLong currentId = BaseContext.getCurrentId();log.info("当前id为:{}", currentId);// 使用完后移出BaseContext.removeCurrentId(currentId);}
}

这篇关于ThreadLocal使用,配合拦截器HandlerInterceptor使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/797399

相关文章

python中的显式声明类型参数使用方式

《python中的显式声明类型参数使用方式》文章探讨了Python3.10+版本中类型注解的使用,指出FastAPI官方示例强调显式声明参数类型,通过|操作符替代Union/Optional,可提升代... 目录背景python函数显式声明的类型汇总基本类型集合类型Optional and Union(py

Java使用正则提取字符串中的内容的详细步骤

《Java使用正则提取字符串中的内容的详细步骤》:本文主要介绍Java中使用正则表达式提取字符串内容的方法,通过Pattern和Matcher类实现,涵盖编译正则、查找匹配、分组捕获、数字与邮箱提... 目录1. 基础流程2. 关键方法说明3. 常见场景示例场景1:提取所有数字场景2:提取邮箱地址4. 高级

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I

使用Java读取本地文件并转换为MultipartFile对象的方法

《使用Java读取本地文件并转换为MultipartFile对象的方法》在许多JavaWeb应用中,我们经常会遇到将本地文件上传至服务器或其他系统的需求,在这种场景下,MultipartFile对象非... 目录1. 基本需求2. 自定义 MultipartFile 类3. 实现代码4. 代码解析5. 自定

使用Python实现无损放大图片功能

《使用Python实现无损放大图片功能》本文介绍了如何使用Python的Pillow库进行无损图片放大,区分了JPEG和PNG格式在放大过程中的特点,并给出了示例代码,JPEG格式可能受压缩影响,需先... 目录一、什么是无损放大?二、实现方法步骤1:读取图片步骤2:无损放大图片步骤3:保存图片三、示php

使用Python实现一个简易计算器的新手指南

《使用Python实现一个简易计算器的新手指南》计算器是编程入门的经典项目,它涵盖了变量、输入输出、条件判断等核心编程概念,通过这个小项目,可以快速掌握Python的基础语法,并为后续更复杂的项目打下... 目录准备工作基础概念解析分步实现计算器第一步:获取用户输入第二步:实现基本运算第三步:显示计算结果进

AOP编程的基本概念与idea编辑器的配合体验过程

《AOP编程的基本概念与idea编辑器的配合体验过程》文章简要介绍了AOP基础概念,包括Before/Around通知、PointCut切入点、Advice通知体、JoinPoint连接点等,说明它们... 目录BeforeAroundAdvise — 通知PointCut — 切入点Acpect — 切面

python之uv使用详解

《python之uv使用详解》文章介绍uv在Ubuntu上用于Python项目管理,涵盖安装、初始化、依赖管理、运行调试及Docker应用,强调CI中使用--locked确保依赖一致性... 目录安装与更新standalonepip 安装创建php以及初始化项目依赖管理uv run直接在命令行运行pytho

C#使用Spire.XLS快速生成多表格Excel文件

《C#使用Spire.XLS快速生成多表格Excel文件》在日常开发中,我们经常需要将业务数据导出为结构清晰的Excel文件,本文将手把手教你使用Spire.XLS这个强大的.NET组件,只需几行C#... 目录一、Spire.XLS核心优势清单1.1 性能碾压:从3秒到0.5秒的质变1.2 批量操作的优雅

Kotlin 枚举类使用举例

《Kotlin枚举类使用举例》枚举类(EnumClasses)是Kotlin中用于定义固定集合值的特殊类,它表示一组命名的常量,每个枚举常量都是该类的单例实例,接下来通过本文给大家介绍Kotl... 目录一、编程枚举类核心概念二、基础语法与特性1. 基本定义2. 带参数的枚举3. 实现接口4. 内置属性三、