当前位置:网站首页>ThreadLocal保存用户登录信息
ThreadLocal保存用户登录信息
2022-08-01 14:05:00 【独酌先生QAQ】
目录结构:

1.编写注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Target 用于描述注解的使用范围 ElementType.METHOD 用于描述方法 ElementType.TYPE 用于描述类、接口(包括注解类型) 或enum声明
* @Retention 定义被它所注解的注解保留多久
* source:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;被编译器忽略
* class:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期
* runtime:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExposeUserInfo {
}2.编写类user,ThreadLocal存放user类
import lombok.Data;
@Data
public class User {
String id;
String name;
}
public class UserContext {
private static ThreadLocal<User> threadLocal = new ThreadLocal<>();
public static void set(User user) {
threadLocal.set(user);
}
public static User get() {
return threadLocal.get();
}
public static void remove(){
threadLocal.remove();
}
}3.编写切面
import com.example.aopannotation.threadlocal.User;
import com.example.aopannotation.threadlocal.UserContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
public class UserInfoAspect {
public Logger logger = LoggerFactory.getLogger(UserInfoAspect.class);
/**
* 切点放在注解上,通过注解实现aop切面
*/
@Pointcut("@annotation(com.example.aopannotation.annotation.ExposeUserInfo)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
User user = new User();
//1.从请求头获取用户的信息
HttpServletRequest request = null;
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
request = requestAttributes.getRequest();
// 2.获取用户的id
String id = request.getHeader("id");
//此处可以查库,得到user对象的其他信息
user.setId(id);
UserContext.set(user);
try {
// 3.设置用户上下文
UserContext.set(user);
// 执行并返回
return joinPoint.proceed();
} catch (Throwable throwable) {
throw throwable;
} finally {
// 4.移除(防止内存泄漏)
UserContext.remove();
}
}
}4.编写controller
import com.example.aopannotation.annotation.ExposeUserInfo;
import com.example.aopannotation.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class ExposeController {
@Autowired
UserInfoService userInfoService;
@ExposeUserInfo
@PostMapping("/userinfo")
public String test() {
return userInfoService.getUserInfo();
}
}5.编写service
import com.example.aopannotation.threadlocal.User;
import com.example.aopannotation.threadlocal.UserContext;
import org.springframework.stereotype.Service;
@Service
public class UserInfoService {
public String getUserInfo(){
User user= UserContext.get();
return user.getId();
}
}
6.postman请求

边栏推荐
- PAT 1167 Cartesian Tree(30)
- 8. How does the SAP ABAP OData service support the Create operation
- 使用ffmpeg来查看视频的信息,fps,和width,height
- D - I Hate Non-integer Number(背包dp)
- kubernetes之DaemonSet以及滚动更新
- [LiteratureReview]Optimal and Robust Category-level Perception: Object Pose and Shape Estimation f
- VIP的实现原理
- The basic knowledge of scripting language Lua summary
- D - Draw Your Cards(模拟)
- 免费使用高性能的GPU和TPU—谷歌Colab使用教程
猜你喜欢

A Beginner's Guide to Performance Testing

龙口联合化学通过注册:年营收5.5亿 李秀梅控制92.5%股权

HTB-Shocker

170页6万字智慧能源管理平台建设方案书

Koreographer Professional Edition丨一款Unity音游插件教程

openEuler 社区12位开发者荣获年度开源贡献之星

JMP Pro 16.0 software installation package download and installation tutorial

postgresql之page分配管理(一)

Programmer's Romantic Tanabata

HTB-Shocker
随机推荐
经纬信息IPO过会:年营收3.5亿 叶肖华控制46.3%股权
MBI5020 LED驱动
OpenSSL SSL_read: Connection was reset, errno 10054
性能优化——粒子优化笔记
【码蹄集新手村600题】判断一个数字是否为完全平方数
Performance Optimization - Resource Optimization Notes
HTB-Shocker
快速理解拉格朗日乘子法
Efficiency tools to let programmers get off work earlier
E - Red and Blue Graph (Combinatorics)
iPhone难卖,被欧洲反垄断的服务业务也难赚钱了,苹果的日子艰难
Longkou united chemical registration: through 550 million revenue xiu-mei li control 92.5% stake
Yann LeCun开怼谷歌研究:目标传播早就有了,你们创新在哪里?
A Beginner's Guide to Performance Testing
【无标题】
长江欧拉生态创新中心成立,武汉数字经济再添坚实底座
有限合伙人与普通合伙人的区别
牛客刷SQL--4
十九届浙大城院程序设计竞赛 F.Sum of Numerators(数学/找规律)
直播系统聊天技术(八):vivo直播系统中IM消息模块的架构实践