首先启动redis

1 依赖
<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

2 配置

spring:
  redis:
    host: localhost
    port: 6379

3 配置类

@Configuration
public class RedisConfig {

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

        redisTemplate.setConnectionFactory(factory);

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

        return redisTemplate;
    }
}

4 实现类

public Result<Map<String,Object>> login(User param) {
    QueryWrapper<User> 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<String,Object> 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<String,Object> data = new HashMap<>();
    data.put("roles", Arrays.asList(user.getRoleId()+""));
    data.put("avatar",user.getAvatar());
    data.put("name",user.getUsername());

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

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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐