Controller
@PostMapping("/login")
public Result<Map<String, Object>> login(@RequestBody User user) {
System.out.println(user);
HashMap<String, Object> map = userService.login(user);
if (map == null) {
return Result.fail(map, "用户名或者密码不对");
}
return Result.success(map, "登陆成功");
}
Service
@Override
public HashMap<String, Object> login(User user) {
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUsername, user.getUsername());
// queryWrapper.eq(User::getPassword, user.getPassword());
User loginUser = userMapper.selectOne(queryWrapper);
// 如果没有用户
if(loginUser == null) {
return null;
}
if(!passwordEncoder.matches(user.getPassword(), loginUser.getPassword())) {
return null;
}
// 生成token
String key = "user:" + UUID.randomUUID();
// 存入redis
loginUser.setPassword(null);
redisTemplate.opsForValue().set(key, loginUser, 30, TimeUnit.MINUTES);
// 返回数据
HashMap<String, Object> map = new HashMap<>();
map.put("token", key);
return map;
}
Redis配置
@Configuration
public class MyRedisConfig {
@Resource
private RedisConnectionFactory factory;
@Bean
public RedisTemplate redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// 为了更好的查看redis key内容,设置一个序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer());
// 为了更好的查看redis value内容,设置一个序列化器
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
redisTemplate.setValueSerializer(serializer);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
om.setTimeZone(TimeZone.getDefault());
om.configure(MapperFeature.USE_ANNOTATIONS, false);
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
serializer.setObjectMapper(om);
return redisTemplate;
}
}