Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Install Memcached on CentOS 7

Last modified on April 16, 2019 1 min read

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 [email protected] -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=""

Start the Memcached:

sudo systemctl start memcached.service

Enable on server reboot:

sudo systemctl enable memcached.service

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.service

Check remote connectivity:

sudo echo stats | nc memcache_host_name_or_ip 11211

Step 4 : Install Memcached PHP Module

We need to install Memcached PHP module to work with PHP:

sudo yum install php php-pecl-memcached

Now restart Memcached and Web server:

# Memcached
sudo systemctl restart memcached.service

# Web server
sudo systemctl restart httpd.service

Now check phpinfo().

Step 5 : Store and Fetch Data

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. 🙂

You're welcome to suggest any article to write!

Md Obydullah Follow I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and web development.

Leave a Reply

Your email address will not be published. Required fields are marked *