Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Setting Up Memcached

Introduction

Memcached is a high-performance, distributed memory object caching system used to speed up dynamic web applications by alleviating database load. This tutorial provides a step-by-step guide on how to set up Memcached on your server, whether it's a local environment or a cloud-based server.

Prerequisites

Before you begin, ensure that you have the following:

  • A server or local machine with a Linux-based operating system (e.g., Ubuntu, CentOS).
  • Root access or sudo privileges.
  • Basic knowledge of using the terminal.

Installing Memcached

To install Memcached, follow these steps based on your operating system:

On Ubuntu

sudo apt update
sudo apt install memcached libmemcached-dev

On CentOS

sudo yum install epel-release
sudo yum install memcached libmemcached

After running the above commands, you will have Memcached installed on your server.

Starting Memcached

Once installed, you can start Memcached using the following command:

sudo service memcached start

You can also enable Memcached to start on boot with:

sudo systemctl enable memcached

Configuring Memcached

Memcached's configuration file is typically located at /etc/memcached.conf. You can edit this file to customize various settings:

sudo nano /etc/memcached.conf

Some common configurations include:

  • -m: Amount of memory to allocate for caching (in MB).
  • -p: Port number on which Memcached listens (default is 11211).
  • -u: User under which Memcached should run.

After making changes, restart Memcached to apply them:

sudo service memcached restart

Testing Memcached

You can test if Memcached is running by using the telnet command:

telnet localhost 11211

If successful, you can now run Memcached commands. Try the following command to set a key:

set test_key 0 900 4
test

Then retrieve it with:

get test_key
VALUE test_key 0 4
test

Integrating Memcached with Your Application

Memcached can be integrated with various programming languages. Below is an example of how to use Memcached in a PHP application:

PHP Example:

<?php
$memcached = new Memcached();
$memcached->addServer('localhost', 11211);

// Set a value
$memcached->set('test_key', 'Hello, Memcached!');

// Get the value
$value = $memcached->get('test_key');

echo $value; // Outputs: Hello, Memcached!
?>

Conclusion

You've successfully set up Memcached on your server! This powerful caching solution can significantly improve the performance of your web applications. Explore various options and configurations to optimize it further based on your needs.