一个小小的签到功能,到底用MySQL还是Redis?
程序员的成长之路
共 2447字,需浏览 5分钟
·
2020-09-17 04:50
阅读本文大概需要 2.8 分钟。
来自:网络
一. 方案1
签到流程
last_checkin_time = time()
checkin_count=1
last_checkin_time = time()
checkin_count= checkin_count+1
last_checkin_time = time()
checkin_count=1
//0点
$today_0 = strtotime(date('y-m-d'));
//昨天0点
$yesterday_0 = $today_0-24*60*60;
$last_checkin_time = $model->last_checkin_time;if(empty($last_checkin_time)){
//first checkin
$model->last_checkin_time = time();
$model->checkin_count = 1;
}else{
if($today_0 < $last_checkin_time){
//checkin ed 当天已签到过
return json_encode(['code' => 0, 'msg' => '已签到成功']);
} //昨天签到过 if($last_checkin_time < $today_0 && $last_checkin_time > $yesterday_0){
$model->last_checkin_time = time();
$model->checkin_count = $model->checkin_count + 1;
}else{
//昨天没签到过,重新计数
$model->last_checkin_time = time();
$model->checkin_count = 1;
}}$rs = $model->save();
二. 方案2
签到流程
一个以每天日期为key ,每个uid为偏移量
一个以用户uid为key ,当天在一年中的索引为偏移量,
//每天一个key
$key = 'checkin_' . date('ymd');
if($redis->getbit($key, $uid)){
//已签到 return json_encode(['code' => 0, 'msg' => '已签到成功']);
}else{
//签到 $redis->setbit($key, $uid, 1);
$redis->setbit('checkin_'.$uid , date('z'), 1);
}
public static function getUserCheckinCount($uid){
$key = 'checkin_'.$uid;
$index = date('z');
$n = 0;
for($i = $index; $i>=0;$i--){
$bit = Yii::$app->redis->getbit($key, $i); if($bit == 0) break;
$n++; } return $n;
}
$key = 'checkin_' . date('ymd');
$redis = Yii::$app->redis;$count = $redis->BITCOUNT($key);
三. 优缺点比较
推荐阅读:
微信扫描二维码,关注我的公众号
朕已阅
评论