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.233G
高下立判,无需多言。
那么,问题来了,如何表示一个数呢?
刚才说了,每一位表示一个数,0表示不存在,1表示存在,这正符合二进制
这样我们可以很容易表示{1,2,4,6}这几个数:
计算机内存分配的最小单位是字节,也就是8位,那如果要表示{12,13,15}怎么办呢?
当然是在另一个8位上表示了:
方法正确但是难以落地实现。
签到用户量较小时怎么设计都行,但是用户体量大(估算3000w签到用户),一天一条数据,一个月就是9亿数据了,如果一条签到记录对应当日用记录,那么数据量就恐怖了
如何解决这个痛点?
1 一条签到记录对应一条记录,会占据越来越大的空间。
2 一个月最多31天,刚好我们的int类型是32位,那这样一 个int类型就可以搞定一个月,32位大于31天,当天来了位是1没来就是0。.
3 一条数据直接存储-一个月的签到记录,不再是存储一 天的签到记录。
Redis提供了以下几个命令用于操作位图:
Java BitMap:
@ComponentScanpublic class RedisUtils {@Autowiredprivate RedisTemplate redisTemplate;//--------------BitMap命令----------/*** 基于Redis位图的用户签到功能实现类* 实现功能:* 1. 用户签到* 2. 检查用户是否签到* 3. 获取用户签到次数* 4. 获取用户连续签到次数* 5. 获取用户每天的签到情况*//*** 用户签到* 指令:SETBIT** @param userId 用户Id* @param date 日期* @return*/public boolean doSign(Long userId, LocalDate date) {int offSet = date.getDayOfMonth() - 1;return redisTemplate.opsForValue().setBit(buildUserKey(userId, date), offSet, true);}/*** 检查用户某天是否签到* 指令:GETBIT** @param userId 用户id* @param date 当前签到状态* @return*/public boolean checkSign(Long userId, LocalDate date) {int offSet = date.getDayOfMonth() - 1;return redisTemplate.opsForValue().getBit(buildUserKey(userId, date), offSet);}/*** 通过日期获取用户签到次数* 指令:BITCOUNT** @param userId 用户id* @param date 时间* @return*/public long getSigCount(Long userId, LocalDate date) {return (long) redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(buildUserKey(userId, date).getBytes(StandardCharsets.UTF_8)));}// public long getContinuousSingCount(Long userId,LocalDate date){// int singCount=0;// String type = String.format("u%d", date.getDayOfMonth());//// redisTemplate.execute((RedisCallback<List<Long>>)con-> con.bitField(buildUserKey(userId,date)))//////// }/*** 获取到返回值后判断用户当月连续签到次数** @param userId* @param date* @return*/public long getContinuousSignCount(Long userId, LocalDate date) {int signCount = 0;String type = String.format("u%d", date.getDayOfMonth());List<Long> lists = bitfield(buildUserKey(userId, date), date.getDayOfMonth(), 0);if (lists != null && lists.size() > 0) {//取低位连续不为0的个数即为连续签到的次数,需考虑当天尚未签到的情况long val = lists.get(0) == null ? 0 : lists.get(0);for (int i = 0; i < date.getDayOfMonth(); i++) {if (val >> 1 << 1 == val) { //先右移再左边移,如果相同低位为0//低位为0且非当天说明连续签到中断了if (i > 0) break;} else {signCount += 1;}val >>= 1;}}return signCount;}public Map<String, Boolean> getSignInfo(Long userId, LocalDate date) {HashMap<String, Boolean> signMap = new HashMap<>();String type = String.format("u%d", date.lengthOfMonth());List<Long> lists = bitfield(buildUserKey(userId, date), date.lengthOfMonth(), 0);if (lists != null && lists.size() > 0) {long val = lists.get(0) == null ? 0 : lists.get(0);//由低位到高位,为0表示未签到 为1表示已签到for (int i = 0; i < date.lengthOfMonth(); i++) {LocalDate localDate = date.withDayOfMonth(i);signMap.put(formatDate(localDate, "yyyy-MM-dd"), val >> 1 << 1 != val);val >>= 1;}}return signMap;}/*** 获取当月首次签到日期** @param userId 用户ID* @param date 日期* @return 首次签到日期*/public LocalDate getFirstSignDate(Long userId, LocalDate date) {// redisTemplate.opsForValue().bitField()return date;}/*** 执行:BITFIELD命令** @param buildSignKey* @param limit* @param offset* @return*/public List<Long> bitfield(String buildSignKey, int limit, int offset) {return (List<Long>) redisTemplate.execute((RedisCallback<List<Long>>) con ->con.bitField(buildSignKey.getBytes(StandardCharsets.UTF_8), BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(limit)).valueAt(offset)));}public static String buildUserKey(Long userId, LocalDate date) {return String.format("userId:%d:%s", userId, formatDate(date));}private static String formatDate(LocalDate date, String pattern) {return date.format(DateTimeFormatter.ofPattern(pattern));}private static String formatDate(LocalDate date) {return formatDate(date, "yyyyMM");}/*** 统计出现次数** @param string 目标字符串* @param sub 目标子字符串* @return*/public static int countMatched(String string, String sub) {//判空,为空直接返回0,表示不存在if (StringUtil.isNullOrEmpty(string)) {return 0;}int count = 0;int index;// 循环一次将出现的字符串索引向后移一位,计数器+1,并截取原字符串索引+1的字符串,// 如“abcdeeeee”第一次循环找到“e”索引4,substring(4+1)方法截取后得到新的字符串“eeee”,// 循环第二次找到“e”的索引0,substring(0+1)方法截取后得到新的字符串“eee”,,,以此类推while ((index = string.indexOf(sub)) > -1) {count++;string = string.substring(index + 1);}return count;}}
