redis-bitmap使用场景

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");
        // 操作 Bitmap
        bitSet.set(0, true);  // 设置第 0 位为 1
        bitSet.set(1, false); // 设置第 1 位为 0
        bitSet.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);

        // 未设置的默认false
        boolean 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上每位代表一个用户,如果重复登陆,则是重复对某位设置,不会影响结果。

布隆过滤器

复制代码
相关推荐
小北方城市网19 小时前
分布式锁实战指南:从选型到落地,避开 90% 的坑
java·数据库·redis·分布式·python·缓存
ohoy20 小时前
RedisTemplate 使用之Zset
java·开发语言·redis
冰冰菜的扣jio1 天前
Redis缓存中三大问题——穿透、击穿、雪崩
java·redis·缓存
阿里巴巴P8资深技术专家1 天前
基于 Spring AI 和 Redis 向量库的智能对话系统实践
人工智能·redis·spring
oMcLin1 天前
如何在 AlmaLinux 9 上配置并优化 Redis 集群,支持高并发的实时数据缓存与快速查询?
数据库·redis·缓存
洛阳纸贵1 天前
Redis
数据库·redis·缓存
挺6的还1 天前
13.持久化
redis
沙白猿1 天前
Redis报错:A bean with that name has already been defined in class path resource
spring boot·redis·mybatis
IT 行者1 天前
Spring Security 7 OAuth2 授权码分布式存储之Redis存储方案
redis·分布式·spring
花~盗1 天前
redis笔记
redis