侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

PHP使用redis位图bitMap 实现签到功能

Redis  /  管理员 发布于 5年前   396

一、需求

记录用户签到,查询用户签到

二、技术方案

1、使用mysql(max_time字段为连续签到天数)

 

思路:

(1)用户签到,插入一条记录,根据create_time查询昨日是否签到,有签到则max_time在原基础+1,否则,max_time=0

(2)检测签到,根据user_id、create_time查询记录是否存在,不存在则表示未签到

2、使用redis位图功能

思路:

(1)每个用户每个月单独一条redis记录,如00101010101010,从左往右代表01-31天(每月有几天,就到几天)
(2)每月8号凌晨,统一将redis的记录,搬至mysql,记录如图

 

(3)查询当月,从redis查,上月则从mysql获取

3、方案对比

举例:一万个用户签到365天

方案1、mysql 插入365万条记录

・ 频繁请求数据库做一些日志记录浪费服务器开销。
・  随着时间推移数据急剧增大
・ 海量数据检索效率也不高,同时只能用时间create_time作为区间查询条件,数据量大肯定慢

方案2、mysql 插入12w条记录

・ 节省空间,每个用户每天只占用1bit空间 1w个用户每天产生10000bit=1050byte 大概为1kb的数据
・ 内存操作存度快

3、实现(方案2)

(1)key结构

前缀_年份_月份:用户id -- sign_2019_10:01

查询:

单个:keys sign_2019_10_01

全部:keys sign_*

月份:keys sign_2019_10:*

(2)mysql表结构

 

(3)代码(列出1个调用方法,与三个类)

・签到方法

public static function userSignIn($userId)  {    $time = Time();    $today = date('d', $time);    $year = date('Y', $time);    $month = date('m', $time);    $signModel = new Sign($userId,$year,$month);    //1、查询用户今日签到信息    $todaySign = $signModel->getSignLog($today);    if ($todaySign) {      return self::jsonArr(-1, '您已经签到过了', []);    }    try {      Db::startTrans();      $signModel->setSignLog($today);      //4、赠送积分      if (self::SING_IN_SCORE > 0) {        $dataScore['order_id'] = $userId.'_'.$today;        $dataScore['type'] = 2;//2、签到        $dataScore['remark'] = '签到获得积分';        Finance::updateUserScore(Finance::OPT_ADD, $userId, self::SING_IN_SCORE, $dataScore);      }      $code = '0';      $msg = '签到成功';      $score = self::SING_IN_SCORE;      Db::commit();    } catch (\Exception $e) {      Db::rollback();      $code = '-2';      $msg = '签到失败';      $score = 0;    }    return self::jsonArr($code, $msg, ['score' => $score]);  }

・redis基类

getRedis();  }  public function _calcKey($id)  {    return $this->_tableName . $id;  }  /**   * 查找key   * @param $key   * @return array   * @throws \Exception   * @author wenzhen-chen   */  public function keys($key)  {    return $this->getRedis()->keys($this->_calcKey($key));  }  /**   * 获取是否开启缓存的设置参数   *   * @return boolean   */  public function _getEnable()  {    $conf = Config('redis');    return $conf['enable'];  }  /**   * 获取redis连接   *   * @staticvar null $redis   * @return \Redis   * @throws \Exception   */  public function getRedis()  {    if (!self::$redis) {      $conf = Config('redis');      if (!$conf) {        throw new \Exception('redis连接必须设置');      }      self::$redis = new \Redis();      self::$redis->connect($conf['host'], $conf['port']);      self::$redis->select($this->_db);    }    return self::$redis;  }  /**   * 设置位图   * @param $key   * @param $offset   * @param $value   * @param int $time   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function setBit($key, $offset, $value, $time = 0)  {    if (!$this->_getEnable()) {      return null;    }    $result = $this->getRedis()->setBit($key, $offset, $value);    if ($time) {      $this->getRedis()->expire($key, $time);    }    return $result;  }  /**   * 获取位图   * @param $key   * @param $offset   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function getBit($key, $offset)  {    if (!$this->_getEnable()) {      return null;    }    return $this->getRedis()->getBit($key, $offset);  }  /**   * 统计位图   * @param $key   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function bitCount($key)  {    if (!$this->_getEnable()) {      return null;    }    return $this->getRedis()->bitCount($key);  }  /**   * 位图操作   * @param $operation   * @param $retKey   * @param mixed ...$key   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function bitOp($operation, $retKey, ...$key)  {    if (!$this->_getEnable()) {      return null;    }    return $this->getRedis()->bitOp($operation, $retKey, $key);  }  /**   * 计算在某段位图中 1或0第一次出现的位置   * @param $key   * @param $bit 1/0   * @param $start   * @param null $end   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function bitPos($key, $bit, $start, $end = null)  {    if (!$this->_getEnable()) {      return null;    }    return $this->getRedis()->bitpos($key, $bit, $start, $end);  }  /**   * 删除数据   * @param $key   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function del($key)  {    if (!$this->_getEnable()) {      return null;    }    return $this->getRedis()->del($key);  }}

・签到redis操作类

keySign = $this->keySign . '_' . $year . '_' . $month . ':' . $userId;  }  /**   * 用户签到   * @param $day   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function setSignLog($day)  {    return $this->setBit($this->keySign, $day, 1);  }  /**   * 查询签到记录   * @param $day   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function getSignLog($userId,$day)  {    return $this->getBit($this->keySign, $day);  }  /**   * 删除签到记录   * @return int|null   * @throws \Exception   * @author wenzhen-chen   */  public function delSignLig()  {    return $this->del($this->keySign);  }}

・ 定时更新至mysql的类

keys('sign_' . $year . '_' . $month . ':*');    foreach ($keys as $key) {      $bitLog = '';//用户当月签到记录      $userData = explode(':', $key);      $userId = $userData[1];      //3、循环查询用户是否签到(这里没按每月天数存储,直接都存31天了)      for ($i = 1; $i <= 31; $i++) {        $isSign = $signModel->getBit($key, $i);        $bitLog .= $isSign;      }      $data[] = [        'user_id' => $userId,        'year' => $year,        'month' => $month,        'bit_log' => $bitLog,        'create_time' => $time,        'update_time' => $time      ];    }    //4、插入日志    if ($data) {      $logModel = new SignLog();      $logModel->insertAll($data, '', 100);    }  }}

总结

以上所述是小编给大家介绍的PHP使用redis位图bitMap 实现签到功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

  • thinkPHP实现签到功能的方法
  • php+mysql+jquery实现日历签到功能
  • php实现每日签到功能
  • php实现签到功能的方法实例分析
  • 定位地理位置PHP判断员工打卡签到经纬度是否在打卡之内
  • Php连接及读取和写入mysql数据库的常用代码
  • php中关于mysqli和mysql区别的一些知识点分析
  • PHP读取MySQL数据代码
  • PHP+MYSQL实现用户的增删改查
  • php基础之连接mysql数据库和查询数据
  • PHP连续签到功能实现方法详解


  • 上一条:
    Yii框架的redis命令使用方法简单示例
    下一条:
    Laravel的Auth验证Token验证使用自定义Redis的例子
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Redis中能实现的功能、常见应用介绍(0个评论)
    • 2024年Redis面试题之一(0个评论)
    • 在redis缓存常见出错及解决方案(0个评论)
    • 在redis中三种特殊数据类型:地理位置、基数(cardinality)估计、位图(Bitmap)使用场景介绍浅析(2个评论)
    • Redis 删除 key用 del 和 unlink 有啥区别?(1个评论)
    • 近期文章
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-12
    • 2020-03
    • 2020-05
    • 2021-04
    • 2022-03
    • 2022-05
    • 2022-08
    • 2023-02
    • 2023-04
    • 2023-07
    • 2024-01
    • 2024-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客