ThinkPHP3.2.3:Memcache缓存的使用方法总结

20 篇文章 6 订阅
14 篇文章 0 订阅

  • 方法一:原生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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李维山

帮到你就行 不差钱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值