使用redis的bitmap實現簽到功能

一、簽到功能的實現思路

最常規的思路,一般我們會選擇每個用戶,每天的簽到作為一條mysql表的數據,然后一條一條的記錄。這種方式的確是可以的,但是它的局限性很大,只能適用于小規模公司的內部系統,人數不多的情況下。
如果是用于普通大眾的話,這就將不堪設想。如果有一百萬用戶,每天簽到,一個月,需要存的數據就會有三千萬條數據,一年,需要存三億六千萬條數據。這要是用戶量再大點,或者使用的時長再長點,這數據是不是就太多了,而且還只是意義不是很大的數據。
常規思路存在的問題:
1.用戶數量多的時候,存在很大的IO性能消耗,對數據庫造成壓力
2.用戶數量多的時候,存儲的數據占用的空間太大
3.用戶數量多,時間久的情況下,查詢統計會性能下降
最近在深入學習redis,發現它里面的bitmap數據結構就能很好的用戶簽到功能的實現,而且簽到數據占用的內存也很小,查詢統計的性能也不錯,很好的解決了常規思路存在的問題。

二、BITMAP介紹

bitmap也叫位圖,可以理解成二進制的bit數組,數組每位只有兩種數字:0或1。
redis中關于bitmap的常用命令有:

#向指定位置(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代碼實現簽到功能

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天,這樣也是可以實現的簽到的,用戶多的時候,產生的數據量也不是很大。個人感覺就是在做相關的統計會比較麻煩。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容