1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| @Service public class SignService {
@Resource private RedisTemplate redisTemplate;
public Map<String, Object> doSign(Integer userId, String dateStr) { Map<String, Object> result = new HashMap<>(); Date date = getDate(dateStr); int day = DateUtil.dayOfMonth(date) - 1; String signKey = buildSignKey(userId, date); boolean isSigned = redisTemplate.opsForValue().getBit(signKey, day); if (isSigned) { result.put("message", "当前日期已完成签到,无需再签"); result.put("code", 400); return result; } redisTemplate.opsForValue().setBit(signKey, day, true); Date today = new Date(); int continuous = getContinuousSignCount(userId, today); long count = getSumSignCount(userId, today); result.put("message", "签到成功"); result.put("code", 200); result.put("continuous", continuous); result.put("count", count); return result; }
private int getContinuousSignCount(Integer userId, Date date) { int dayOfMonth = DateUtil.dayOfMonth(date); String signKey = buildSignKey(userId, date); BitFieldSubCommands bitFieldSubCommands = BitFieldSubCommands.create() .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)) .valueAt(0); List<Long> list = redisTemplate.opsForValue().bitField(signKey, bitFieldSubCommands); if (list == null || list.isEmpty()) { return 0; } int signCount = 0; long v = list.get(0) == null ? 0 : list.get(0); for (int i = dayOfMonth; i > 0; i--) { if (v >> 1 << 1 == v) { if (i != dayOfMonth) break; } else { signCount++; } v >>= 1; } return signCount; }
private Long getSumSignCount(Integer userId, Date date) { String signKey = buildSignKey(userId, date); return (Long) redisTemplate.execute( (RedisCallback<Long>) con -> con.bitCount(signKey.getBytes()) ); }
private Date getDate(String dateStr) { return StrUtil.isBlank(dateStr) ? new Date() : DateUtil.parseDate(dateStr); }
private String buildSignKey(Integer userId, Date date) { return String.format("user:sign:%d:%s", userId, DateUtil.format(date, "yyyyMM")); }
}
|