Memcache - высокопроизводительная система хранения данных в оперативной памяти сервера, применяющаяся, как правило, на высоконагруженных проектах. Memcached целесообразно использовать в случаях повышенной нагрузки на MySQL и дисковую подсистему. Высокая производительность кэширования достигается благодаря тому, что все данные хранятся в оперативной памяти, и для доступа к ним не требуется обращения к дисковой подсистеме. На хостинге «Джино» Memcached развернута на отдельных серверах, соединенных с серверами пользовательских сайтов гигабитной сетью. Все это обеспечивает высокую скорость доступа к кэшу, не нагружая ресурсы основных серверов.
Устанавливаем Memcached и связанные пакеты
Yum -y install memcached
Редактируем файл /etc/sysconfig/memcached:
PORT="11211" USER="memcached" MAXCONN="2048" CACHESIZE="4096" OPTIONS="-l 127.0.0.1"
Сохраняем настройки и перезапускаем Memcached
Systemctl restart memcached
Systemctl start memcached
Добавляем в автозагрузку
Systemctl enable memcached
Проверяем текущий статус
Systemctl status memcached
Для остановки используем
Systemctl stop memcached
Устанавливаем php-pecl-memcached
Yum -y install php-pecl-memcached
Перезапускаем apache
Systemctl restart httpd
Для просмотра свободного и занятого места на разделах диска в Linux можно воспользоваться командой df. Для просмотра размеров папок на диске используется команда du.
В этом руководстве мы покажем вам, как обновить ImageMagick с 6.7 до 7.0 в Centos 7
Как проверить номер мобильного телефона? Проверка правильности, введенного номера телефона является не сложной, но важной задачей. Если пользователь введет некорректный номер, то смс сообщение до него не дойдет.
M emcache является ключевой частью инфраструктуры для многих приложений. Базы данных, очереди и удаленные сервисы часто являются узким местом веб-запросов, но во многих случаях информация, которую они содержат не меняется. Memcache является стандартным демоном, который может кэшировать произвольные значения, и может ускорить все от запросов MySQL до запросов к REST.
Для завершения этого руководства, вам потребуется следующее:
Когда мы закончили, стек LAMP будет увеличен с Memcache, и вы можете начать интегрировать его в существующие сайты и приложения.
Для начала, мы установим пакет Memcached .
Yum -y install memcached
Пакет теперь установлен, но он также должен быть запущен. Мы также должны настроить его для запуска при загрузке системы.
Systemctl start memcached.service systemctl enable memcached.service
Теперь Memcached должен быть настроен для оптимального использования. Мы позаботимся о том.
Nano /etc/sysconfig/memcached
Вы хотите выделить память для Memcached? Это достигается путем изменения значения CACHESIZE, установив его на желаемое количество оперативной памяти, выделенной для кэша.
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="64"
OPTIONS=""
Так как вы только изменили конфигурацию, вам необходимо перезапустить Memcached чтобы новые значения вступили в силу.
Systemctl restart memcached.service
Чтобы использовать Memcached из PHP, требуется расширение. Мы установим в следующем примере.
Yum -y install php-pecl-memcache
Теперь, когда PHP был обновлен, вам необходимо перезапустить Apache. Кроме того, перезапустите Memcached.
Systemctl restart httpd.service systemctl restart memcached.service
Давайте проверим загрузку модуля Memcached.
Php -m | grep memcache memcache
Для дальнейшего проверки состояния модуля, мы создадим информационную страницу PHP. Эта функция возвращает информацию о конфигурации окружающей среды PHP. Если Memcached настроен правильно, он будет включать в себя подробную информацию о поддержки Memcached.
Nano /var/www/html/index.php
Теперь мы, наконец, проверим состояние модуля Memcached в PHP. Посетите страницу, которую вы только что создали по адресу: http://your_main_ip/index.php
Memory object caching systems like Memcached can optimize backend database performance by temporarily storing information in memory, retaining frequently or recently requested records. In this way, they reduce the number of direct requests to your databases.
Because systems like Memcached can contribute to denial of service attacks if improperly configured, it is important to secure your Memcached servers. In this guide, we will cover how to protect your Memcached server by binding your installation to a local or private network interface and creating an authorized user for your Memcached instance.
This tutorial assumes that you have a server set up with a non-root sudo user and a basic firewall. If that is not the case, set up and install the following:
With these prerequisites in place, you will be ready to install and secure your Memcached server.
If you don"t already have Memcached installed on your server, you can install it from the official CentOS repositories. First, make sure that your local package index is updated:
Next, install the official package as follows:
We can also install libmemcached , a library that provides several tools to work with your Memcached server:
Memcached should now be installed as a service on your server, along with tools that will allow you to test its connectivity. We can now move on to securing its configuration settings.
To ensure that our Memcached instance is listening on the local interface 127.0.0.1 , we will modify the OPTIONS variable in the configuration file located at /etc/sysconfig/memcached . We will also disable the UDP listener. Both of these actions will protect our server from denial of service attacks.
You can open /etc/sysconfig/memcached with vi:
Locate the OPTIONS variable, which will initially look like this:
/etc/sysconfig/memcached
OPTIONS=""
Binding to our local network interface will restrict traffic to clients on the same machine. We will do this by adding -l 127.0.0.1 to our OPTIONS variable. This may be too restrictive for certain environments, but it can make a good starting point as a security measure.
Because UDP protocol is much more effective for denial of service attacks than TCP, we can also disable the UDP listener. To do this, we will add the -U 0 parameter to our OPTIONS variable. The file in full should look like this:
/etc/sysconfig/memcached
PORT="11211" USER="memcached" MAXCONN="1024" CACHESIZE="64" OPTIONS="-l 127.0.0.1 -U 0 "
Save and close the file when you are done.
Restart your Memcached service to apply your changes:
Verify that Memcached is currently bound to the local interface and listening only for TCP connections by typing:
You should see the following output:
Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name . . . tcp 0 0 127.0.0.1 :11211 0.0.0.0:* LISTEN 2383/memcached . . .
This confirms that memcached is bound to the 127.0.0.1 address using only TCP.
To add authenticated users to your Memcached service, it is possible to use Simple Authentication and Security Layer (SASL), a framework that de-couples authentication procedures from application protocols. We will enable SASL within our Memcached configuration file and then move on to adding a user with authentication credentials.
We can first test the connectivity of our Memcached instance with the memstat command. This will help us establish that SASL and user authentication are enabled after we make changes to our configuration files.
To check that Memcached is up and running, type the following:
Now we can move on to enabling SASL. First, we can add the -S parameter to our OPTIONS variable in /etc/sysconfig/memcached , which will enable SASL. Open the file again:
We will add both the -S and -vv parameters to our OPTIONS variable. The -vv option will provide verbose output to /var/log/memcached , which will help us as we debug. Add these options to the OPTIONS variable as follows:
/etc/sysconfig/memcached
OPTIONS="-l 127.0.0.1 -U 0 -S -vv "
Save and close the file.
Next, we can take a look at the logs to be sure that SASL support has been enabled:
You should see the following line, indicating that SASL support has been initialized:
Mar 05 18:16:11 memcached-server memcached: Initialized SASL. . . .
We can check the connectivity again, but because SASL has been initialized, this command should fail without authentication:
This command should not produce output. We can type the following to check its status:
$? will always return the exit code of the last command that exited. Typically, anything besides 0 indicates process failure. In this case, we should see an exit status of 1 , which tells us that the memstat command failed.
Now we can download two packages that will allow us to work with the Cyrus SASL Library and its authentication mechanisms, including plugins that support PLAIN authentication schemes. These packages, cyrus-sasl-devel and cyrus-sasl-plain , will allow us to create and authenticate our user. Install the packages by typing:
Next, we will create the directory and file that Memcached will check for its SASL configuration settings:
Add the following to the SASL configuration file:
/etc/sasl2/memcached.conf
Mech_list: plain log_level: 5 sasldb_path: /etc/sasl2/memcached-sasldb2
In addition to specifying our logging level, we will set mech_list to plain , which tells Memcached that it should use its own password file and verify a plaintext password. We will also specify the path to the user database file that we will create next. Save and close the file when you are finished.
Now we will create a SASL database with our user credentials. We will use the saslpasswd2 command to make a new entry for our user in our database using the -c option. Our user will be sammy here, but you can replace this name with your own user. Using the -f option, we will specify the path to our database, which will be the path we set in /etc/sasl2/memcached.conf:
Finally, we want to give the memcached user ownership over the SASL database:
Restart the Memcached service:
Running memstat again will confirm whether or not our authentication process worked. This time we will run it with our authentication credentials:
You should see output like the following:
Server: 127.0.0.1 (11211) pid: 3831 uptime: 9 time: 1520028517 version: 1.4.25 . . .
Our Memcached service is now successfully running with SASL support and user authentication.
We have covered how to configure Memcached to listen on the local interface, which can prevent denial of service attacks by protecting the Memcached interface from exposure to outside parties. There may be instances where you will need to allow access from other servers, however. In this case, you can adjust your configuration settings to bind Memcached to the private network interface.
Note:
We will cover how to configure firewall settings using FirewallD
in this section, but it is also possible to use DigitalOcean Cloud Firewalls to create these settings. For more information on setting up DigitalOcean Cloud Firewalls, see our . To learn more about how to limit incoming traffic to particular machines, check out the section of this tutorial on and our discussion of .
Before you adjust your configuration settings, it is a good idea to set up firewall rules to limit the machines that can connect to your Memcached server. If you followed the prerequisites and installed FirewallD on your server and do not plan on connecting to Memcached from another host, then you do not need to adjust your firewall rules. Your standalone Memcached instance should be listening on 127.0.0.1 , thanks to the OPTIONS variable we defined earlier, and there should therefore be no concerns about incoming traffic. If you plan to allow access to your Memcached server from other hosts, however, then you will need to make changes to your firewall settings using the firewall-cmd command.
Begin by adding a dedicated Memcached zone to your firewalld policy:
Then, specify which port you would like to keep open. Memcached uses port 11211 by default:
Next, specify the private IP addresses that should be allowed to access Memcached. For this, you will need to know your client server"s private IP address :
Reload the firewall to ensure that the new rules take effect:
Packets from your client"s IP address should now be processed according to the rules in the dedicated Memcached zone. All other connections will be processed by the default public zone.
With these changes in place, we can move on to making the necessary configuration changes to our Memcached service, binding it to our server"s private networking interface.
The first step in binding to our server"s private networking interface will be modifying the OPTIONS variable we set earlier.
We can open /etc/sysconfig/memcached again by typing:
Inside, locate the OPTIONS variable. We can now modify -l 127.0.0.1 to reflect our Memcached server"s private IP:
/etc/sysconfig/memcached
OPTIONS="-l memcached_servers_private_IP -U 0 -S -vv"
Save and close the file when you are finished.
Restart the Memcached service again:
Check your new settings with netstat to confirm the change:
Test connectivity from your external client to ensure that you can still reach the service. It is a good idea to also check access from a non-authorized client to ensure that your firewall rules are effective.
In this tutorial we have covered how to secure your Memcached server by configuring it to bind to your local or private network interface, and by enabling SASL authentication.
Memcached — это система которая кеширует все данные в память. Это означает, что вы можете генерировать кэш самым быстрым способом что позволит быстрее использовать приложения с самыми современными языками программирования, таких как Python, PHP, Ruby, и т.д. В своей теме «Установка memcached в Unix/Linux(CentOS/Debian/Ubuntu)» я расскажу как можно установить memcached на Unix/Linux и на готовом примере, покажу как я это делал. Для тестирования, я выбрал CentOS 6 и Debian 8.
$ sudo apt-get update
Теперь используйте следующую команду для установки Memcached:
$ sudo apt-get install memcached
Теперь я установлю PHP с несколькими необходимыми пакетами:
# apt-get install php5 php5-dev php-pear php5-memcached
Также необходимо установить модуль MemCache для PHP:
# apt-get install libmemcached-dev build-essential
Наконец выполняем установку расширения Memcache php с помощью PECL:
# pecl install memcache
Теперь включим поддержку MemCache в PHP. Прежде чем создавать новый файл просто убедитесь, возможно он уже существует и если файл уже существует просто пропустите команду что ниже:
$ echo "extension=memcache.so" > /etc/php5/apache2/conf.d/20-memcache.ini
После всех изменений, производим перезапуск службы Apache:
# service apache2 restart
Для начала, обновим ОС:
# yum update
После обновления, выполняем установку memcached:
# yum install memcached
Отредактируем файл:
$ vim /etc/sysconfig/memcached
Убедитесь, что в данном файле конфигурации имеются следующие строки:
PORT="11211" USER="memcached" MAXCONN="256" CACHESIZE="64" OPTIONS="-l 127.0.0.1"
PORT 11211
является портом прослушивания по умолчанию для Memcached.
USER
— это пользователь memcached от которого будет запущен демон.
MAXCONN
— максимальные количество возможных соединений.
CACHESIZE
— это количество мегабайт (64 MB) для использования, если у вас есть много трафика, это хорошо для большинства малых/средних сайтов. Для загруженного сервера вы можете увеличить его на 512 или 1 Гб (1024 MB).
OPTIONS=»-l 127.0.0.1″
— это означает что memcached будет слушать только на localhost-е, избегая каких-либо внешних подключений. Вы можете установить IP-адрес сервера. По умолчанию он установлен в INADDR_ANY. Это важно опция, поскольку нет никакого другого способа обеспечить установку. Привязка к внутреннему или межсетевому интерфейсу предлагается.
Для CentOS/RHEL 6/5:
запуск Memcached выполняется:
# service memcached start
Пропишем memcached в загрузку ОС:
# chkconfig memcached on
Для CentOS/RHEL 7:
# systemctl enable memcached # systemctl start memcached
Устновка PHP расширений с Memcached.
выполняем:
# yum install php-pear pecl_http php-devel
И выполняем:
$ pecl install memcache
Если PECL при установке задаст вам вопрос, который вы видите ниже, просто нажмите ENTER:
"Enable memcache session handler support? "
У меня возникла ошибка:
ERROR: `/var/tmp/memcache/configure --enable-memcache-session=yes" failed
Исправляем:
# yum install libmemcached libmemcached-devel
Получил следующую:
Checking for zlib location... configure: error: memcached support requires ZLIB. Use --with-zlib-dir=
# yum install zlib zlib-devel
Добавим модуль memcache.so module в php.ini
# echo "extension=memcache.so" >> /etc/php.ini
Перезапускаем службы.
Если на вашем сервере установлен php-fpm, то чтобы перезапустить его, выполните:
# service php-fpm reload
Если на вашем сервере установлен apache, то чтобы перезапустить его, выполните:
Для CentOS/RHEL 7:
# systemctl restart httpd
Для CentOS/RHEL 6/5:
# service httpd restart
Использование следующую команду, чтобы проверить и убедиться, что Memcached служба работает нормально:
$ echo "stats settings" | nc localhost 11211
Теперь нужно проверить, включено ли расширение и удостоверимся что работает правильно. Создайте файл в домашнем каталоге и пропишите следующий ПХП код:
# echo "" > /var/www/html/php_info.php
Если открыть сайт, то увидим:
Проверьте, установлен ли Memcached как модуль PHP:
# php -i | grep memcache -i
Добавьте слудеющие правила для разрешения соедения (для работы memcached):
Iptables -A INPUT -p tcp --destination-port 11211 -m state --state NEW -m iprange --src-range 192.168.1.10-192.168.1.15 -j ACCEPT iptables -A INPUT -p udp --destination-port 11211 -m state --state NEW -m iprange --src-range 192.168.1.10-192.168.1.15 -j ACCEPT
Проверяем, запущен ли демон memcached на ОС:
$ ps -aux | grep memcached
На этом, статья «Установка memcached в Unix/Linux(CentOS/Debian/Ubuntu)» завершена.
Memcached - программное обеспечение, реализующее сервис кэширования данных в оперативной памяти на основе хеш-таблицы.
Memcached - система кэширования в оперативной памяти, обладающая высокой производительностью, которая используется в основном для ускорения сайтов, которые интенсивно используют базу данных.
Большинство современных языков программирования поддерживают библиотеки Memcached , в том числе PHP , Perl , Ruby и Python . Memcached работает в ОЗУ, потому обмен данными происходит практически мгновенно.
PORT
: Порт по умолчанию для использования Memcached.
USER
: Пользователь от которого запущен Memcached.
MAXCONN
: Максимальное количество соединений Memcached.
CACHESIZE
: Размер кеша для памяти.
OPTIONS
: Установите IP-адрес сервера, чтобы веб-серверы Apache или Nginx могли подключаться к нему.
После перезапускаем сервис systemctl restart memcached .
Добавляем сервис в автозапуск systemctl enable memcached .