* @version : HUOSDK 8.5 */ namespace huoIdentify\logic; use huo\model\common\CommonModel; use huoIdentify\model\IdentifyMotModel; use huolib\constant\CacheConst; use huolib\constant\CommonConst; use think\Cache; class IdentifyMotLogic extends CommonModel { protected $update_time = CommonConst::MINUTE_SECONDS_10; //写入数据库间隔时间 10分钟 60s protected $cache_key_prefix = CacheConst::CACHE_IDENTIFY_MOT_PREFIX; //缓存前缀 /*** * 根据玩家id和日期获取缓存key * * @param int $mem_id 玩家id * @param string $date 日期 年月日 空者获取今日日期 * * @return string */ public function getCacheKeyByMemId($mem_id, $date = '') { $_date = date('Ymd'); if (!empty($date)) { $_date = date('Ymd', strtotime($date)); } $_cache_key = $this->cache_key_prefix.$mem_id.$_date; return $_cache_key; } /** * 保存缓存数据 * * @param $key * @param $data */ public function saveCacheData($key, $data) { $_expire = CommonConst::CONST_7_DAY_SECONDS; //缓存7天 Cache::set($key, $data, $_expire); } /*** * 根据id_card获取统计数据 * * @param int $mem_id 玩家id * * @return mixed */ public function getInfoByMemId($mem_id) { if (empty($mem_id)) { return []; } $_cache_key = $this->getCacheKeyByMemId($mem_id); $_data = Cache::get($_cache_key); if (!empty($_data)) { return $_data; } $_model = new IdentifyMotModel(); $_info = $_model->getInfoByMemId($mem_id); if (empty($_info)) { $_data = [ 'mem_id' => $mem_id ]; $_model->addData($_data); $_info = $_model->getInfoByMemId($mem_id); } $_next_update_time = time() + $this->update_time; $_info['next_update_time'] = $_next_update_time; $this->saveCacheData($_cache_key, $_info); return $_info; } /** * 根据id_card更新统计数据 * * @param array $data 更新数据 * @param int $mem_id 玩家id * * @return bool */ public function updateByMemId($data, $mem_id) { $_cache_key = $this->getCacheKeyByMemId($mem_id); $_time = time(); $_old_data = $this->getInfoByMemId($mem_id); $_data = array_merge($_old_data, $data); $_update_time = $_data['next_update_time']; //获取当前缓存的更新时间 入库失败则回退 $_data['update_time'] = $_time; $this->saveCacheData($_cache_key, $_data); //先更新缓存 if ($_update_time <= $_time) { $_data['next_update_time'] = $_time + $this->update_time; $_rs = (new IdentifyMotModel())->updateByMemId($_data, $mem_id); if (false === $_rs) { /* 入库失败 */ $_data['next_update_time'] = $_update_time; //还原更新时间 } $this->saveCacheData($_cache_key, $_data); //更新缓存 } return true; } /** * 更新时长 * * @param int $time 时长 * @param int $mem_id 玩家id * * @return bool */ public function updateOnlineTimeByMemId($time, $mem_id) { $_data = $this->getInfoByMemId($mem_id); $_data['online_duration'] += $time; $_rs = $this->updateByMemId($_data, $mem_id); return $_rs; } }