1.web:
监听session:HttpSessionListener接口 sessionDestroyed方法
获取session失效时保存的用户(在token里)
保存失效信息 WebApplicationContextUtils.getWebApplicationContext(session.getServletContext()).getBean(SysUserDao.class);
2.app:
监听redis失效key:KeyExpirationEventMessageListener类 onMessage方法
创建新redis用来保存失效key里面的value和其他信息
redis里面如果用户调用新接口则重置失效时间,新建redis也要重置:新建拦截器:HandlerInterceptor
保存失效信息
拦截器:
@Override
public boolean preHandle(@NonNull HttpServletRequest request,
@NonNull HttpServletResponse response,
@NonNull Object handler){
// log.info(“AppInterceptor>>preHandle(),requestURL={}”,request.getRequestURL());
String token = request.getParameter(“token”);
// log.info(“token={}”, token);
if (StringUtils.isNotBlank(token)) {
Object userId = redisTemplate.opsForValue().get(token);
//有操作时把token重置为1小时过期
redisTemplate.opsForValue().set(token, userId, 1, TimeUnit.HOURS);//保存userId
redisTemplate.opsForValue().set(RedisKey.getUserAppIp(token), userId + “,” + IpUtils.getRealIp(request), 2, TimeUnit.HOURS);//改为2小时过期,有操作时会重置时间,保存userId和ip
if (Objects.nonNull(userId)) {
try {
Object json = redisTemplate.opsForValue().get(RedisKey.getUserKey(Long.parseLong(userId.toString())));
if (Objects.nonNull(json)) {
SysUser user = jacksonObjectMapper.readValue(json.toString(), SysUser.class);
request.setAttribute(“user”, user);
return true;
}
} catch (JsonProcessingException e) {
log.error(e.getMessage(), e);
}
}
}
try{
response.setStatus(200);
response.setHeader(“Content-Type”,“text/plain;charset=utf-8”);
ReturnObject returnObject=new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_FALSE,“用户未登陆”);
String result=jacksonObjectMapper.writeValueAsString(returnObject);
response.getWriter().write(result);
}catch (Exception e){
log.error(e.getMessage());
}
return false;
}
@Configuration
public class MVCConfigurer implements WebMvcConfigurer {
@Resource
private RedisTemplate<String,Object> redisTemplate;
@Resource
private ObjectMapper jacksonObjectMapper;
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false)
.setUseTrailingSlashMatch(true);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
//registry.addInterceptor(vrAPPInterceptor()).addPathPatterns("/app/**").excludePathPatterns("/app/userCenter/getValidCode");
registry.addInterceptor(new ManageInterceptor()).addPathPatterns("/manage/**");
registry.addInterceptor(new AppInterceptor(jacksonObjectMapper, redisTemplate)).addPathPatterns("/app/**").excludePathPatterns("/app/login", "/app/versionupdate/getAppVersion");
}
//注册session监听器
@Bean
public ServletListenerRegistrationBean<SessionListener> servletListenerRegistrationBean() {
ServletListenerRegistrationBean<SessionListener> slrBean = new ServletListenerRegistrationBean<SessionListener>();
slrBean.setListener(new SessionListener());
return slrBean;
}
}