PHP使用redis位图bitMap 实现签到功能(3)
·签到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 实现签到功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对黑区网络网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
