Redis的练习:
1.在pom类中导入依赖:
<!--redis坐标--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.在application.yml类中:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/big_event username: root password: 1234 data: redis: host: localhost port: 6379
3、在UserController里面的登录模块里 :
@PostMapping(\"/login\") public Result login(@Pattern(regexp = \"^\\\\S{5,16}$\") String username, @Pattern(regexp = \"^\\\\S{5,16}$\") String password){ User loginUser = userService.findByUsername(username); if(loginUser == null){ return Result.error(\"用户名错误\"); } if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){ Map<String,Object> claims = new HashMap<>(); claims.put(\"id\",loginUser.getId()); claims.put(\"username\",loginUser.getUsername()); String token = JwtUtil.genToken(claims); ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); operations.set(token,token,6, TimeUnit.HOURS); return Result.success(token); } return Result.error(\"密码错误\"); }
4、在LoginInterceptor类里面:
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); String redisToken = operations.get(token); if(redisToken == null){ throw new RuntimeException(); }
5、在usercontroller更改密码的模块:
ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); operations.getOperations().delete(token);