为了账号安全,请及时绑定邮箱和手机立即绑定

写一个php memcache简单的函数

标签:
PHP

在一个项目中添加了memcache层,但由于数据库本来压力就不大,数据量很小,所以性能改善不是特别明显,因此学习并应用下来记录一下方便以后自己使用。这里我只应用了直接调用对应api函数的方法,另外一种方法是创建对象来连接memcache,具体是$mem=new Memcache,然后再调用对象里的方法来操作要存储的item。

本次使用环境为php 5.4.17,

yum安装的驱动:

php-pecl-memcache-3.0.8-1.el5.remi

代码如下:

$MEMCACHE["host"]="10.54.178.202";

$MEMCACHE["port"]="11211";

$MEMCACHE["timeout"]="5";

 

 

function cache_set($key, $value, $expire = 86400, $flag = MEMCACHE_COMPRESSED, $cache_host = NULL) {
    if(empty($cache_host)) {
        global $MEMCACHE;
        $cache_host = $MEMCACHE["host"];
        $cache_port = $MEMCACHE["port"];
        $cache_timeout = $MEMCACHE["timeout"];
    }
    $memcache = memcache_connect($cache_host,$cache_port,$cache_timeout);
    $memcache->set($key, $value, $flag, $expire);
    memcache_close($memcache);
}
 
function cache_get($key, $cache_host = null) {
    if(empty($cache_host)) {
        global $MEMCACHE;
        $cache_host = $MEMCACHE["host"];
        $cache_port = $MEMCACHE["port"];
        $cache_timeout = $MEMCACHE["timeout"];
    }
 
    $memcache = memcache_connect($cache_host,$cache_port,$cache_timeout);
    $result=$memcache->get($key);
    memcache_close($memcache);
    return $result;
}
 
function cache_clear($key, $cache_host = null) {
    if(empty($cache_host)) {
        global $MEMCACHE;
        $cache_host = $MEMCACHE["host"];
        $cache_port = $MEMCACHE["port"];
        $cache_timeout = $MEMCACHE["timeout"];
    }
    $memcache = memcache_connect($cache_host,$cache_port,$cache_timeout);
    $memcache->delete($key, 0);
    memcache_close($memcache);
}


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消