本文实例讲述了ThinkPHP3.2.3框架Memcache缓存使用方法。分享给大家供大家参考,具体如下:
前面一篇文章讲述了Linux下安装Memcached服务器和客户端,这里来总结一下ThinkPHP3.2.3框架Memcache的使用方法。
方法一:原生Memcache的写法
public function test1() { $mc = new \\Memcache(); //创建Memcache对象 $mc->connect(\"127.0.0.1\", 11211); //连接Memcached服务器 $mc->set(\'test1\',\'hello world\',0,10); //存储数据 echo $mc->get(\'test\'); //获取数据 $mc->delete(\'test\'); //删除数据 $mc->flush(); //强制刷新全部缓存,即清空Memcached服务器 $mc->close(); //断开与Memcached服务器的连接 }
方法二:直接调用集成好的Memcache缓存驱动
public function test2() { $mc = new \\Think\\Cache\\Driver\\Memcache(); //实例化Memcache驱动 $mc->set(\'test2\',\'hello world\',60); //写入缓存 echo $mc->get(\'test2\'); //读取缓存 $mc->rm(\'test2\'); //删除指定缓存 $mc->clear(); //清空全部缓存 }
方法三:S方法
①直接调用S方法
public function test3() { //缓存初始化 S(array( \'type\'=>\'memcache\', //缓存类型 \'host\'=>\'127.0.0.1\', //Memcache服务器地址 \'port\'=>\'11211\', //Memcache端口号 \'prefix\'=>\'think\', //缓存标识前缀 \'expire\'=>10,) //缓存有效期(时间为秒) ); //设置缓存 S(\'test3\',\'hello world\'); //可以改变缓存时间:S(\'test3\',\'hello world\',60); //读取缓存 echo S(\'test3\'); //删除缓存 S(\'test3\',null); }
②采用对象方式操作缓存
public function test4() { $cache = S(array(\'type\'=>\'memcache\',\'prefix\'=>\'think\',\'expire\'=>10)); //缓存初始化 $cache->test4 = \'hello world\'; //设置缓存 echo $cache->test4; //获取缓存 unset($cache->test4); //删除缓存 }
手册中关于S方法初始化:如果不传入type参数,会读取配置文件中设置的DATA_CACHE_TYPE作为默认缓存类型;如果不传入prefix参数,会读取DATA_CACHE_PREFIX作为默认缓存标识前缀;如果不传入expire参数,会读取DATA_CACHE_TIME作为默认缓存有效期。
配置文件config.php中,关于Memcache缓存配置如下:
\'DATA_CACHE_TYPE\' => \'Memcache\', //数据缓存类型 \'DATA_CACHE_PREFIX\' => \'\', //缓存前缀 \'DATA_CACHE_TIME\' => 10, //数据缓存有效期 0表示永久缓存 \'DATA_CACHE_COMPRESS\' => false, //数据缓存是否压缩缓存
配置之后调用S方法无需再初始化
public function test5() { //设置缓存 S(\'test5\',\'hello world\'); //读取缓存 echo S(\'test5\'); //删除缓存 S(\'test5\',null); }
更多关于thinkPHP相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。
希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。
© 版权声明
THE END
暂无评论内容