zoukankan      html  css  js  c++  java
  • memcache分布式小实例

    <?php
    
    /**
     * 分布式的 memcache set 实现
     */
    
    /**
     * 创建缓存实现memcache 添加分布式服务器  并设置权限
     */
    
    function createCache() {
        $arr = array(
            array("host" => "127.0.0.1", "port" => 11211, "weight" => 20), //127.0.0.1:11211的权重是20%
            array("host" => "127.0.0.1", "port" => 11212, "weight" => 80), //127.0.0.1:11212的权重是80%
        );
        $cache = new memcache();
        foreach ($arr as $ele) {
            //使用长连接,并且设置不同memcache服务器的权重,将memcache服务器添加到连接池
            $cache->addServer($ele["host"], $ele["port"], true, $ele["weight"]);
        }
        return $cache;
    }
    
    header("content-type:text/html;charset=utf-8");
    $cache = createCache();
    for ($i = 0; $i < 10; $i++) {
        //由于使用了分布式,所以这里不需要使用connect或者pconnect打开链接,
    //set方法会调用memcache的分布式缓存分配算法,按照权重将缓存项缓存到连接池的某个服务器
    if ($cache->set($i, $i, 0, 3600)) { echo "缓存成功,key:$i,value:$i"; } else { echo "缓存失败"; } echo "<br/>"; } ?>
    <?php
    
    /**
     * 分布式的 memcache get 实现
     */
    
    function createCache() {
        $arr = array(
            array("host" => "127.0.0.1", "port" => 11211, "weight" => 20),
            array("host" => "127.0.0.1", "port" => 11212, "weight" => 80)
        );
        $cache = new memcache();
        foreach ($arr as $ele) {
            $cache->addServer($ele ["host"], $ele ["port"], true, $ele ["weight"], 1);
        }
        return $cache;
    }
    
    header('content-type:text/html;charset=utf-8');
    $cache = createCache();
    $val;
    for ($i = 0; $i < 10; $i ++) {
        $val = $cache->get($i);
        if (false === $val) {
            echo "缓存获取失败";
        } else {
            echo "缓存获取成功:,key:$val,value:$val";
        }
        echo "<br/>";
    }
    $cache->close();
    ?>
  • 相关阅读:
    git的撤销操作
    mysql的逻辑结构
    mysql的系列大纲
    CompletableFuture的介绍
    AQS学习
    mysql中的数据格式
    将excel的数据进行sql处理
    什么是数据分析
    找圆方法的总结和比较(三种主要识别方法的比较和融合)
    一个有趣问题的分析--寻找并且增强印章
  • 原文地址:https://www.cnblogs.com/timelesszhuang/p/4254209.html
Copyright © 2011-2022 走看看