用户签到
/**
* 签到
* @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);
}