PHP擴充模組memcached長串連使用方法分析,擴充模組memcached_PHP教程

來源:互聯網
上載者:User

PHP擴充模組memcached長串連使用方法分析,擴充模組memcached


網上廣泛流傳著一篇文章,講述php的兩個擴充模組memcache和memcached的區別,其中特意強調了memcached與memcached一個很大的區別是memcached模組不支援長串連。以至於後來很多年我都認為memcached是不支援長串連的,其實不然,memcached擴充模組從很早的版本開始就已經支援長串連了。從擴充模組的源碼注視中我們就能看到:

/* {{{ Memcached::__construct([string persistent_id[, callback on_new[, string connection_str]]]))

Creates a Memcached object, optionally using persistent memcache connection */

static PHP_METHOD(Memcached, __construct)

{

從php的手冊身上我們可以看到memcached的擴充模組提供的建構函式提供一個參數persistent_id可選項,手冊中這樣介紹:

預設情況下,Memcached執行個體在請求結束後會被銷毀。但可以在建立時通過persistent_id為每個執行個體指定唯一的ID, 在請求間共用執行個體。所有通過相同的persistent_id值建立的執行個體共用同一個串連。

這個參數的含義就是說如果你傳遞了一個命名id給到構造方法,那麼就會建立長串連,通常我們使用的都是PHP-FPM模式,這樣PHP-FPM進程就會和memcached服務簡曆一條長串連通道。我們也可以理解為persistent_id就是一個串連池名字,所有php-fpm進程都是這個串連池中的一員。

但我們需要注意的是php是解釋性語言,當php第一次通過memached模組建立起長串連後,切記後續的php執行就不要再通過memcached的建構函式構建相同persistent_id命名的長串連,可以建立不同persistent_id名字的長串連,如果是相同的名字被php重複執行,一定會導致php-fpm的進程異常導致與memcached的通訊越來越慢,同時根據libmemcached的版本不同還會導致php產生coredump。

那麼我們如何避免單個php-fpm在建立完以persistent_id命名的長串連後不再重複建立長串連呢?其實在PHP帶有評註的手冊上是有講解的,內容如下:

When using persistent connections, it is important to not re-add servers.

This is what you do not want to do:

$mc = new Memcached('mc');$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);$mc->addServers(array(  array('mc1.example.com',11211),  array('mc2.example.com',11211),));


Every time the page is loaded those servers will be appended to the list resulting in many simultaneous open connections to the same server. The addServer/addServers functions to not check for existing references to the specified servers.

A better approach is something like:

$mc = new Memcached('mc');$mc->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);if (!count($mc->getServerList())) {  $mc->addServers(array(    array('mc1.example.com',11211),    array('mc2.example.com',11211),  ));}

通過使用getServerList()方法來檢查當前執行使用的php-fpm進程容器中是否已經存在相同名字的長串連資源,如果存在就不要重複使用addServers() 方法來新增長串連配置。

http://www.bkjia.com/PHPjc/932496.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/932496.htmlTechArticlePHP擴充模組memcached長串連使用方法分析,擴充模組memcached 網上廣泛流傳著一篇文章,講述php的兩個擴充模組memcache和memcached的區別,其中特...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.