123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
- namespace app\common\model;
- use app\common\library\Redis;
- use think\Cache;
- use think\Model;
- class ChannelSpecialManage extends Model
- {
- // 表名
- protected $table = 'channel_special_manage';
-
- // 自动写入时间戳字段
- protected $autoWriteTimestamp = 'int';
- // 定义时间戳字段名
- protected $createTime = 'createtime';
- protected $updateTime = 'updatetime';
- protected $redisKey = "CFW:";
-
- // 追加属性
- protected $append = [];
- protected static function init()
- {
- parent::init(); // TODO: Change the autogenerated stub
- self::afterUpdate(function ($model) {
- $model->removeCache($model->rule_name);
- });
- self::afterDelete(function ($model) {
- $model->removeCache($model->rule_name);
- });
- }
- /**
- * 是否是白名单
- * @param $rule_name
- * @param $channel_id
- * @return int
- */
- public function isWhite($rule_name, $channel_id)
- {
- $isWhite = 0;
- $redisKey = $this->redisKey.$rule_name;
- $redisData = Redis::instance()->hGetAll($redisKey);
- $fromDb = false;
- if (!empty($redisData)) {
- if (isset($redisData['expire_time']) && $redisData['expire_time'] <= time()) {
- $fromDb = true;
- } else {
- if (strrpos($redisData['channel_id'], '*') !== false) {
- //全部
- $isWhite = 1;
- } else if (strlen($redisData['channel_id']) > 0) {
- $channelIdArr = explode(',', $redisData['channel_id']);
- if (in_array($channel_id, $channelIdArr)) {
- $isWhite = 1;
- }
- }
- }
- } else {
- $fromDb = true;
- }
- if ($fromDb) {
- //读库缓存所有的结果
- $data = [
- 'channel_id' => ''
- ];
- $dbRow = $this->where('rule_name', 'eq', $rule_name)->find();
- if ($dbRow) {
- $data = $dbRow->toArray();
- $channelIdsRow =model("ChannelMenuList")->where('id', 'eq', $data['channel_id'])->find();
- $data['channel_id'] = $channelIdsRow['channel_id'] ?: '';
- if (strrpos($data['channel_id'], '*') !== false) {
- //全部
- $isWhite = 1;
- } else if (strlen($data['channel_id']) > 0) {
- $channelIdArr = explode(',', $data['channel_id']);
- if (in_array($channel_id, $channelIdArr)) {
- $isWhite = 1;
- }
- }
- }
- $data['expire_time'] = time() + 600;
- //写入redis 哈希结构
- Redis::instance()->hMSet($redisKey, $data);
- $expire = 3600 + mt_rand(0, 1000);
- Redis::instance()->expire($redisKey, $expire);
- }
- return $isWhite;
- }
- public function removeCache($rule_name)
- {
- $key = $this->redisKey.$rule_name;
- Redis::instance()->del($key);
- }
- }
|