极简极速-Bitset (bitmap)实现考勤打卡场景

1. redis命令行操作bitmap

在这里插入图片描述

2. RedisTemplate操作bitmap

bitmap的常见业务场景主要有日活统计(类似的月考勤)、点赞、BloomFilter等,以用户mj考勤统计为例,一个用户一个月的打卡记录用不了32bit(4byte)存储空间,性能也很好:

@Resource
private StringRedisTemplate template;

template.opsForValue().setBit("mj",1,true);
template.opsForValue().setBit("mj",2,true);
template.opsForValue().setBit("mj",30,true);       
template.opsForValue().setBit("mj",31,true);
// 查看mj本月第三天是否打卡
Boolean ifArrive= template.opsForValue().getBit("mj", 3);
System.out.println(ifArrive);// false
// 统计本月打卡数
Long count = template.execute((RedisCallback<Long>) connection -> connection.bitCount("mj".getBytes(StandardCharsets.UTF_8), 1, 31));
System.out.println(count); // 4

3. Java中的Bitset

直接使用Java的bitset实现考勤打卡,这里数据集存储DB需要转化,如Bitset#toLongArray(),再转为json进行存储。

 public static void main(String[] args) {
    
    
        // Key一般为userId
        Map<String,BitSet> map=new HashMap(1024);
        BitSet set = map.getOrDefault("mj",new BitSet(32));
        set.set(1,true);
        set.set(2,true);
        set.set(30,true);
        set.set(31,true);
        System.out.println(set.get(3));  //  本月第三天打卡:false
        System.out.println(set.cardinality());// 本地打卡数:4
    }

猜你喜欢

转载自blog.csdn.net/qq_39506978/article/details/132613188
今日推荐