This page looks best with JavaScript enabled

Memcached Server

 ·  🎃 kr0m

Memcached is an object storage system in RAM, widely used as a caching system in web servers, thus avoiding disk access since data is cached in RAM. Its main features are: Key/Value Maximum 250 characters as key and 1MB as value, TTL Expiration time of the key, after this time the key is deleted. If the RAM assigned to memcached is completely occupied, the oldest values will be automatically deleted.

NOT persistent The data is stored in RAM and is never dumped to disk.

To install it, it is as simple as:

emerge net-misc/memcached

We modify the config to indicate the RAM to use and the IP to listen on:

vi /etc/conf.d/memcached

# memcached config file

MEMCACHED_BINARY="/usr/bin/memcached"

# Specify memory usage in megabytes (do not use letters)
# 64MB is default
MEMUSAGE="500"

# User to run as
MEMCACHED_RUNAS="memcached"

# Specify maximum number of concurrent connections
# 1024 is default
MAXCONN="1024"

# Listen for connections on what address?
# If this is empty, memcached will listen on 0.0.0.0
# be sure you have a firewall in place!
LISTENON="A.B.C.D"

# Listen for connections on what port?
PORT="11211"

# Listen for UDP connecitons on what port? 0 means turn off UDP
UDPPORT="${PORT}"

# PID file location
# '-${PORT}.${CONF}.pid' will be appended to this!
# You do not normally need to change this.
PIDBASE="/var/run/memcached/memcached"

# Other Options
MISC_OPTS=""

NOTE: If the code that queries memcached is going to be on the same machine as memcached, I recommend binding memcached to the loopback and using the socket file to connect. This way, in addition to being more secure, it will be more efficient ;)

MISC_OPTS="-s /var/run/memcached/memcached.sock -a 755"

If, on the other hand, it is going to be an independent server, it will be necessary to assign iptables rules since memcached does not support any type of authentication.

We start the service and add it to the runlevel:

/etc/init.d/memcached start
rc-update add memcached default

With this simple Python script, we can check that our memcached is working correctly:

emerge dev-python/python-memcached

vi memcached.py

#! /usr/bin/python

import memcache
import time

s = memcache.Client(["A.B.C.D:11211"])

value=0
print "--------------------------------"
while True:
    print "Asignando Valor: " + str(value)
    s.set("AA", value, time=5)
    #time.sleep(6)
    value2 = s.get("AA")
    print "Value: " + str(value2)
    if (value == value2):
        print "++ Values match"
    else:
        print "++ Values DONT MATCH"

    value=value + 1
    print "--------------------------------"
    time.sleep(2)

If we uncomment the line time.sleep(6), we can see how the key has expired when we query it.

If you liked the article, you can treat me to a RedBull here