使用Redis实现登录验证功能
首先启动redis1 依赖<!-- redis --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><depe
·
首先启动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); }
更多推荐
已为社区贡献3条内容
所有评论(0)