Install Memcached on CentOS 7
In this tutorial, we will install Memcached on CentOS 7. Let’s follow these steps:
Step 1 : Login to Server
At first, we need to login to our server via SSH. Open your terminal and run this command:
ssh root@IPaddress -p PORT
Step 2 : Install and Configure Memcached
By using this command install Memcached:
sudo yum install memcached
Now configure is CACHESIZE (MB) and etc. by this command:
sudo nano /etc/sysconfig/memcached
PORT="11211"
USER="memcached"
MAXCONN="1024"
CACHESIZE="512"
OPTIONS="-l 127.0.0.1"
Start the Memcached:
sudo systemctl start memcached
Enable on server reboot:
sudo systemctl enable memcached
Confirm Memcached running:
sudo memcached-tool 127.0.0.1:11211 stats
Step 3 : Allow in Firewall
If you use Firewall then you need to add port to firewall:
sudo firewall-cmd --permanent --zone=public --add-port=11211/tcp
Restart firewall:
sudo systemctl restart firewalld
Check remote connectivity:
sudo echo stats | nc 127.0.01 11211
Step 4 : Install Memcached PHP Module
We need to install Memcached PHP module to work with PHP:
sudo yum install php-pecl-memcached
Now restart Memcached and Web server:
# Memcached
sudo systemctl restart memcached
# Web server
sudo systemctl restart nginx
sudo systemctl restart httpd
Now check phpinfo().
Step 5 : Store and Fetch Data
If SELinux is enabled, we’ve to run this command to work Memcached in PHP file:
setsebool -P httpd_can_network_connect on
Now create a file named cache.php
and paste this code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');
$memcacheD = new Memcached;
$memcacheD->addServer('localhost', 11211) or die ("Unable to connect");
$cache_name = "test_mc_1";
$expire_time = 10;
$data = $memcacheD->get($cache_name);
if (!$data){
echo 'Cache miss!<br/>';
$data = Date("d M, Y - h:i:s");
$memcacheD->set($cache_name, $data, $expire_time) or die ("Unable to save data in the cache");
}
echo $data;
Thank you.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.