yii2 FileCache修改默认的文件名定义规则

场景

yii2使用FielCache缓存网页,时间长了之后,堆在一起不好清理

解决

自定义文件的缓存文件名的规则
. yii\caching\Cache;
. yii\caching\yii\caching;
    /**
     * Builds a normalized cache key from a given key.
     *
     * If the given key is a string containing alphanumeric characters only and no more than 32 characters,
     * then the key will be returned back prefixed with [[keyPrefix]]. Otherwise, a normalized key
     * is generated by serializing the given key, applying MD5 hashing, and prefixing with [[keyPrefix]].
     *
     * @param mixed $key the key to be normalized
     * @return string the generated cache key
     */
    public function buildKey($key)
    {
        if (is_string($key)) {

            //$key = ctype_alnum($key) && StringHelper::byteLength($key) <= 32 ? $key : md5($key);

            // 修改文件名的规则 如果文件名的长度大于100或者不全是数字字母,md5加密生成新的文件名
            $key = ctype_alnum($key) && StringHelper::byteLength($key) <= 100 ? $key : md5($key);

        } else {
            $key = md5(json_encode($key));
        }

        return $this->keyPrefix . $key;
    }
    protected function setValue($key, $value, $duration)
    {
        $this->gc();
        $cacheFile = $this->getCacheFile($key);
        if ($this->directoryLevel > 0) {
            @FileHelper::createDirectory(dirname($cacheFile), $this->dirMode, true);
        }
        if (@file_put_contents($cacheFile, $value, LOCK_EX) !== false) {
            if ($this->fileMode !== null) {
                @chmod($cacheFile, $this->fileMode);
            }
            if ($duration <= 0) {
                $duration = 31536000; // 1 year
            }

            return @touch($cacheFile, $duration + time());
        } else {
            $error = error_get_last();
            Yii::warning("Unable to write cache file '{$cacheFile}': {$error['message']}", __METHOD__);
            return false;
        }
    }

猜你喜欢

转载自blog.csdn.net/cominglately/article/details/80053431
今日推荐