Yii2 redis Active Record 使用, 查询慢的问题

Redis · Fecshop · 于 8个月前 发布 · 569 次阅读

Yii2 有redis AR扩展,可以方便的使用

但是使用过程中,发现AR的查询非常的慢

譬如我的定义:

namespace fecshop\models\redis;

use yii\redis\ActiveRecord;

/**
 * @author Terry Zhao <2358269014@qq.com>
 * @since 1.0
 */
class SessionStorage extends ActiveRecord
{
    public function attributes()
    {
        return [
            'id', 'session_uuid',
            'session_key', 'session_value',
            'session_timeout','session_updated_at'
        ];
    }
    /**
     * relations can not be defined via a table as there are not tables in redis. You can only define relations via other records.
     */
}

查询:

$one =  SessionStorage::find()->where([
            'session_uuid' => $uuid,
            'session_key'  => $key,
        ])->one();

改进:

redis AR中插入数据的id通过 uuid 和key生成,

public function getUuidKey($uuid, $key){
        return $uuid.'###^^###'.$key;
    }

查询:

public function get($key,$reflush){
        $uuid = Yii::$service->session->getUUID();
        $r_id = $this->getUuidKey($uuid, $key);
        $one = $this->_sessionModel->find()->where([
            'id' => $r_id,
        ])->one();
        if($one['id']){
            $timeout = $one['session_timeout'];
            $updated_at = $one['session_updated_at'];
            if($updated_at + $timeout > time()){
                if($reflush){
                    $one['session_updated_at']  = time();
                    $one->save();
                }
                return $one['session_value'];
            }
        }
    }

速度明显提升,对于vue端,以前需要300ms,现在只要100多ms(中间有网络时间,访问html静态文件也要80ms)

issue: https://github.com/yiisoft/yii2-redis/issues/146

共收到 1 条回复
Fecshop#18个月前 0 个赞

对fecshop的代码进行了优化, https://github.com/fecshop/yii2_fecshop/commit/5173c7e2e3c9c260cf11570147fa71b793a9df21

vue访问速度明显提升

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics