一、概述
在一般性的基设需求中,有需要获取当前用户操作记录的情况,也就是说我们需要记录当前用户的信息。如:id、昵称、账号等信息。
这些信息一般用于记录用户的个人行为,例如:用户的操作日志,记录某些数据的更改或者添加者信息等。
本例主要用于记录更改及添加者信息(操作数据库时)
我希望借助mybatis的默认插件:MetaObjectHandler类实现公共字段的插入和更改,如:创建者、更新者、创建时间、更新时间、删除状态等。
this.strictInsertFill(metaObject, "createUser", Long.class, memberId); this.strictInsertFill(metaObject, "updateUser", Long.class, memberId); this.strictInsertFill(metaObject, "updateTime", Date.class, date); this.strictInsertFill(metaObject, "createTime", Date.class, date); this.strictInsertFill(metaObject, "deleted", Integer.class, 0);
技术:SpringBoot+ThreadLocal+Redis。其中ThreadLocal用于存储当前线程的用户信息,redis用于存储登录用户信息,如:根据token获取用户信息,然后再把用户信息存入ThreadLocl
二、代码示例
1.首先定义一个过滤器,用于获取请求的token,然后根据token获取响应的用户信息,获取到用户信息后把用户信息存储的WebContextHolder中(ps:此类是一个封装了ThreadLocal的类)
@Slf4j @Component @Order(Ordered.HIGHEST_PRECEDENCE + 1) public class WebContextHolderFilter extends GenericFilterBean { @Autowired RedisUtil<AdminUserResponse> redisUtil; @Override @SneakyThrows public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; try { String token = request.getHeader("Authorization"); log.info("token:{}",token); if (token != null&&!"undefined".equals(token)) { AdminUserResponse adminUserResponse = redisUtil.getValue(token); WebContextHolder.setMemberId(adminUserResponse.getUserId()); log.error("用户id:{}", adminUserResponse.getUserId()); } filterChain.doFilter(request, response); } finally { WebContextHolder.clear(); } } }
2.创建一个ThreadLocal用于存储用户id
public class WebContextHolder {private static final ThreadLocal<Long> THREAD_LOCAL_MEMBER = new ThreadLocal<>(); public static void setMemberId(Long memberId) { THREAD_LOCAL_MEMBER.set(memberId); } public static Long getMemberId() { return THREAD_LOCAL_MEMBER.get(); } public static void clear() { THREAD_LOCAL_MEMBER.remove(); } }
3.在MetaObjectHandler类中使用memberId
@Slf4j @Component public class MyBatisMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { Long memberId = WebContextHolder.getMemberId(); log.info("memberId:{}",memberId);//用户id Date date = new Date(); this.strictInsertFill(metaObject, "createUser", Long.class, memberId); this.strictInsertFill(metaObject, "updateUser", Long.class, memberId); this.strictInsertFill(metaObject, "updateTime", Date.class, date); this.strictInsertFill(metaObject, "createTime", Date.class, date); this.strictInsertFill(metaObject, "deleted", Integer.class, 0); } @Override public void updateFill(MetaObject metaObject) { this.strictInsertFill(metaObject, "updateUser", Long.class, WebContextHolder.getMemberId()); this.strictInsertFill(metaObject, "updateTime", Date.class, new Date()); } }
标签:strictInsertFill,metaObject,SpringBoot,public,memberId,id,获取,token,class From: https://www.cnblogs.com/tony-yang-flutter/p/17786631.html