广铁建设集团门户网站长沙网络推广软件
bitmap原理
Bitmap(位图)是一种基于二进制位的数据结构,用于高效地存储和操作大量的布尔值
可以对单个位进行读写操作
demo
package org.example;import org.redisson.Redisson;
import org.redisson.api.RBitSet;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;public class BitmapTest {private static final RedissonClient redisson;static {Config config = new Config();config.useSingleServer().setAddress("redis://******.redis.rds.aliyuncs.com:6379").setUsername("******").setPassword("*******");redisson = Redisson.create(config);}public static void main(String[] args) {// 获取 Bitmap 对象RBitSet bitSet = redisson.getBitSet("myBitMap");// 操作 BitmapbitSet.set(0, true); // 设置第 0 位为 1bitSet.set(1, false); // 设置第 1 位为 0bitSet.set(20, 30, true); // 设置第 20 到 29 位为 1// 获取位的值boolean bitValue = bitSet.get(0);System.out.println("Bit at position 0: " + bitValue);boolean bit1Value = bitSet.get(1);System.out.println("Bit at position 1: " + bit1Value);// 未设置的默认falseboolean bit100Value = bitSet.get(100);System.out.println("Bit at position 100: " + bit100Value);// 统计所有为1的个数long count = bitSet.cardinality(); System.out.println("Number of bits set to 1: " + count);获取 Bitmap 的长度long size = bitSet.size();System.out.println("Bitmap size: " + size);// 关闭 Redisson 客户端redisson.shutdown();}}
Bitmap 的长度是动态扩展的
未设置的位默认为 0
使用场景
用户签到
统计活跃用户
统计每天使用系统的用户总数,bitmap上每位代表一个用户,如果重复登陆,则是重复对某位设置,不会影响结果。