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

记录用户的连续登录天数

  • 访问量: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}")
相关推荐
IVEN_10 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang11 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮11 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling11 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮14 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽15 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers