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


Posted in PHP onOctober 08, 2019

一、需求

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

二、技术方案

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

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

思路:

(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,记录如图

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

(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表结构

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

(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基类

<?php
namespace app\common\redis\db1;
/**
 * redis操作类
 */
class RedisAbstract
{
  /**
   * 连接的库
   * @var int
   */
  protected $_db = 1;//数据库名
  protected $_tableName = '';//表名
  static $redis = null;
  public function __construct()
  {
    return $this->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操作类

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/30
 * Time: 14:42
 */
namespace app\common\redis\db1;
class Sign extends RedisAbstract
{
  public $keySign = 'sign';//签到记录key
  public function __construct($userId,$year,$month)
  {
    parent::__construct();
    //设置当前用户 签到记录的key
    $this->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的类

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/4
 * Time: 19:03
 */
namespace app\common\business;
use app\common\mysql\SignLog;
use app\common\redis\db1\Sign;
class Cron
{
  /**
   * 同步用户签到记录
   * @throws \Exception
   */
  public static function addUserSignLogToMysql()
  {
    $data = [];
    $time = Time();
    //1、计算上月的年份、月份
    $dataTime = Common::getMonthTimeByKey(0);
    $year = date('Y', $dataTime['start_time']);
    $month = date('m', $dataTime['start_time']);
    //2、查询签到记录的key
    $signModel = new Sign(0, $year, $month);
    $keys = $signModel->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 实现签到功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

PHP 相关文章推荐
逐步提升php框架的性能
Jan 10 PHP
php gd2 上传图片/文字水印/图片水印/等比例缩略图/实现代码
May 15 PHP
php中数字、字符与对象判断函数用法实例
Nov 26 PHP
PHP中实现crontab代码分享
Mar 26 PHP
PHP编程之设置apache虚拟目录
Jul 08 PHP
分析PHP中单双引号的误区和双引号小隐患
Jul 19 PHP
基于ThinkPHP实现的日历功能实例详解
Apr 15 PHP
Kindeditor编辑器添加图片上传水印功能(php代码)
Aug 03 PHP
PHP的PDO预处理语句与存储过程
Jan 27 PHP
php使用socket调用http和smtp协议实例小结
Jul 26 PHP
PHP 命名空间和自动加载原理与用法实例分析
Apr 29 PHP
PHP7变量处理机制修改
Mar 09 PHP
laravel-admin自动生成模块,及相关基础配置方法
Oct 08 #PHP
laravel-admin表单提交隐藏一些数据,回调时获取数据的方法
Oct 08 #PHP
关于Laravel-admin的基础用法总结和自定义model详解
Oct 08 #PHP
laravel-admin 实现给grid的列添加行数序号的方法
Oct 08 #PHP
PHP实现数组根据某个字段进行水平合并,横向合并案例分析
Oct 08 #PHP
thinkphp5框架前后端分离项目实现分页功能的方法分析
Oct 08 #PHP
PHP7 安装event扩展的实现方法
Oct 08 #PHP
You might like
php获取mysql版本的几种方法小结
2008/03/25 PHP
Yii2.0框架实现带分页的多条件搜索功能示例
2019/02/20 PHP
Laravel 微信小程序后端实现用户登录的示例代码
2019/11/26 PHP
jQuery插件jQuery-JSONP开发ajax调用使用注意事项
2013/11/22 Javascript
解决Jquery鼠标经过不停滑动的问题
2014/03/03 Javascript
jQuery源码解读之hasClass()方法分析
2015/02/20 Javascript
Bootstrap每天必学之媒体对象
2015/11/30 Javascript
jQuery点击其他地方时菜单消失的实现方法
2016/04/22 Javascript
Bootstrap Paginator分页插件使用方法详解
2016/05/30 Javascript
JavaScript中 ES6 generator数据类型详解
2016/08/11 Javascript
原生js 封装get ,post, delete 请求的实例
2017/08/11 Javascript
js图片无缝滚动插件使用详解
2020/05/26 Javascript
vue+ElementUI 关闭对话框清空验证,清除form表单的操作
2020/08/06 Javascript
Python中的深拷贝和浅拷贝详解
2015/06/03 Python
Python统计文件中去重后uuid个数的方法
2015/07/30 Python
Python max内置函数详细介绍
2016/11/17 Python
pycharm+django创建一个搜索网页实例代码
2018/01/24 Python
使用django-guardian实现django-admin的行级权限控制的方法
2018/10/30 Python
Python功能点实现:函数级/代码块级计时器
2019/01/02 Python
python 判断三个数字中的最大值实例代码
2019/07/24 Python
关于python导入模块import与常见的模块详解
2019/08/28 Python
python通过文本在一个图中画多条线的实例
2020/02/21 Python
python的flask框架难学吗
2020/07/31 Python
拿来就用!Python批量合并PDF的示例代码
2020/08/10 Python
JD Sports德国官网:英国领先的运动鞋和运动服饰零售商
2018/02/26 全球购物
享受加州生活方式的时尚舒适:XCVI
2018/07/09 全球购物
.net工程师笔试题
2012/06/09 面试题
什么是虚拟内存?虚拟内存有什么优势?
2016/02/09 面试题
初入社会应届生求职信
2013/11/18 职场文书
地理教师岗位职责
2014/03/16 职场文书
党支部公开承诺践诺书
2014/03/28 职场文书
2014年综治宣传月活动总结
2014/04/28 职场文书
销售目标责任书
2014/07/23 职场文书
2014年教师思想工作总结
2014/12/03 职场文书
联谊会开场白
2015/06/01 职场文书
开学随笔
2015/08/15 职场文书