用户签到与统计

用户签到

/**
 * 签到
 * @return
 */
@PostMapping("/sign")
public Result sign(){
return userService.sign();
}

/**
 * 统计本月连续签到天数
 * @return
 */
@GetMapping("/sign/count")
public Result signCount(){
return userService.singCount();
}
/**
 * 签到
 * @return
 */
@Override
public Result sign() {
    // 1.获取当前用户
    UserDTO user = UserHolder.getUser();
    if(user == null){
        return Result.fail("未登录!");
    }
    Long userId = user.getId();
    // 2.获取当前时间
    LocalDateTime now = LocalDateTime.now();
    // 3.拼接key
    String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
    String key = USER_SIGN_KEY + userId + keySuffix;
    // 4.获取今天是本月第几天
    int dayOfMonth = now.getDayOfMonth();
    // 5.写入Redis SETBIT key offset 1
    stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
    return Result.ok();
}

/**
 * 统计本月连续签到天数
 * @return
 */
@Override
public Result singCount() {
    // 1.获取当前用户
    UserDTO user = UserHolder.getUser();
    if(user == null){
        return Result.fail("未登录!");
    }
    Long userId = user.getId();
    // 2.获取当前日期
    LocalDateTime now = LocalDateTime.now();
    // 3.拼接key
    String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
    String key = USER_SIGN_KEY + userId + keySuffix;
    // 4.获取今天是本月第几天
    int dayOfMonth = now.getDayOfMonth();
    // 5.获取截止今天为止的所有签到记录,返回十进制数
    List<Long> result = stringRedisTemplate.opsForValue().bitField(
            key,
            BitFieldSubCommands.create()
                    .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                    .valueAt(0)
    );
    if(result == null || result.isEmpty()){
        return Result.ok(0);
    }
    Long num = result.get(0);
    if(num == null || num == 0){
        return Result.ok(0);
    }
    // 6.得到连续签到天数
    int count = 0;
    while(num > 0){
        if ((num & 1) == 0){
            break;
        }else{
            count ++;
        }
        num >>>= 1;
    }
    // 7.返回
    return Result.ok(count);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值