BitMap:

Bit-map的基本思想就是用一个bit位来标记某个元素对应的Value,而Key即是该元素。由于采用了Bit为单位来存储数据,因此在存储空间方面,可以大大节省。(PS:划重点 节省存储空间)
假设有这样一个需求:在20亿个随机整数中找出某个数m是否存在其中,并假设32位操作系统,4G内存
在Java中,int占4字节,1字节=8位(1 byte = 8 bit)
如果每个数字用int存储,那就是20亿个int,因而占用的空间约为 (20000000004/1024/1024/1024)≈7.45G
如果按位存储就不一样了,20亿个数就是20亿位,占用空间约为 (2000000000/8/1024/1024/1024)≈*0.233
G
高下立判,无需多言。

那么,问题来了,如何表示一个数呢?
刚才说了,每一位表示一个数,0表示不存在,1表示存在,这正符合二进制
这样我们可以很容易表示{1,2,4,6}这几个数:
image.png

计算机内存分配的最小单位是字节,也就是8位,那如果要表示{12,13,15}怎么办呢?
当然是在另一个8位上表示了:
image.png

方法正确但是难以落地实现。
签到用户量较小时怎么设计都行,但是用户体量大(估算3000w签到用户),一天一条数据,一个月就是9亿数据了,如果一条签到记录对应当日用记录,那么数据量就恐怖了

如何解决这个痛点?

1 一条签到记录对应一条记录,会占据越来越大的空间。
2 一个月最多31天,刚好我们的int类型是32位,那这样一 个int类型就可以搞定一个月,32位大于31天,当天来了位是1没来就是0。.
3 一条数据直接存储-一个月的签到记录,不再是存储一 天的签到记录。

Redis提供了以下几个命令用于操作位图:

Java BitMap:

  1. @ComponentScan
  2. public class RedisUtils {
  3. @Autowired
  4. private RedisTemplate redisTemplate;
  5. //--------------BitMap命令----------
  6. /**
  7. * 基于Redis位图的用户签到功能实现类
  8. * 实现功能:
  9. * 1. 用户签到
  10. * 2. 检查用户是否签到
  11. * 3. 获取用户签到次数
  12. * 4. 获取用户连续签到次数
  13. * 5. 获取用户每天的签到情况
  14. */
  15. /**
  16. * 用户签到
  17. * 指令:SETBIT
  18. *
  19. * @param userId 用户Id
  20. * @param date 日期
  21. * @return
  22. */
  23. public boolean doSign(Long userId, LocalDate date) {
  24. int offSet = date.getDayOfMonth() - 1;
  25. return redisTemplate.opsForValue().setBit(buildUserKey(userId, date), offSet, true);
  26. }
  27. /**
  28. * 检查用户某天是否签到
  29. * 指令:GETBIT
  30. *
  31. * @param userId 用户id
  32. * @param date 当前签到状态
  33. * @return
  34. */
  35. public boolean checkSign(Long userId, LocalDate date) {
  36. int offSet = date.getDayOfMonth() - 1;
  37. return redisTemplate.opsForValue().getBit(buildUserKey(userId, date), offSet);
  38. }
  39. /**
  40. * 通过日期获取用户签到次数
  41. * 指令:BITCOUNT
  42. *
  43. * @param userId 用户id
  44. * @param date 时间
  45. * @return
  46. */
  47. public long getSigCount(Long userId, LocalDate date) {
  48. return (long) redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(buildUserKey(userId, date).getBytes(StandardCharsets.UTF_8)));
  49. }
  50. // public long getContinuousSingCount(Long userId,LocalDate date){
  51. // int singCount=0;
  52. // String type = String.format("u%d", date.getDayOfMonth());
  53. //
  54. // redisTemplate.execute((RedisCallback<List<Long>>)con-> con.bitField(buildUserKey(userId,date)))
  55. //
  56. //
  57. //
  58. // }
  59. /**
  60. * 获取到返回值后判断用户当月连续签到次数
  61. *
  62. * @param userId
  63. * @param date
  64. * @return
  65. */
  66. public long getContinuousSignCount(Long userId, LocalDate date) {
  67. int signCount = 0;
  68. String type = String.format("u%d", date.getDayOfMonth());
  69. List<Long> lists = bitfield(buildUserKey(userId, date), date.getDayOfMonth(), 0);
  70. if (lists != null && lists.size() > 0) {
  71. //取低位连续不为0的个数即为连续签到的次数,需考虑当天尚未签到的情况
  72. long val = lists.get(0) == null ? 0 : lists.get(0);
  73. for (int i = 0; i < date.getDayOfMonth(); i++) {
  74. if (val >> 1 << 1 == val) { //先右移再左边移,如果相同低位为0
  75. //低位为0且非当天说明连续签到中断了
  76. if (i > 0) break;
  77. } else {
  78. signCount += 1;
  79. }
  80. val >>= 1;
  81. }
  82. }
  83. return signCount;
  84. }
  85. public Map<String, Boolean> getSignInfo(Long userId, LocalDate date) {
  86. HashMap<String, Boolean> signMap = new HashMap<>();
  87. String type = String.format("u%d", date.lengthOfMonth());
  88. List<Long> lists = bitfield(buildUserKey(userId, date), date.lengthOfMonth(), 0);
  89. if (lists != null && lists.size() > 0) {
  90. long val = lists.get(0) == null ? 0 : lists.get(0);
  91. //由低位到高位,为0表示未签到 为1表示已签到
  92. for (int i = 0; i < date.lengthOfMonth(); i++) {
  93. LocalDate localDate = date.withDayOfMonth(i);
  94. signMap.put(formatDate(localDate, "yyyy-MM-dd"), val >> 1 << 1 != val);
  95. val >>= 1;
  96. }
  97. }
  98. return signMap;
  99. }
  100. /**
  101. * 获取当月首次签到日期
  102. *
  103. * @param userId 用户ID
  104. * @param date 日期
  105. * @return 首次签到日期
  106. */
  107. public LocalDate getFirstSignDate(Long userId, LocalDate date) {
  108. // redisTemplate.opsForValue().bitField()
  109. return date;
  110. }
  111. /**
  112. * 执行:BITFIELD命令
  113. *
  114. * @param buildSignKey
  115. * @param limit
  116. * @param offset
  117. * @return
  118. */
  119. public List<Long> bitfield(String buildSignKey, int limit, int offset) {
  120. return (List<Long>) redisTemplate.execute((RedisCallback<List<Long>>) con ->
  121. con.bitField(buildSignKey.getBytes(StandardCharsets.UTF_8), BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(limit)).valueAt(offset)));
  122. }
  123. public static String buildUserKey(Long userId, LocalDate date) {
  124. return String.format("userId:%d:%s", userId, formatDate(date));
  125. }
  126. private static String formatDate(LocalDate date, String pattern) {
  127. return date.format(DateTimeFormatter.ofPattern(pattern));
  128. }
  129. private static String formatDate(LocalDate date) {
  130. return formatDate(date, "yyyyMM");
  131. }
  132. /**
  133. * 统计出现次数
  134. *
  135. * @param string 目标字符串
  136. * @param sub 目标子字符串
  137. * @return
  138. */
  139. public static int countMatched(String string, String sub) {
  140. //判空,为空直接返回0,表示不存在
  141. if (StringUtil.isNullOrEmpty(string)) {
  142. return 0;
  143. }
  144. int count = 0;
  145. int index;
  146. // 循环一次将出现的字符串索引向后移一位,计数器+1,并截取原字符串索引+1的字符串,
  147. // 如“abcdeeeee”第一次循环找到“e”索引4,substring(4+1)方法截取后得到新的字符串“eeee”,
  148. // 循环第二次找到“e”的索引0,substring(0+1)方法截取后得到新的字符串“eee”,,,以此类推
  149. while ((index = string.indexOf(sub)) > -1) {
  150. count++;
  151. string = string.substring(index + 1);
  152. }
  153. return count;
  154. }
  155. }