缓存类, 单例模式, 当前支持 Memcached, Redis
PHP脚本结束时框架会自动关闭已经连接的所有资源
在开启命名空间情况下(asf.use_namespace=1)类名为 Asf\Cache
<?php final class Asf_Cache { public static array getConfig(void) public static bool setConfig(array $config) public static array getLinks(void) public static object store(string $name) public static bool close(string $name) public static bool closeAll(void) }
设置缓存配置信息
获取缓存的配置信息
使用单例模式连接Redis, Memcached, 返回对应的实例化对象
根据各项配置信息的字段type明确使用缓存的类型
复用资源时, 框架会自动检查资源是否有效。有效资源则复用连接, 无效资源则重新连接一次
获取已经连接的所有缓存信息
关闭基于单个(name)配置的连接, 并且清除掉指定(name)缓存的单例
关闭所有配置的连接, 并且清除掉所有缓存的单例
<?php use Asf\Cache; $cache_config = [ 'memcached' => [ 'type' => 'memcached', 'host' => array( array('127.0.0.1', 11211), ), ], 'redis' => [ 'type' => 'redis', 'host' => '10.139.240.177', 'password' => '5905b51e17dbce22', ], ]; /* init configs */ cache::setConfig($cache_config); /* 连接Redis */ cache::store('redis'); /* 连接Memcached */ cache::store('memcached'); /* 存储一个元素 aaa */ cache::store('redis')->set('aaa', 'test'); cache::store('memcached')->set('aaa', 'test');
<?php use Asf\Cache; $cache_config = [ 'redis1' => [ 'type' => 'redis', 'host' => '1.1.1.1', 'password' => '1111111', 'port' => 6379, // default 6379 'timeout' => 1, // default 1 'select' => 0, // default 0 'persistent' => 0, // default 0 ], 'redis2' => [ 'type' => 'redis', 'host' => '2.2.2.2', 'password' => '22222222', 'timeout' => 2, ], ]; var_dump(Cache::setConfig($cache_config)); print_r(Cache::getConfig()); echo PHP_EOL; echo '------------------------redis1', PHP_EOL; $key = 'cache_key'; $redis = Cache::store('redis1'); print_r(Cache::getLinks()); var_dump($redis->close()); // 切换到redis操作 & 连接 echo '------------------------redis2', PHP_EOL; $redis = Cache::store('redis2'); print_r(Cache::getLinks()); echo '------------------------set/has/get', PHP_EOL; var_dump($redis->set($key, 1)); var_dump($redis->has($key)); var_dump($redis->get($key)); echo '------------------------incr/decr', PHP_EOL; var_dump($redis->incr($key)); var_dump($redis->decr($key)); var_dump($redis->incr($key, 10)); var_dump($redis->decr($key, 5)); echo '------------------------get', PHP_EOL; var_dump($redis->get($key)); echo '------------------------del', PHP_EOL; var_dump($redis->get($key)); var_dump($redis->delete(array($key, 'ddd'))); var_dump($redis->get($key)); echo '------------------------clear', PHP_EOL; var_dump($redis->clear()); echo '------------------------close', PHP_EOL; var_dump($redis->close());
<?php use Asf\Cache; $cache_config = [ '6379_master' => [ 'type' => 'redis', 'host' => '1.1.1.1', 'password' => '1111111', ], '6379_slave' => [ 'type' => 'redis', 'host' => '2.2.2.2', 'password' => '22222222', ], ]; Cache::setConfig($cache_config); $master = Cache::store('6379_master'); $slave = Cache::store('6379_slave');