public class SessionInterceptor {
@Autowired
private RedisUtils redisUtils;
@Autowired
private UserService userService;
@Pointcut("execution(* com.jajian.demo.web.*.controller.*.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void controllerMethodPointcut() {
}
@Around("controllerMethodPointcut()")
public Object Interceptor(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
Signature signature = proceedingJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method targetMethod = methodSignature.getMethod();
if (targetMethod.getDeclaringClass().isAnnotationPresent(NoLogin.class) || targetMethod.isAnnotationPresent(NoLogin.class)) {
return proceedingJoinPoint.proceed();
}
// 从获取RequestAttributes中获取HttpServletRequest的信息
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
String token = request.getHeader("token");
if(StringUtils.isEmpty(token)){
Log.debug("验证token", "token验证失败,{}", "token不存在");
throw new FieldException(Constants.LOGIN_ERROR_CODE, "login.session.timeout");
}
Integer userId= (Integer)redisUtils.get(CacheConstants.USER_TOKEN_KEY_WEB + token);
if (null == userId) {
Log.debug("验证token", "token验证失败,{}", "token超时");
throw new FieldException(Constants.LOGIN_ERROR_CODE, "login.session.timeout");
}
User user = userService.getById(userId.longValue());
if (ObjectUtils.isEmpty(user)){
Log.debug("验证token", "token验证失败,{}", "用户信息不存在");
throw new FieldException(Constants.LOGIN_ERROR_CODE, "login.session.timeout");
}
if (user.getStatus() == UserStatusEnum.NO.getCode() || user.getDeleteFlag() == DeleteFlagEnum.YES.getCode()){
Log.debug("验证token", "token验证失败,用户信息异常 userName : {}, status : {},deleteFlag : {}", user.getUserName(),user.getStatus(), user.getDeleteFlag());
throw new FieldException(Constants.LOGIN_ERROR_CODE, "login.session.timeout");
}
return proceedingJoinPoint.proceed();
}
}
以上实现方式简单易用,而且Redis 在分布式系统中的使用率也很高,所以无需额外的技术引入。可以支持水平扩展,数据库或缓存水平切分即可,服务端重启或者扩容都不会有session丢失的情况发生。 # v# [4 i- o8 i* R! A0 |0 S+ g 7 D |* }+ k$ Y, F x/ Y% N/ v