token+Redis实现登录与退出登录

token+Redis实现登录与退出登录

application.properties配置文件添加Sql、Redis配置信息

#MySQL配置
spring.datasource.url=jdbc:mysql://localhost:3306/【数据库】?useUnicode=true&autoReconnect=true&failOverReadOnly=false&zeroDateTimeBehavior=round&autoReconnect=true&serverTimezone=GMT
spring.datasource.username=【数据库账号】
spring.datasource.password=【数据库密码】

#Redis配置
spring.redis.host=【服务器地址】
spring.redis.password=【Redis密码】
spring.redis.port=6379【Redis默认端口】

Controller接受请求判断登录账号密码 生成Token并存入Redis

@RequestMapping(method = RequestMethod.POST)
@ApiOperation(value = “登录”)
public ResponseEntity login(@RequestParam String username, @RequestParam String password) {
//此处判断传进来的值是否为空 可用if判断
Assert.notNull(username, “username can not be empty”);
Assert.notNull(password, “password can not be empty”);

    User user = 调用查询用户方法;
    if (user == null ||  //未注册
            !user.getPassword().equals(password)) {  //密码错误
        //提示用户名或密码错误
        return new ResponseEntity<>(ApiRspDto.error(ResultStatus.USERNAME_OR_PASSWORD_ERROR), HttpStatus.NOT_FOUND);
    }


    //这里生成一个token 调用token工具类
   //TokenModel model = tokenManager.createToken(user.getId());
    public TokenModel createToken(long userId) {
    //使用uuid作为源token
    String token = UUID.randomUUID().toString().replace("-", "");
    TokenModel model = new TokenModel(userId, token);
    //存储到redis并设置过期时间
    redis.boundValueOps(userId).set(token, Constants.TOKEN_EXPIRES_HOUR【一般设置为72小时】, TimeUnit.HOURS);
    return model;
}  
   

    return new ResponseEntity<>(ApiRspDto.ok(model), HttpStatus.OK);
}

退出登录——删除Redis

@RequestMapping(method = RequestMethod.DELETE)
@Authorization
@ApiOperation(value = "退出登录")
@ApiImplicitParams({
@ApiImplicitParam(name = "authorization", value = "authorization", required = true, dataType = "string", paramType = "header"),
})
public ResponseEntity logout(@CurrentUser User user) {
	//删除Redis存储的Token
    tokenManager.deleteToken(user.getId());【redis.delete(userId);】
    return new ResponseEntity<>(ApiRspDto.ok(), HttpStatus.OK);
}

本文章仅用作于萌新存储代码知识点 如有问题可进行回复讨论 欢迎大佬指导

你可能感兴趣的:(redis,java)