Memcached Installation and Configuration with PHP on Arch Linux

Memcached is “a free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load”.

Memcached’s APIs provide a giant hash table distributed across multiple machines. Memcached is used from Internet giants as YouTube, Reddit, Facebook, Twitter, Wikipedia and more.

Here is a guide to install and configure Memcached on Archlinux (used as development workstation). In next post I describe Memcached installation on a production Debian server.

Memcached installation

Using pacman:

sudo pacman -S memcached

the result is:

resolving dependencies...
looking for inter-conflicts...

Packages (1): memcached-1.4.15-1

Total Download Size:    0.05 MiB
Total Installed Size:   0.14 MiB

:: Proceed with installation? [Y/n] y
:: Retrieving packages ...
memcached-1.4.15-1-x86_64                             48.4 KiB  1309K/s 00:00 [#############################################] 100%
(1/1) checking keys in keyring                                                 [#############################################] 100%
(1/1) checking package integrity                                               [#############################################] 100%
(1/1) loading package files                                                    [#############################################] 100%
(1/1) checking for file conflicts                                              [#############################################] 100%
(1/1) checking available disk space                                            [#############################################] 100%
(1/1) installing memcached                                                     [#############################################] 100%
Optional dependencies for memcached
perl: for memcached-tool usage [installed]

Enable Memcached to run on system start-up

I suppose you are using systemd instead of initscripts

systemctl enable memcached.service

result

ln -s '/usr/lib/systemd/system/memcached.service' '/etc/systemd/system/multi-user.target.wants/memcached.service'

Start Memcached

Using systemd:

systemctl start memcached.service

Test Memcached is running

Using ps:

ps -eaf | grep memcached

the result is:

memcach+  4303     1  0 11:46 ?        00:00:00 /usr/bin/memcached -l 127.0.0.1
root      4388  3369  0 11:54 pts/0    00:00:00 grep memcached

or using netstat:

netstat -tap | grep memcached

the result is:

tcp        0      0 localhost.loca:memcache *:*                     LISTEN      4303/memcached

Inspecting Running Configuration

Using netcat (if it is not installed to your system: pacman -S gnu-netcat):

echo "stats settings" | nc localhost 11211

the result is:

STAT maxbytes 67108864
STAT maxconns 1024
STAT tcpport 11211
STAT udpport 11211
STAT inter 127.0.0.1
STAT verbosity 0
STAT oldest 0
STAT evictions on
STAT domain_socket NULL
STAT umask 700
STAT growth_factor 1.25
STAT chunk_size 48
STAT num_threads 4
STAT num_threads_per_udp 4
STAT stat_key_prefix :
STAT detail_enabled no
STAT reqs_per_event 20
STAT cas_enabled yes
STAT tcp_backlog 1024
STAT binding_protocol auto-negotiate
STAT auth_enabled_sasl no
STAT item_size_max 1048576
STAT maxconns_fast no
STAT hashpower_init 0
STAT slab_reassign no
STAT slab_automove 0
END

Memcached configuration

Memcached configuration file is /etc/conf.d/memcached

nano /etc/conf.d/memcached

By default it contains

# user to run memcached as; also used for pid file ownership
MEMCACHED_USER="memcached"
# see 'memcached -h' for available options
MEMCACHED_ARGS="-l 127.0.0.1 -t 1"

Default Memcached settings (on Arch) are

  • user for Memcached server: memcached (user has been created during installation with pacman)
  • -l 127.0.0.1 listen to localhost
  • -t 1 number of threads to use (default: 4)
  • default port is TCP 11211 (-p 11211 which is omitted)
  • 64 MB RAM assigned to Memcached (-m 64 which is omitted). This is the minimum RAM for Memcached

systemd Memcached service file is /usr/lib/systemd/system/memcached.service

By default it contains

[Unit]
Description=Memcached Daemon
After=network.target

[Service]
User=memcached
# Remove '-l 127.0.0.1' to listen on all addresses
ExecStart=/usr/bin/memcached -l 127.0.0.1

[Install]
WantedBy=multi-user.target

As you can see, systemd service file (/usr/lib/systemd/system/memcached.service) does not load user defined parameters from /etc/conf.d/memcached. See also this bug report.

So, you can modify it (see also this Github repo)

nano /usr/lib/systemd/system/memcached.service

as follows:

[Unit]
Description=Memcached Daemon
After=network.target

[Service]
EnvironmentFile=/etc/conf.d/memcached
ExecStart=/usr/bin/memcached -u $MEMCACHED_USER $MEMCACHED_ARGS

[Install]
WantedBy=multi-user.target

Then, modify /etc/conf.d/memcached according to your preferences.

Documentation is available here. See all availables options, using

memcached -h

So, to assign 1GB RAM to Memcached (1024 MB)

nano /etc/conf.d/memcached

add -m 1024 to MEMCACHED_ARGS

# user to run memcached as; also used for pid file ownership
MEMCACHED_USER="memcached"
# see 'memcached -h' for available options
MEMCACHED_ARGS="-m 1024 -l 127.0.0.1 -t 1"

Now

echo "stats settings" | nc localhost 11211

returns the following results

STAT maxbytes 1073741824
STAT maxconns 1024
STAT tcpport 11211
STAT udpport 11211
STAT inter 127.0.0.1
STAT verbosity 0
STAT oldest 0
STAT evictions on
STAT domain_socket NULL
STAT umask 700
STAT growth_factor 1.25
STAT chunk_size 48
STAT num_threads 1
STAT num_threads_per_udp 1
STAT stat_key_prefix :
STAT detail_enabled no
STAT reqs_per_event 20
STAT cas_enabled yes
STAT tcp_backlog 1024
STAT binding_protocol auto-negotiate
STAT auth_enabled_sasl no
STAT item_size_max 1048576
STAT maxconns_fast no
STAT hashpower_init 0
STAT slab_reassign no
STAT slab_automove 0
END

PHP memcached extension

There are two php extensions for Memcached: php-memcache and php-memcached. The second (php-memcached) is newer and probably preferable. See also this StackOverflow thread.

pacman -S php-memcached

the result is:

resolving dependencies...
looking for inter-conflicts...

Packages (2): libmemcached-1.0.16-1  php-memcached-2.1.0-1

Total Download Size:    0.36 MiB
Total Installed Size:   1.99 MiB

:: Proceed with installation? [Y/n] y
:: Retrieving packages ...
libmemcached-1.0.16-1-x86_64                         338.4 KiB  1709K/s 00:00 [#############################################] 100%
php-memcached-2.1.0-1-x86_64                          25.8 KiB  1985K/s 00:00 [#############################################] 100%
(2/2) checking keys in keyring                                                 [#############################################] 100%
(2/2) checking package integrity                                               [#############################################] 100%
(2/2) loading package files                                                    [#############################################] 100%
(2/2) checking for file conflicts                                              [#############################################] 100%
(2/2) checking available disk space                                            [#############################################] 100%
(1/2) installing libmemcached                                                  [#############################################] 100%
(2/2) installing php-memcached                                                 [#############################################] 100%

this will also create the php configuration file /etc/php/conf.d/memcached.ini

Edit this file

nano /etc/php/conf.d/memcached.ini

and uncomment

;extension=memcached.so

to

extension=memcached.so

Then restart Apache

systemctl restart httpd.service

phpinfo must contain something like this:

Simple test php script

This is a simple script to test basic Memcached functionality with PHP:

<?php
$mc = new Memcached();
$mc->addServer("127.0.0.1", 11211);

$result = $mc->get("test_key");

if($result) {
        echo $result;
} else {
        echo "No data on Cache. Please refresh page pressing F5";
        $mc->set("test_key", "test data pulled from Cache!") or die ("Failed to save data at Memcached server");
}
?>

Remarks

Restarting Apache web server will not affect data stored in Memcached memory.

Restarting Memcached server (moreover, on system restart) all data stored in Memcached memory will be lost.

There is an interesting fork of Memcached, named Memcached-dd, which can dump Memcached RAM data to disk and restore them from here. Take a look here.