Memcached is a high-performance, distributed memory object caching system. It is used to speed up dynamic web applications by reducing the database load. Memcached caches objects (such as strings, JSON data, or serialized objects) in memory so that subsequent requests can fetch data directly from memory instead of querying the database or performing expensive computations.
This tutorial will cover the basics of installing and using Memcached.
—
### 1. **Installing Memcached**
#### On Ubuntu/Debian:
“`bash
sudo apt update
sudo apt install memcached
sudo apt install libmemcached-tools # Optional, but useful for testing
“`
#### On CentOS/RHEL:
“`bash
sudo yum install memcached
sudo yum install libmemcached # Optional
“`
#### On macOS (using Homebrew):
“`bash
brew install memcached
“`
#### Windows:
For Windows, Memcached isn’t natively supported. However, you can use Windows Subsystem for Linux (WSL) or install it using third-party ports, such as from [MemcachedWin](https://github.com/memcached/memcached/wiki/Download#memcached-for-windows).
—
### 2. **Starting Memcached**
After installation, you can start Memcached:
#### On Ubuntu/Debian:
“`bash
sudo systemctl start memcached
sudo systemctl enable memcached # To start it on boot
“`
#### On CentOS/RHEL:
“`bash
sudo systemctl start memcached
sudo systemctl enable memcached
“`
#### On macOS:
“`bash
memcached -d
“`
By default, Memcached runs on **port 11211** and binds to the local interface (localhost).
—
### 3. **Basic Memcached Commands**
Memcached provides a simple text-based protocol to interact with it. You can use the **`telnet`** command to connect to the Memcached server and interact with it.
“`bash
telnet localhost 11211
“`
Once connected, you can use the following basic commands:
#### **SET** – Store a value:
“`bash
set key 0 900 5
hello
“`
– `key`: The key under which the data is stored.
– `0`: Flags, used for storing additional data (usually not used).
– `900`: Expiration time in seconds (900 seconds = 15 minutes).
– `5`: The length of the data you’re storing (in this case, 5 characters).
– `hello`: The value you’re storing.
#### **GET** – Retrieve a value:
“`bash
get key
“`
This will return:
“`
VALUE key 0 5
hello
END
“`
#### **DELETE** – Remove a value:
“`bash
delete key
“`
#### **INCR / DECR** – Increment or Decrement a numeric value:
“`bash
set counter 0 0 5
100
incr counter 2
get counter
“`
—
### 4. **Memcached with PHP**
PHP provides a Memcached extension for working with Memcached directly. Here’s how to install and use it.
#### Installing the PHP Memcached Extension:
“`bash
sudo apt install php-memcached
“`
#### Example PHP Code:
“`php
<?php
// Create a Memcached instance
$memcached = new Memcached();
// Add the server (localhost, port 11211)
$memcached->addServer(‘localhost’, 11211);
// Store data in Memcached
$memcached->set(‘user_1’, ‘John Doe’);
// Retrieve data from Memcached
$user = $memcached->get(‘user_1’);
if ($user) {
echo “User: ” . $user;
} else {
echo “User not found in cache”;
}
?>
“`
In this example:
– The `set` method stores the value `’John Doe’` with the key `’user_1’`.
– The `get` method retrieves the value associated with `’user_1’`.
—
### 5. **Memcached Configuration**
Memcached’s behavior can be controlled through its configuration file or startup options. Some key options include:
– **Memory Limit (`-m`)**: Controls the memory available for caching.
“`bash
memcached -m 512 # Allocate 512 MB of memory
“`
– **Port (`-p`)**: You can specify a custom port if you don’t want to use the default (11211).
“`bash
memcached -p 12345
“`
– **User (`-u`)**: Run Memcached as a specific user.
“`bash
memcached -u memcacheuser
“`
– **Daemon mode (`-d`)**: Run Memcached as a background process.
“`bash
memcached -d
“`
– **Listen on specific IP (`-l`)**: Specify a particular IP address to bind to.
“`bash
memcached -l 192.168.1.100
“`
– **Max Connections (`-c`)**: Set the maximum number of simultaneous connections.
“`bash
memcached -c 1024
“`
—
### 6. **Memcached with Other Languages**
#### Python (Using `pymemcache` or `python-memcached`):
Install `pymemcache` via pip:
“`bash
pip install pymemcache
“`
Example:
“`python
from pymemcache.client import base
client = base.Client((‘localhost’, 11211))
client.set(‘foo’, ‘bar’)
value = client.get(‘foo’)
print(value) # Output: b’bar’
“`
#### Node.js (Using `memcached` package):
Install the package:
“`bash
npm install memcached
“`
Example:
“`javascript
const Memcached = require(‘memcached’);
const memcached = new Memcached(‘localhost:11211’);
memcached.set(‘key’, ‘value’, 10, function (err) {
if (err) console.log(err);
});
memcached.get(‘key’, function (err, data) {
if (err) console.log(err);
console.log(data); // Output: value
});
“`
—
### 7. **Best Practices for Memcached**
– **Expiration Time**: Always set an expiration time for the cached data. This helps to avoid stale data and prevents your memory from getting filled up with obsolete objects.
– **Efficient Data Structures**: Memcached works best with simple key-value pairs. Complex data structures should be serialized, but always ensure that the size of the data is optimized.
– **Consistent Hashing**: In a distributed environment, use consistent hashing to ensure that data is evenly distributed across Memcached servers.
– **Eviction Policies**: Memcached uses an **LRU (Least Recently Used)** eviction policy when the memory limit is reached. Ensure that your memory usage is efficiently managed to avoid data being evicted too often.
– **Persistent Connections**: In some applications, maintaining a persistent connection to Memcached can reduce connection overhead and improve performance.
—
### Conclusion
Memcached is a powerful, fast caching system for improving the performance of your applications. By caching frequently requested data, Memcached reduces the load on your database and speeds up response times. Whether you’re using it with PHP, Python, Node.js, or other languages, Memcached’s simple API and high performance make it a popular choice for many developers.