统计用户本月的连续登录天数

记录用户的连续登录天数

  • 访问量:10W+、100W+

技术栈

  • Redis的bitmap: 100w+的日活用户时
  • Redis的sortedSet:10W+的日活用户时
  • Mysql: 10W的日活用户时

简述

  • bitmap:每个月最多31天,即31bit,每一位表示第N天是否登录的状态:0-未登录/1-已登录
  • setbit uid1:2025:6 25 1 (表示uid为1的用户在2025年6月份的25号登录)
  • getbit uid1:2025:6 25 (获取uid为1的用户2025年6月份25号是否登录)
  • bitcount uid1:2025:6 (获取uid为1的用户2025年6月份的登录天数)
  • 要获取当前连续登录的天数则需要代码实现,redis不能直接获取
  • sortedSet,ZADD添加时将当前日期当成score记录,获取时通过ZRangeByScore获取完整的数据,后端做连续登录天数的判断。

代码实现:python

python 复制代码
import redis, calendar
from datetime import datetime,date
re = redis.Redis(host='127.0.0.1', port=6379, db=0)
# 获取指定年月的最大天数
def getDays(year, month):
    max_days = calendar.monthrange(year, month)[1]
    print("%d年%d月份的最大天数为: %d" % (year, month,  max_days))
    return max_days
# 签到初始化
def init(uid, year, month, day):
    key = 'sign:%d:%d:%d' % (uid, year, month)
    if re.exists(key) == 0: # 首次签到时初始化
        maxDays = getDays(year, month)
        for i in range(1, maxDays+1):
            re.setbit(key, i, 0)
            print('初始化' , key, i)
    re.setbit(key, day, 1)  

# 统计本次签到的连续签到次数
def static(uid, year, month, day):
    cc = 0
    key = 'sign:%d:%d:%d' % (uid, year, month)
    for i in range(1, day+1):
        res = re.getbit(key, i)
        if res == 0:
            cc = 0
        else:
            cc += 1
    return cc         
# 用户本月的总的签到次数
def getAll(uid, year, month):
    key = 'sign:%d:%d:%d' % (uid, year, month)
    return re.bitcount(key) 

try:
    today = str(date.today())
    year, month, day = list(map(int, today.split('-')))
    uid = 1
    init(uid, year, month, day)
    # cc = re.bitcount('uid1') # 统计签到的总次数
    cc  = static(uid, year, month, day)
    all = getAll(uid, year, month) 
    print('uid:%d 本次连续签到的次数为:%d, %d 月份的签到次数为:%d' % (uid, cc, month, all))
except Exception as e:
    print(f"连接失败: {e}")
相关推荐
Joy T38 分钟前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
专注仿真4 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
Best-Wishes4 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停5 小时前
自动化测试(java)
java·开发语言·selenium·自动化
Smoothcloud润云5 小时前
PyTorch大模型权重加载与启动耗时优化实战:定位磁盘、内存与显存瓶颈
人工智能·pytorch·python·深度学习·gpu算力
databook5 小时前
从循环到向量化:NumPy提速的7个关键思维
python·数据分析·numpy
棉猴6 小时前
玩游戏学Python1-Python和pgzero库的安装
python·pygame·玩游戏·pgzero·pgzrun
诺伦6 小时前
GEO优化数据实证:78%引用流向官网的机制拆解与小品牌三步管线实战教程 | RiseClaw玄策
python·seo·geo·内容营销·ai搜索
oooost6 小时前
pytorch学习笔记1
python·学习方法
鬼手点金7 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github