Open In App

PHP memcached

Last Updated : 03 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Cache has an important role in system design whenever it comes to the key-value store with a very less fetch time. So to remove database latency we all use cache memory which is a bit volatile but is highly available and it’s easy to use as a session store and similar use case.

The Memcached is a type of cache which is a highly-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

It works with libMemcached, which is designed to provide the greatest number of options to use Memcached. Some of the features provided:

  • Asynchronous and Synchronous Transport Support.
  • Consistent Hashing and Distribution.
  • Tunable Hashing algorithm to match keys.
  • Access to large object support.
  • Local replication.
  • A complete reference guide and documentation to the API.
  • Tools to Manage your Memcached networks

Installation on ubuntu: To install Memcached on Ubuntu, go to terminal and type the following commands −

$sudo apt-get update
$sudo apt-get install memcached

Example:

PHP




<?php
   
echo "<pre>";
 
// Server & port details
$server = '127.0.0.1';
$port = 11211;
 
// Initiate a new object of memcache
$memcacheD = new Memcached();
 
// Add server
if ($memcacheD->addServer($server, $port)) {
    echo "**  server added ** \n";
}
else {
    echo "** issue while creating a server **\n";
}
 
// Set key & value with TTL
$key = "GEEKSFORGEEKS";
$value = "computer science portal";
$ttl = 3600;
if ($memcacheD->add($key, $value, $ttl))
      echo "** added key-value (" . $key . ":"
      . $value . ")to cache successfully!! **\n";
else
      echo "** error while adding value to cache!! **\n";
 
// Get value of key
echo "****   FETCHED VALUE   FOR KEY :"
              . $key . " ****\n";
 
$valD = $memcacheD->get($key);
var_dump($valD);
 
?>


Output:

**  server added ** ** added key-value (GEEKSFORGEEKS:computer science portal)to cache successfully!! ** ****   FETCHED VALUE   FOR KEY :GEEKSFORGEEKS **** string(23) “computer science portal”

Reference: https://www.php.net/manual/en/book.memcached.php



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads