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
| @Service public class BitmapCheckInService { @Autowired private StringRedisTemplate redisTemplate;
public boolean checkIn(Long userId) { LocalDate today = LocalDate.now(); int day = today.getDayOfMonth(); String key = buildSignKey(userId, today); Boolean isSigned = redisTemplate.opsForValue().getBit(key, day - 1); if (isSigned != null && isSigned) { return false; } redisTemplate.opsForValue().setBit(key, day - 1, true); redisTemplate.expire(key, 100, TimeUnit.DAYS); updateContinuousSignDays(userId); return true; }
private void updateContinuousSignDays(Long userId) { LocalDate today = LocalDate.now(); String continuousKey = "user:sign:continuous:" + userId; boolean yesterdayChecked = isSignedIn(userId, today.minusDays(1)); if (yesterdayChecked) { redisTemplate.opsForValue().increment(continuousKey); } else { redisTemplate.opsForValue().set(continuousKey, "1"); } }
public boolean isSignedIn(Long userId, LocalDate date) { int day = date.getDayOfMonth(); String key = buildSignKey(userId, date); Boolean isSigned = redisTemplate.opsForValue().getBit(key, day - 1); return isSigned != null && isSigned; }
public int getContinuousSignDays(Long userId) { String continuousKey = "user:sign:continuous:" + userId; String value = redisTemplate.opsForValue().get(continuousKey); return value != null ? Integer.parseInt(value) : 0; }
public long getMonthSignCount(Long userId, LocalDate date) { String key = buildSignKey(userId, date); int dayOfMonth = date.lengthOfMonth(); return redisTemplate.execute((RedisCallback<Long>) con -> { return con.bitCount(key.getBytes()); }); }
public List<Integer> getMonthSignData(Long userId, LocalDate date) { List<Integer> result = new ArrayList<>(); String key = buildSignKey(userId, date); int dayOfMonth = date.lengthOfMonth(); for (int i = 0; i < dayOfMonth; i++) { Boolean isSigned = redisTemplate.opsForValue().getBit(key, i); result.add(isSigned != null && isSigned ? 1 : 0); } return result; }
public int getFirstSignDay(Long userId, LocalDate date) { String key = buildSignKey(userId, date); int dayOfMonth = date.lengthOfMonth(); for (int i = 0; i < dayOfMonth; i++) { Boolean isSigned = redisTemplate.opsForValue().getBit(key, i); if (isSigned != null && isSigned) { return i + 1; } } return -1; }
private String buildSignKey(Long userId, LocalDate date) { return String.format("user:sign:%d:%d%02d", userId, date.getYear(), date.getMonthValue()); } }
|