springboot下的用户上下文和拦截器
兄弟们,你是否见过,很多项目或者框架中在项目的任何位置,都可以通过上下文或者某些util直接获取贯穿整个请求的对象,比如用户对象,例如在你任意的代码里,直接调用 SecurityUtil.getCurrentUser();就可以得到当前登录的用户信息,简单,快捷,随用随取,那叫一个方便,下面让老王带你一探究竟
其实就是在程序的入口获取到用户信息,并且把用户信息存的ThreadLocal中,废话不多说,直接上代码
用户上下文创建,采用netty中FastThreadLocal来实现,告别内存泄漏,实现快准稳
引入maven依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.66.Final</version>
</dependency>
登录用户上下文
import com.wlc.doc.model.User;
import io.netty.util.concurrent.FastThreadLocal;
/**
*登录用户上下文
*/
public class UserContext {
/**FastThreadLocal快,稳,没内存泄露问题*/
private static FastThreadLocal<User> userHolder = new FastThreadLocal();
/**
*设置用户到 FastThreadLocal
*/
public static void setUser(User loginUser) {
userHolder.set(loginUser);
}
/**
*从FastThreadLocal中获取用户
*/
public static User getUser() {
return userHolder.get();
}
/**
*清除FastThreadLocal,反之内存泄露
*/
public static void remove() {
userHolder.remove();
}
}
登录token拦截器阉割版
import com.wlc.doc.annotation.IgnoreAuth;
import com.wlc.doc.http.constant.HttpCode;
import com.wlc.doc.interceptor.token.JwtUtil;
import com.wlc.doc.interceptor.token.TokenUser;
import com.wlc.doc.interceptor.token.UserContext;
import com.wlc.doc.model.User;
import com.wlc.doc.http.response.Result;
import com.wlc.doc.http.response.ResultBuilder;
import com.wlc.doc.util.BeanCopierUtil;
import com.wlc.doc.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* 登录token拦截器
* @author IT学习道场
* @create 2019-08-24 15:35
*/
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
private static final String TOKEN = "token";
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if("OPTIONS".equals(request.getMethod().toUpperCase())) {
System.out.println("Method:OPTIONS");
return true;
}
if (!(handler instanceof HandlerMethod)) {
return true;
}
String token = request.getHeader(TOKEN);
// 从参数中获取token
if (ObjectUtils.isEmpty(token)) {
token = request.getParameter(TOKEN);
}
//获取用户信息的问题
if (!ObjectUtils.isEmpty(token)){
User loginUser = getUser(request, response, token);
UserContext.setUser(loginUser);
}
return super.preHandle(request, response, handler);
}
//拦截器的后置处理器
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//手动清除当前用户上下文的用户对象
UserContext.remove();
}
private User getUser(HttpServletRequest request, HttpServletResponse response, String token) {
// 然后根据token获取用户登录信息,
TokenUser tokenUser = JwtUtil.decodeToken(token);
User loginUser = BeanCopierUtil.copyProperties(tokenUser, User.class);
// 如果这里校验用户信息失败,则直接抛出异常
return loginUser;
}
}
拦截器注册到拦截器容器中使之生效
import com.wlc.doc.interceptor.AccessLimitInterceptor;
import com.wlc.doc.interceptor.LoginInterceptor;
import com.wlc.doc.interceptor.token.LoginUserArgumentResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* mvc拦截器配置类
* @author IT学习道场
* @create 2019-08-24 15:35
*/
@Configuration
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**");
}
}
流程:request --> loginInterceptor --> preHandle --> token获取并且解析出用户信息 --> set到UserContext的FastThreadLocal中,获取,用UserContext的get就行,不存在内存泄漏问题,FastThreadLocal后端会有定时器自动清理,不需要操心,或者为了最好的安全起见,可以在后置处理中进行FastThreadLocal的清理
作者:IT学习道场
欢迎关注微信公众号 : IT学习道场