Extremely simple and fast-Bitset (bitmap) realizes attendance and clocking in scenarios

1. Redis command line operation bitmap

Insert image description here

2. RedisTemplate operates bitmap

Common business scenarios of bitmap mainly include daily activity statistics (similar to monthly attendance), likes, BloomFilter, etc. Taking user mj's attendance statistics as an example, a user's check-in record for a month does not require 32bit (4byte) storage space, and the performance is also very good :

@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. Bitset in Java

Directly use Java's bitset to implement attendance and clocking. The data set storage DB here needs to be converted, such as Bitset#toLongArray(), and then converted to json for storage.

 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
    }

Guess you like

Origin blog.csdn.net/qq_39506978/article/details/132613188