极简极速-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
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值