# 使用redis的bitmap实现签到功能

**URL:** <https://www.shiqidu.com/t/topic/867>\
**Category:** 开发调优\
**Tags:** Redis\
**Created:** [2025 年11 月 6 日 15:49 UTC](https://www.shiqidu.com/t/topic/867 "2025-11-06T15:49:34Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![shiqidu\_editor](https://www.shiqidu.com/user_avatar/www.shiqidu.com/shiqidu_editor/32/528_2.png) [@shiqidu\_editor](https://www.shiqidu.com/u/shiqidu_editor)\
发布日期： [2025 年11 月 6 日 15:49 UTC](https://www.shiqidu.com/t/topic/867/1 "2025-11-06T15:49:34Z")

</div>

# 一、签到功能的实现思路

**最常规的思路** ，一般我们会选择每个用户，每天的签到作为一条mysql表的数据，然后一条一条的记录。这种方式的确是可以的，但是它的局限性很大，只能适用于小规模公司的内部系统，人数不多的情况下。  
如果是用于普通大众的话，这就将不堪设想。如果有一百万用户，每天签到，一个月，需要存的数据就会有三千万条数据，一年，需要存三亿六千万条数据。这要是用户量再大点，或者使用的时长再长点，这数据是不是就太多了，而且还只是意义不是很大的数据。  
**常规思路存在的问题：**  
1.用户数量多的时候，存在很大的IO性能消耗，对数据库造成压力  
2.用户数量多的时候，存储的数据占用的空间太大  
3.用户数量多，时间久的情况下，查询统计会性能下降  
最近在深入学习redis，发现它里面的bitmap数据结构就能很好的用户签到功能的实现，而且签到数据占用的内存也很小，查询统计的性能也不错，很好的解决了常规思路存在的问题。

# 二、BITMAP介绍

bitmap也叫位图，可以理解成二进制的bit数组，数组每位只有两种数字：0或1。  
redis中关于bitmap的常用命令有：

```bash
#向指定位置（offset）存入0或1
SETBIT key offset value

#获取指定位置（offset）的bit值
GETBIT key offset

#统计bitmap中(从start到end，如果不写起始位置，就统计整个key)值为1的bit数量
BITCOUNT key [start end]

#操作（查询，修改，自增）Bitmap中指定的位置（offset）的值
BITFIELD key [GET type offset] [SET type offset value] [INCRBY type offset increment] [OVERFLOW WRAP|SAT|FAIL]

#获取Bitmap中的bit数组，并以十进制返回
BITFIELD_RO

```

# 三、java代码实现签到功能

```kotlin
package com.mumu.controller;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * @author 
 * @date 2022-06-05 下午2:28
 * @description：
 */
@RestController
@RequestMapping("/sign")
public class SignController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 当日签到
     *
     * @return
     */
    @PostMapping("/do")
    public String doSign() {
        //用户Uid
        String userId = "1234";
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 组合成key= sign:userId:年月
        String key = "sign:" + userId + keySuffix;
        // 获取当前日期是当月的第多少天
        int dayOfMonth = now.getDayOfMonth();
        // 存到redis中的bitmap中，由于bitmap从0开始，第多少天从1开始，dayOfMonth需要减1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return "ok";
    }

    /**
     * 指定日期补签
     *
     * @return
     */
    @PostMapping("/doSign")
    public String doSupplementarySignature(@RequestParam String signDate) {
        String userId = "1234";
        LocalDateTime dateOfSign = StringParseLocalDateTime(signDate);
        String keySuffix = dateOfSign.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + keySuffix;
        int dayOfMonth = dateOfSign.getDayOfMonth();
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return "ok";
    }

    /**
     * 统计指定月的用户总共签到次数
     * date：年月日
     * @return
     */
    @GetMapping("/count")
    public Integer getSignCount(@RequestParam String date) {
        String userId = "1234";
        LocalDateTime dateOfSign = StringParseLocalDateTime(date);
        String keySuffix = dateOfSign.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = "sign:" + userId + keySuffix;
        Long count = stringRedisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.bitCount(key.getBytes());
            }
        });
        assert count != null;
        return count.intValue();
    }

    /**
     * 统计当前日期往前的连续签到数（连续的）
     *
     * @return
     */
    @GetMapping("/signCount")
    public Integer signCount() {
        //用户Uid
        String userId = "1234";
        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        // 组合成key= sign:userId:年月
        String key = "sign:" + userId + keySuffix;
        // 获取当前日期是当月的第多少天
        int dayOfMonth = now.getDayOfMonth();
        // 获取本月截止今天为止的所有签到记录，返回的是一个十进制的数字
        List<Long> result = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));

        if (result == null || result.isEmpty()) {
            return 0;
        }
        Long number = result.get(0);
        int count = 0;
        if (number == null || number == 0) {
            return 0;
        }
        while (true) {
            // 让这个数字与1做与运算，得到数字的最后一位bit，并判断这个bit是否为0
            if ((number & 1) == 0) {
                // 如果为0说明不是连续签到，直接终止
                break;
            } else {
                // 如果不为0，那就为1，说明有签到，继续下次循环，并且计数器加一
                count++;
            }
            // 把数字右移一位，抛弃最后一位的bit，继续下一个bit
            number = number >>> 1; // 也可以写成 number >>>= 1
        }
        return count;
    }

    /**
     * 字符串日期转换成LocalDateTime
     *
     * @param date
     * @return
     * @throws ParseException
     */
    private LocalDateTime StringParseLocalDateTime(String date) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            Date parse = simpleDateFormat.parse(date);
            Instant instant = parse.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            return instant.atZone(zoneId).toLocalDateTime();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式转换报错");
        }
    }

}

```

# 四、思考

其实可以借鉴redis的这种bitmap思想，我们可以设计一张mysql的签到表，字段有：用户id，年份，一月，二月，三月，四月，五月，六月，七月，八月，九月，十月，十一月，十二月。这些字段，月份字段里面存0和1组成的字符串，代表是否签到，字符串最长31位，代表当月一共31天，这样也是可以实现的签到的，用户多的时候，产生的数据量也不是很大。个人感觉就是在做相关的统计会比较麻烦。

> 本文转自 [https://www.jianshu.com/p/ca4ad11d1f9a](https://www.jianshu.com/p/ca4ad11d1f9a)，如有侵权，请联系删除。
