php-fpm грузит CPU на 100% после включения memcached

debian 6 + Nginx + mysql + php-fpm 5.5 + OPcache (вроде так называется, стандартный кеш в php 5,5). Включен файловый кеш в LS. Загрузка сервера выше 0.20 0.20 0.20 редко подымается.

Ставлю memcached:

apt-get install memcached php5-memcache


в /etc/memcached.conf добавляю:

-s /var/run/memcached.sock
-a 0777


Комментирую -p и -l

-u nobody меняю на root

/etc/init.d/memcached restart


В config.local.php добавил:

$config['memcache']['servers'][0]['host'] = 'unix:///var/run/memcached.sock';
$config['memcache']['servers'][0]['port'] = '0';
$config['sys']['cache']['use']    = true;
$config['sys']['cache']['type']   = 'memory';
$config['sys']['cache']['prefix'] = 'mysite';


После этого memcached начинает работать, но сервер перегружается через пару минут. Висят 3 процесса php-fpm по 30% использования CPU на каждый, загрузка сервера показывает примерно 4.54 3.12 2.75.

Подскажите пожалуйста мб я что то упустил или где то ошибся?

Решение:


В общем проблему решил следующим образом. Пробовал по всякому с memcached — не работает.

Удаляем memcached:

apt-get remove memcached php5-memcache


Далее, кеш типа file. Если топик открывается несколько раз (например нажмем 20 раз f5 и посмотрим результат) php full time: увеличится раз в 5. Поэтому файловый кеш лучше вообще не включать.

А теперь наш король — apcu

Почитал несколько статей, говорят, что встроенный в php 5.5 Opcache работает значительно быстрее всех своих аналогов но не умеет кешировать backend. Поэтому в пару ему ставят apcu или memcached.

Устанавливаем apcu:

apt-get install php5-apcu


В конфиге LS нет возможности выбрать тип кеширования apcu но нам повезло, в далеком 2010 BIT написал, как решается эта проблема APC Backend Cache.

!!! В php не очень хорошо разбираюсь, поэтому просто сравнил с другими php файлами кеша и по аналогии внес изменения. Но лучше чтобы кто-нибудь проверил. В любом случае работает !!!

Создаем файл следующего содержания здесь:
/engine/lib/external/DklabCache/Zend/Cache/Backend/Apc.php

<?php
/**
	* Zend Framework
 *
 * LICENSE 
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 * 
 * @category   Zend
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright © 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */ 


/**
 * @see Zend_Cache_Backend_Interface
 */
require_once LS_DKCACHE_PATH.'Zend/Cache/Backend/Interface.php';

/**
 * @see Zend_Cache_Backend
 */
require_once LS_DKCACHE_PATH.'Zend/Cache/Backend.php';


/**
 * @package    Zend_Cache
 * @subpackage Zend_Cache_Backend
 * @copyright  Copyright © 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Cache_Backend_APC extends Zend_Cache_Backend implements Zend_Cache_Backend_Interface
{
    /**
     * Persistent
     */
    const DEFAULT_PERSISTENT = true;

    /**
     * Constructor
     *
     * @param array $options associative array of options
     * @throws Zend_Cache_Exception
     * @return void
     */
    public function __construct($options = array())
    {
        if (!extension_loaded('apc')) {
            Zend_Cache::throwException('The apc extension must be loaded for using this backend !');
        }
    }

    /**
     * Test if a cache is available for the given id and (if yes) return it (false else)
     *
     * @param  string  $id                     Cache id
     * @param  boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
     * @return string|false cached datas
     */
    public function load($id, $doNotTestCacheValidity = false)
    {
        // WARNING : $doNotTestCacheValidity is not supported !!!
        if ($doNotTestCacheValidity) {
            $this->_log("Zend_Cache_Backend_APC::load() : \$doNotTestCacheValidity=true is unsupported by the APC backend");
        }

        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            return $tmp[0];
        }
        return false;
    }

    /**
     * Test if a cache is available or not (for the given id)
     *
     * @param  string $id Cache id
     * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
     */
    public function test($id)
    {
        $tmp = apc_fetch($id);
        if (is_array($tmp)) {
            return $tmp[1];
        }
        return false;
    }

    /**
     * Save some string datas into a cache record
     *
     * Note : $data is always "string" (serialization is done by the
     * core not by the backend)
     *
     * @param  string $data             Datas to cache
     * @param  string $id               Cache id
     * @param  array  $tags             Array of strings, the cache record will be tagged by each string entry
     * @param  int    $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
     * @return boolean True if no problem
     */
    public function save($data, $id, $tags = array(), $specificLifetime = false)
    {
        $lifetime = $this->getLifetime($specificLifetime);

        $result = apc_store($id, array($data, time()), $lifetime);
        return $result;
    }

    /**
     * Remove a cache record
     *
     * @param  string $id Cache id
     * @return boolean True if no problem
     */
    public function remove($id)
    {
        return apc_delete($id);
    }

    /**
     * Clean some cache records
     *
     * Available modes are :
     * 'all' (default)  => remove all cache entries ($tags is not used)
     * 'old'            => remove too old cache entries ($tags is not used)
     * 'matchingTag'    => remove cache entries matching all given tags
     *                     ($tags can be an array of strings or a single string)
     * 'notMatchingTag' => remove cache entries not matching one of the given tags
     *                     ($tags can be an array of strings or a single string)
     *
     * @param  string $mode Clean mode
     * @param  array  $tags Array of tags
     * @return boolean True if no problem
     */
    public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
    {
        return true;
    }

    /**
     * Return true if the automatic cleaning is available for the backend
     *
     * @return boolean
     */
    public function isAutomaticCleaningAvailable()
    {
        return false;
    }

}


Редактируем файл:
/var/www/imgver.com/engine/modules/cache/Cache.class.php

Добавляем после:

define('SYS_CACHE_TYPE_MEMORY','memory');


Этот код:

define('SYS_CACHE_TYPE_APC','apc');


Далее, перед:

} elseif ($this->sCacheType==SYS_CACHE_TYPE_MEMORY) {


Вставляем:

} elseif ($this->sCacheType==SYS_CACHE_TYPE_APC) {
			require_once(LS_DKCACHE_PATH.'Zend/Cache/Backend/Apc.php');
			$oCahe = new Zend_Cache_Backend_APC();
			$this->oBackendCache = new Dklab_Cache_Backend_TagEmuWrapper(new Dklab_Cache_Backend_Profiler($oCahe,array($this,'CalcStats')));


В файле /config/config.php меняем тип кеширования на apc

$config['sys']['cache']['type']   = 'apc';


Тесты:


Главная страница, на сайте 1000 топиков, в которых минимум текста:

Кеш выключен

Стабильно показывает подобное время, визуально работает быстрее чем file кеш.



File

Самый нестабильный тип кеширования, примерно: 2/3 раз показывает php full time: ~0.280 и только 1/3 — 0.112. Опять же топики с 30+ просмотров имеют php full time ~0.500 и это не предел. На сервере установлен SSD.



Apcu
Визуально, стабильнее и быстрее всех остальных. Только запросов почему-то так много :)

Иностранные компании работающие на территории России зачастую не доверяют разработку сайтов местным исполнителям. Заказ сайтов в Латвии у http://www.primera.lv достойна альтернатива российским разработчикам.

0 комментариев

Только зарегистрированные и авторизованные пользователи могут оставлять комментарии.