使用Redis实现登录验证功能

首先启动redis

1 依赖


    org.springframework.boot
    spring-boot-starter-data-redis


    org.apache.commons
    commons-pool2

2 配置

spring:
  redis:
    host: localhost
    port: 6379

3 配置类

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory){
        RedisTemplate redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(factory);

        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class));

        return redisTemplate;
    }
} 
  

4 实现类

public Result> login(User param) {
    QueryWrapper wrapper = new QueryWrapper<>();
    wrapper.eq("username",param.getUsername());
    wrapper.eq("password",param.getPassword());
    User user = this.baseMapper.selectOne(wrapper);

    if(user == null){
        return Result.fail(20002,"用户名或密码错误");
    }

    // 登录成功,将用户信息写入redis
    String key = "user:"+UUID.randomUUID()+"";
    user.setPassword(null);
    redisTemplate.opsForValue().set(key,user,60L, TimeUnit.MINUTES);
    Map data = new HashMap<>();
    data.put("token", token);

    return Result.success(data);
}
public Result getUserInfoByToken(String token) {
// 通过token从redis中获取登录用户信息
    Object obj = redisTemplate.opsForValue().get(token);
    if(obj == null){
        return Result.fail(20003,"登录凭证无效,请重新登录");
    }
    log.debug("--------> obj: " + obj);
    log.debug("--------> obj to json: " + JSON.toJSONString(obj));
    User user = JSON.parseObject(JSON.toJSONString(obj),User.class);
    
    Map data = new HashMap<>();
    data.put("roles", Arrays.asList(user.getRoleId()+""));
    data.put("avatar",user.getAvatar());
    data.put("name",user.getUsername());

    // 根据角色id查询菜单权限列表
    List menuList = menuService.getMenuTreeByRoleId(user.getRoleId());
    data.put("menuList",menuList);

    return Result.success(data);
}
public void logout(String token) {
    redisTemplate.delete(token);
}

你可能感兴趣的:(java,spring,maven,idea,数据库开发)