分布式Session
实现方式
-
Session复制
配置tomcat,使得不同tomcat之间共享session
-
Session粘滞
利用nginx等代理工具使得某一客户端交互过程中只使用一台服务器
-
前端储存
用户信息储存到前端
-
后端集中存储
Redis储存用户信息
配置Redis
Redis配置文件
redis:
# 主机号
host: 127.0.0.1
#端口
port: 6379
#数据库
database: 0
#超时时间
timeout: 1000ms
lettuce:
pool:
#最大连接数
max-active: 8
#最大阻塞等待时间
max-wait: 10000ms
#最大空闲连接
max-idle: 200
#最小空闲连接
min-idle: 5
Redis配置类
@Configuration
public class RedisConfig {
@Bean(name = "myRedisTemplate")
public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
//key序列化
template.setKeySerializer(new StringRedisSerializer());
//value序列化
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
//hash序列化
template.setHashKeySerializer(new StringRedisSerializer());
//hash序列化
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(factory);
return template;
}
}
WebMvcConfigurer预处理参数
分布式Session每次业务流程都要代码进行验证user,代码里昂过于繁重。导入WebMvcConfigurer提前处理参数直接传入controller
WebConfig
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Resource
private UserArgumentResolver userArgumentResolver;
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
resolvers.add(userArgumentResolver);
}
}
UserArgumentResolver
主要验证业务
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
@Resource
private IUserService userService;
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
Class<?> clazz = methodParameter.getParameterType();
return clazz== User.class;
}
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
String userTicket = CookieUtil.getCookieValue(request, "userTicket");
if (StringUtils.isEmpty(userTicket)) {
return "null";
}
return userService.getByUserTicket(userTicket, request, response);
}
}