cmemcache requires php memcache extension to be loaded

Memcached и PHP ликбез

Что такое Memcache и какое отношение он имеет к PHP?

Memcache разработан для кэширования данных, генерация которых требует большого количества ресурсов. Такого рода данные могут содержать что угодно, начиная с результатов запроса к базе данных и заканчивая тяжеловесным куском шаблона. Memcached не входит в базовый набор модулей, поставляемых с PHP, однако он доступен в репозитории pecl.

Установка и настройка

В качестве рассматриваемого дистрибутива я решил использовать Debian, потому как он наиболее часто используется при создании web-серверов. Модуль Memcached для PHP доступен в репозитории уже скомпилированным (php5-memcached), но я опишу процесс установки из исходного кода, так как не все репозитории настолько богаты, как дебиановский.

Устанавливаем сервер Memcached

#/etc/memcached.conf
#Memcached будет работать, как демон
-d
#Лог будет складывать туда
logfile / var / log / memcached.log
#Отведём 256 мегабайт ОЗУ под хранилище
-m 256
#Слушать будет этот порт
-p 11211
#В последствии желательно поменять
-u nobody
#Слушаем localhost
-l 127.0.0.1

Проверяем

Компилируем и устанавливаем модуль для PHP

apt-get install php5-dev libmemcache-dev

echo ‘extension=memcache.so’ >> / etc / php5 / apache2 / php.ini
/ etc / init.d / apache2 restart

Примеры использования

1. Базовые операции

В результате выполнения этого кода каждый раз будет выводиться время с точностью до секунд. Однако обновляться оно будет раз в 5 секунд, пока не очистится кэш. В данном примере проиллюстрированы самые простые операции, но в производительности мы скорее потеряем, чем выиграем. Ведь нам каждый раз придётся подключаться к серверу…

2. Повышаем производительность

2.1 С кэшированием

В данном примере приведена функция, которая создаёт изображение размером 800×600 и расставляет на нём 10 000 точек. Один раз, сгенерировав такое изображение, в дальнейшем мы лишь выводим его на экран, не генерируя заново.

2.2 Без кэширования

Тут всё гораздо проще и привычней: генерируем изображение каждый раз заново.

Результаты

Я протестировал оба скрипта на производительность. Одна и та же машина в первом случае выдала 460 ответов в секунду, а во втором лишь 10. Чего и следовало ожидать.
cmemcache requires php memcache extension to be loaded

Ещё несколько полезных функций

addServer — в случае, если у вас в распоряжении несколько кэширующих серверов, вы можете создать некий кластер, добавляя сервера в пул. Следует обратить внимание на параметр weight. Он указывает на то, сколько памяти вам будет доступно на конкретном сервере.
delete — из названия понятно, что данный метод удаляет из кэша объект с заданным ключом.
replace — заменяет значение объекта с заданным ключом. Используйте в случае, если Вам понадобится изменить содержимое объекта, раньше чем истечёт время его жизни.

С моей точки зрения, применять кэширование стоит только на высоконагруженных ресурсах. Ведь каждый раз, подключаясь к серверу Memcached, вы тратите драгоценное время, что скорее всего не будет оправданным. Что касается больших проектов, лучше сразу написать больше строк кода, чем потом делать это в попыхах, с мыслью о том, что ваш сервис лежит. Также не стоит забывать о расходовании памяти! Учтите, что положив 300 мегабайт в кэш, вы отняли у себя 300 мегабайт ОЗУ.
В завершение хочу сказать, что данная статья не раскрывает все прелести технологии, однако я надеюсь, что она стимулирует Вас к самосовершенствованию. Спасибо за прочтение, многоуважаемый %username%!

UPD: Ещё один интересный момент. Memcached, есть PHP API к libmemcached. А Memcache, библиотека для php, не использующая libmemcached.

Источник

Как включить кэширование rbac?

Я пробовал использовать данный пример https://habrahabr.ru/post/251847/ кэширование rbac
Но у меня вышло после такого кода common/config/main.php

И пишет проблему ApcCache requires PHP apc extension to be loaded.
Как я понял там там нет этого расширение и второй момент как его загрузить.
Я уже зашел на сайт www.php.net/apc, мне нужно что-то установить как понимаю и второй момент как это потом передать на хостинг?
И у меня версия php 5.6

cmemcache requires php memcache extension to be loaded

slo_nik: Ну я как бы как в документации и сделал, скачал архив, файл php_apcu.dll поместил в директорию C:\openserver\modules\php\PHP-5.6-x64\ext
Зашел в конфигурации PHP-5.6-x64_php.ini и добавил

И все равно ничего не выходит

cmemcache requires php memcache extension to be loaded

cmemcache requires php memcache extension to be loaded

hollanditkzn:
А текст ошибки в google?
Перезагрузка сервера после подключения?

Warning: You cannot install APC and Zend Optimiser on the same server. You should choose one or the other.

cmemcache requires php memcache extension to be loaded

cmemcache requires php memcache extension to be loaded

Не советую пользоваться Windows для запуска PHP. Попробуй запускать код в виртуалке: это легче, чем бороться с Windows.

Источник

Cannot use memcached at php 7.0 because of missing Memcache #100

Comments

pohlaniacz commented Aug 31, 2017

Hi, I can’t install php5-memcache because it’s not available at Debian with php 7.0, so I’m getting an error «Memcache extension is not loaded! To configure pools it MUST be loaded!». Of course memcached extensions is loaded properly, how can I fix/bypass this?

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

mevdschee commented Aug 31, 2017

@pohlaniacz I’m afraid you can’t because there is a memcache and a memcached (with a «d») extension. The memcached extension is not supported. You may have to install the memcache extension via PECL.

pohlaniacz commented Aug 31, 2017

skoop commented Mar 26, 2018

I’m running into this as well, and installing memcache via PECL seems to not be that easy on PHP 7.1. Given the memcache extension is sort of deprecated, is there any chance of a newer version of this bundle using memcached?

mevdschee commented Mar 26, 2018 •

Given the memcache extension is sort of deprecated

Is it? Do you have a reference?

any chance of a newer version of this bundle using memcached?

I tried hard to implement it, but without much luck. Some of the object interfaces of memcached are not fully PHP compatible (parameters that are references and optional if I recall correctly).

I think you are better of with memcache than with memcached. Also memcached does (or at least did) not support windows users (AFAIK).

skoop commented Mar 26, 2018

memcache extension is not packaged with PHP anymore, and if you try to build it on PHP 7.1 you get errors because some PHP header files are renamed in PHP7.

For now I’ve solved the problem by using a fork of the memcache extension that is still maintained (https://github.com/websupport-sk/pecl-memcache) but as you can see from the official PECL page the last release was in 2013: http://pecl.php.net/package/memcache.

This means I’ve now been able to upgrade our development docker containers to PHP 7.1 with the above memcache extension, but I’m not sure if our sysadmins will be willing to upgrade production to such a fork.

Memcached on the other hand still has a recent release (and pretty regular updates anyway): http://pecl.php.net/package/memcached

It might be worth looking at re-implementing Memcached support. I’ve unfortunately not got enough time for it in the upcoming weeks to have a look at this but will see if my client has some time to free up to experiment with this.

mevdschee commented Mar 26, 2018 •

memcache extension is not packaged with PHP anymore

Nor is or was the php memcached extension.

Memcached on the other hand still has a recent release

But is notoriously known for it’s bad support on Windows.

It might be worth looking at re-implementing Memcached support.

AFAIK distributions (such as Debian and Centos) have chosen to build and include the beta versions (of php-memcache). So IMHO you better invest time in getting official builds of php-memcache out, then to rework this package from one sub-par dependency to the other. Honest advice, really 🙂

Источник

require memcached php extension? #5

Comments

dinamic commented Apr 16, 2013

I’ve tried to install the bundle, but it seems the memcached php extension is a requirement.

What about the users of a shared hosting that does not provide memcached extension?

IMHO this should be a suggestion rather than requirement.

The requirement has to be set for the ext-memcache, which provides the Memcache class.

The text was updated successfully, but these errors were encountered:

We are unable to convert the task to an issue at this time. Please try again.

The issue was successfully created but we are unable to update the comment at this time.

mevdschee commented Apr 18, 2013

Basically you are asking for support for both the memcached and the memcache (without d) extension? Maybe we can add a fallback to a PHP based solution and include that in the bundle? Good feature request, thank you.

dinamic commented Apr 24, 2013

Until this is done we should consider the bundle as OS dependent.

The php_memcached extension relies on the libmemcached library which hasn’t been ported to the Windows OS yet.

mevdschee commented Apr 24, 2013

Yes, the bundle requires the «memcached» PHP extension that is indeed not binary downloadable for Windows. If you need support for this extension on Windows you should ask the PHP maintainers / package builders to include the memcached extension in the Windows builds.

Since your enhancement request for this bundle will lead to a sub-optimal workaround for the unavailability of binary builds of that extension on Windows I will close the enhancement requests regarding the bundle. If your request for inclusion of the «memcached» extension in the Windows PHP builds has failed, you may reopen the request.

At that point, with the reason they can not or do not want to included the extension in the Windows PHP builds, we can see what we can do to change their minds. I read that there are no compilation instructions available for libmemcached on Windows, maybe you ask the maintainers of the libmemcached library to make those. That would be a good first step to persuade the PHP maintainers to include the extension in their builds.

Thank you in advance for your further investigation into this matter and your efforts to improve the open source community.

Источник

Unable to load memcache.so extension

I built PHP from source with configure command

I installed php memcache extension :

I add to my /usr/local/lib/php.in

Rebooted my apache and run php-m but php seem doesn’t load memcache extension I followed this solution from this site http://www.howtoforge.com/forums/showthread.php?t=26554

7 Answers 7

Firstly run your php binary like

It should complain that your php.ini wants to load modules that cant be loaded.

If it doesnt complain, run

This should give you the location of your php.ini ( just incase your editing the wrong one 😀 )

After you extract the file, you will get the latest version of memcache, at the time I do this, I get the folder memcache-3.0.8.

So, the next steps will be:

And restart Apache.

cmemcache requires php memcache extension to be loaded

Are you sure memcached is installed in the correct location? What do you get if you run: locate memcache.so

Is memcached installed (the binary)? Does it require any extra libraries (libmemcache)?

Add an extension_dir directive to tell PHP where to load extensions from and remove the path from the extension directive.

One thing that helped me is to use

Another thing (this applies only to rather old php versions though): http://www.hollub.at/phpmanual/ref.memcache.html says:

this is because of your /var/tmp mounted with noexec permission

you can try to recompile memcache using fuenfundachtzig command after temporarily delete /var/tmp symlink and create new /var/tmp folder. (this setting maybe differ from your server)

then secure back your temp folder

read more about securing tmp here

If you have your PHP compiled, try to remove extension_dir from your php.ini.

Not the answer you’re looking for? Browse other questions tagged memcached or ask your own question.

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *