缓存配置


设置配置项

配置文件路径:

config/{环境}/common.config.php
    
app/{应用}/config.php
    
两个里面都可以配置,只需增加一个配置项(cache)即可

例子:

Redis作为缓存

return [
    'cache' => [
        'type' => 'Redis',
        'host' => '127.0.0.1',
        'port' => 6379,
        'timeout' => 3,
        'db' => 6
    ]
];

缓存类库

使用redis缓存之前,请将下面类库放入项目根目录lib/cache下面
<?php
/**
 * Created by timophp.com
 * User: tomener
 */

namespace lib\cache;


use RedisException;
use Timo\Config\Config;
use Timo\Core\Exception;
use Timo\Log\Log;

/**
 * @method static \Redis cache
 * @method static \Redis queue
 * @method static \Redis store
 * @method static \Redis token
 */
class CacheLib
{
    protected static $instances = [];

    /**
     * 获取缓存key配置
     *
     * @param $config_name
     * @param array ...$key
     * @return string
     * @throws Exception
     */
    public static function getCacheKey($config_name, ...$key)
    {
        static $config = null;
        if (null === $config) {
            $config = Config::load(Config::runtime('config.path') . 'cache_key.config.php');
        }

        $cache_key = $config[$config_name];
        if (!$cache_key) {
            throw new Exception("未定义的缓存key: {$config_name}");
        }

        if (!empty($key)) {
            return sprintf('%s:%s', $cache_key, implode(':', $key));
        }

        return $cache_key;
    }

    /**
     * 获取redis实例
     *
     * @param $dbName
     * @return \Redis
     * @throws \Exception
     */
    public static function getRedisInstance($dbName)
    {
        if (isset(self::$instances[$dbName])) {
            return self::$instances[$dbName];
        }
        $config = Config::runtime('redis.' . $dbName);
        $redis = new \Redis();
        for ($i = 0; $i < 3; $i++) {
            try {
                $redis->connect($config['host'], $config['port'], $config['timeout']);
            } catch (RedisException $e) {
                if ($e->getMessage() == 'Connection timed out') {
                    Log::single('connect times ' . $i, 'redis/timeout_retry');
                    if ($i < 2) {
                        continue;
                    }
                }
                unset(self::$instances[$dbName]);
                Log::single([
                    'Message' => $e->getMessage(),
                    'Code' => $e->getCode(),
                    'File' => $e->getFile(),
                    'Line' => $e->getLine()
                ], 'redis/connect_err');
                throw new \Exception($e->getMessage(), $e->getCode());
            }
            break;
        }

        $redis->select($config['db']);
        self::$instances[$dbName] = $redis;
        return $redis;
    }

    /**
     * 销毁redis对象
     */
    public static function destroy()
    {
        self::$instances = [];
    }

    /**
     * @param $name
     * @param $arguments
     * @return bool|\Redis
     * @throws \Exception
     */
    public static function __callStatic($name, $arguments)
    {
        switch ($name) {
            case 'cache' :
            case 'queue' :
            case 'store' :
            case 'token' :
                return self::getRedisInstance($name);
                break;
            default :
                return false;
        }
    }
}

如何使用

<?php

use lib\cache\CacheLib;

$cache_key = 'book:109';
$book = CacheLib::cache()->get($cache_key);