> 技术文档 > springboot实战篇3demo

springboot实战篇3demo


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){ //根据y用户名查询用户信息 User loginUser = userService.findByUsername(username); //判断用户是否存在 if(loginUser == null){ //不存在 return Result.error(\"用户名错误\"); } //判断密码是否正确,LoginUser对象中的password是密文 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); //把token存储到redis中 ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); operations.set(token,token,6, TimeUnit.HOURS); return Result.success(token); } return Result.error(\"密码错误\"); }

4、在LoginInterceptor类里面:

 //从redis中获得相同的token ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); String redisToken = operations.get(token); if(redisToken == null){  throw new RuntimeException(); }

5、在usercontroller更改密码的模块:

 //删除redis中对应的token ValueOperations<String, String> operations = stringRedisTemplate.opsForValue(); operations.getOperations().delete(token);