使用redis位圖bitMap 實現簽到功能(PHP版本)

需要優化的地方,請各位看官在評論幫忙指出

一、需求

記錄用戶簽到,查詢用戶簽到

二、技術方案

1、使用mysql(max_time字段爲連續簽到天數)

clipboard.png
思路:
(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,記錄如圖

clipboard.png

(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表結構
clipboard.png

(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);
        }

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章