Lua – Simple method to use Memcache

Published on Author gryzliLeave a comment

If you need fast and lightweight method of connecting with Memcache daemon, you can do it by just using the ‘socket’ module and open a TCP connection to the Memcache daemon. 

After you have your connection done to Memcache, you could issue all kind of commands for getting/storing information. 

 

Code

#!/usr/bin/lua
require 'socket'


function checkInMemcache (host,port,key)
        if host == nil or port == nil or key == nil then
                return nil
        end
        local timeout=1

        -- Connect to memcache
        local soc = socket.tcp()

        -- set timeout 
        soc:settimeout(timeout)

        -- Try to connect 
        if soc:connect(host, port) == nil then
                return nil

        end

        -- Now try to extract the key
        soc:send("get "..key.." \n")

        local data = {}
        while true do
                local line, err = soc:receive()
                if line == 'END' then
                    break
                elseif string.sub(line, 1, 5) == 'VALUE' then
                else
                    table.insert(data, line)
                end
        end

        if table.getn(data) == 0 then
                return nil
        end

         local datastring = table.concat(data, '\n')

         return datastring
end


checkInMemcache('127.0.0.1', 11211,'some_key')

 

The following piece of code (checkInMemcache) , could be used to make a simple check if a given key string exists in your Memcache. 

This could be easily extended to whatever your need is (setting,getting keys …). 

 

Dependencies:

You are going to need at least lua “socket” library in order to use this function. 

If you are using Centos, you can get ‘socket’ by installing the package: lua-socket

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *