• Stars
    star
    210
  • Rank 187,585 (Top 4 %)
  • Language
    Lua
  • Created almost 13 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Lua memcached client driver for the ngx_lua based on the cosocket API

Name

lua-resty-memcached - Lua memcached client driver for the ngx_lua based on the cosocket API

Table of Contents

Status

This library is considered production ready.

Description

This Lua library is a memcached client driver for the ngx_lua nginx module:

http://wiki.nginx.org/HttpLuaModule

This Lua library takes advantage of ngx_lua's cosocket API, which ensures 100% nonblocking behavior.

Note that at least ngx_lua 0.5.0rc29 or OpenResty 1.0.15.7 is required.

Synopsis

    lua_package_path "/path/to/lua-resty-memcached/lib/?.lua;;";

    server {
        location /test {
            content_by_lua '
                local memcached = require "resty.memcached"
                local memc, err = memcached:new()
                if not memc then
                    ngx.say("failed to instantiate memc: ", err)
                    return
                end

                memc:set_timeout(1000) -- 1 sec

                -- or connect to a unix domain socket file listened
                -- by a memcached server:
                --     local ok, err = memc:connect("unix:/path/to/memc.sock")

                local ok, err = memc:connect("127.0.0.1", 11211)
                if not ok then
                    ngx.say("failed to connect: ", err)
                    return
                end

                local ok, err = memc:flush_all()
                if not ok then
                    ngx.say("failed to flush all: ", err)
                    return
                end

                local ok, err = memc:set("dog", 32)
                if not ok then
                    ngx.say("failed to set dog: ", err)
                    return
                end

                local res, flags, err = memc:get("dog")
                if err then
                    ngx.say("failed to get dog: ", err)
                    return
                end

                if not res then
                    ngx.say("dog not found")
                    return
                end

                ngx.say("dog: ", res)

                -- put it into the connection pool of size 100,
                -- with 10 seconds max idle timeout
                local ok, err = memc:set_keepalive(10000, 100)
                if not ok then
                    ngx.say("cannot set keepalive: ", err)
                    return
                end

                -- or just close the connection right away:
                -- local ok, err = memc:close()
                -- if not ok then
                --     ngx.say("failed to close: ", err)
                --     return
                -- end
            ';
        }
    }

Back to TOC

Methods

The key argument provided in the following methods will be automatically escaped according to the URI escaping rules before sending to the memcached server.

Back to TOC

new

syntax: memc, err = memcached:new(opts?)

Creates a memcached object. In case of failures, returns nil and a string describing the error.

It accepts an optional opts table argument. The following options are supported:

  • key_transform

    an array table containing two functions for escaping and unescaping the memcached keys, respectively. By default, the memcached keys will be escaped and unescaped as URI components, that is

    memached:new{
        key_transform = { ngx.escape_uri, ngx.unescape_uri }
    }

Back to TOC

connect

syntax: ok, err = memc:connect(host, port)

syntax: ok, err = memc:connect("unix:/path/to/unix.sock")

Attempts to connect to the remote host and port that the memcached server is listening to or a local unix domain socket file listened by the memcached server.

Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method.

Back to TOC

sslhandshake

syntax: session, err = memc:sslhandshake(reused_session?, server_name?, ssl_verify?, send_status_req?)

Does SSL/TLS handshake on the currently established connection. See the tcpsock.sslhandshake API from OpenResty for more details.

Back to TOC

set

syntax: ok, err = memc:set(key, value, exptime, flags)

Inserts an entry into memcached unconditionally. If the key already exists, overrides it.

The value argument could also be a Lua table holding multiple Lua strings that are supposed to be concatenated as a whole (without any delimiters). For example,

    memc:set("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to

    memc:set("dog", "a kind of animal")

The exptime parameter is optional and defaults to 0 (meaning never expires). The expiration time is in seconds.

The flags parameter is optional and defaults to 0.

Back to TOC

set_timeout

syntax: ok, err = memc:set_timeout(timeout)

Sets the timeout (in ms) protection for subsequent operations, including the connect method.

Returns 1 when successful and nil plus a string describing the error otherwise.

Back to TOC

set_timeouts

syntax: ok, err = memc:set_timeouts(connect_timeout, send_timeout, read_timeout)

Sets the timeouts (in ms) for connect, send and read operations respectively.

Returns 1 when successful and nil plus a string describing the error otherwise.

set_keepalive

syntax: ok, err = memc:set_keepalive(max_idle_timeout, pool_size)

Puts the current memcached connection immediately into the ngx_lua cosocket connection pool.

You can specify the max idle timeout (in ms) when the connection is in the pool and the maximal size of the pool every nginx worker process.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Only call this method in the place you would have called the close method instead. Calling this method will immediately turn the current memcached object into the closed state. Any subsequent operations other than connect() on the current object will return the closed error.

Back to TOC

get_reused_times

syntax: times, err = memc:get_reused_times()

This method returns the (successfully) reused times for the current connection. In case of error, it returns nil and a string describing the error.

If the current connection does not come from the built-in connection pool, then this method always returns 0, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.

Back to TOC

close

syntax: ok, err = memc:close()

Closes the current memcached connection and returns the status.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

add

syntax: ok, err = memc:add(key, value, exptime, flags)

Inserts an entry into memcached if and only if the key does not exist.

The value argument could also be a Lua table holding multiple Lua strings that are supposed to be concatenated as a whole (without any delimiters). For example,

    memc:add("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to

    memc:add("dog", "a kind of animal")

The exptime parameter is optional and defaults to 0 (meaning never expires). The expiration time is in seconds.

The flags parameter is optional, defaults to 0.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

replace

syntax: ok, err = memc:replace(key, value, exptime, flags)

Inserts an entry into memcached if and only if the key does exist.

The value argument could also be a Lua table holding multiple Lua strings that are supposed to be concatenated as a whole (without any delimiters). For example,

    memc:replace("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to

    memc:replace("dog", "a kind of animal")

The exptime parameter is optional and defaults to 0 (meaning never expires). The expiration time is in seconds.

The flags parameter is optional, defaults to 0.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

append

syntax: ok, err = memc:append(key, value, exptime, flags)

Appends the value to an entry with the same key that already exists in memcached.

The value argument could also be a Lua table holding multiple Lua strings that are supposed to be concatenated as a whole (without any delimiters). For example,

    memc:append("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to

    memc:append("dog", "a kind of animal")

The exptime parameter is optional and defaults to 0 (meaning never expires). The expiration time is in seconds.

The flags parameter is optional, defaults to 0.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

prepend

syntax: ok, err = memc:prepend(key, value, exptime, flags)

Prepends the value to an entry with the same key that already exists in memcached.

The value argument could also be a Lua table holding multiple Lua strings that are supposed to be concatenated as a whole (without any delimiters). For example,

    memc:prepend("dog", {"a ", {"kind of"}, " animal"})

is functionally equivalent to

    memc:prepend("dog", "a kind of animal")

The exptime parameter is optional and defaults to 0 (meaning never expires). The expiration time is in seconds.

The flags parameter is optional and defaults to 0.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

get

syntax: value, flags, err = memc:get(key) syntax: results, err = memc:get(keys)

Get a single entry or multiple entries in the memcached server via a single key or a table of keys.

Let us first discuss the case When the key is a single string.

The key's value and associated flags value will be returned if the entry is found and no error happens.

In case of errors, nil values will be turned for value and flags and a 3rd (string) value will also be returned for describing the error.

If the entry is not found, then three nil values will be returned.

Then let us discuss the case when the a Lua table of multiple keys are provided.

In this case, a Lua table holding the key-result pairs will be always returned in case of success. Each value corresponding each key in the table is also a table holding two values, the key's value and the key's flags. If a key does not exist, then there is no responding entries in the results table.

In case of errors, nil will be returned, and the second return value will be a string describing the error.

Back to TOC

gets

syntax: value, flags, cas_unique, err = memc:gets(key)

syntax: results, err = memc:gets(keys)

Just like the get method, but will also return the CAS unique value associated with the entry in addition to the key's value and flags.

This method is usually used together with the cas method.

Back to TOC

cas

syntax: ok, err = memc:cas(key, value, cas_unique, exptime?, flags?)

Just like the set method but does a check and set operation, which means "store this data but only if no one else has updated since I last fetched it."

The cas_unique argument can be obtained from the gets method.

Back to TOC

touch

syntax: ok, err = memc:touch(key, exptime)

Update the expiration time of an existing key.

Returns 1 for success or nil with a string describing the error otherwise.

This method was first introduced in the v0.11 release.

Back to TOC

flush_all

syntax: ok, err = memc:flush_all(time?)

Flushes (or invalidates) all the existing entries in the memcached server immediately (by default) or after the expiration specified by the time argument (in seconds).

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

delete

syntax: ok, err = memc:delete(key)

Deletes the key from memcached immediately.

The key to be deleted must already exist in memcached.

In case of success, returns 1. In case of errors, returns nil with a string describing the error.

Back to TOC

incr

syntax: new_value, err = memc:incr(key, delta)

Increments the value of the specified key by the integer value specified in the delta argument.

Returns the new value after incrementation in success, and nil with a string describing the error in case of failures.

Back to TOC

decr

syntax: new_value, err = memc:decr(key, value)

Decrements the value of the specified key by the integer value specified in the delta argument.

Returns the new value after decrementation in success, and nil with a string describing the error in case of failures.

Back to TOC

stats

syntax: lines, err = memc:stats(args?)

Returns memcached server statistics information with an optional args argument.

In case of success, this method returns a lua table holding all of the lines of the output; in case of failures, it returns nil with a string describing the error.

If the args argument is omitted, general server statistics is returned. Possible args argument values are items, sizes, slabs, among others.

Back to TOC

version

syntax: version, err = memc:version(args?)

Returns the server version number, like 1.2.8.

In case of error, it returns nil with a string describing the error.

Back to TOC

quit

syntax: ok, err = memc:quit()

Tells the server to close the current memcached connection.

Returns 1 in case of success and nil other wise. In case of failures, another string value will also be returned to describe the error.

Generally you can just directly call the close method to achieve the same effect.

Back to TOC

verbosity

syntax: ok, err = memc:verbosity(level)

Sets the verbosity level used by the memcached server. The level argument should be given integers only.

Returns 1 in case of success and nil other wise. In case of failures, another string value will also be returned to describe the error.

Back to TOC

init_pipeline

syntax: err = memc:init_pipeline(n?)

Enable the Memcache pipelining mode. All subsequent calls to Memcache command methods will automatically get buffer and will send to the server in one run when the commit_pipeline method is called or get cancelled by calling the cancel_pipeline method.

The optional params n is buffer tables size. default value 4

Back to TOC

commit_pipeline

syntax: results, err = memc:commit_pipeline()

Quits the pipelining mode by committing all the cached Memcache queries to the remote server in a single run. All the replies for these queries will be collected automatically and are returned as if a big multi-bulk reply at the highest level.

This method success return a lua table. failed return a lua string describing the error upon failures.

Back to TOC

cancel_pipeline

syntax: memc:cancel_pipeline()

Quits the pipelining mode by discarding all existing buffer Memcache commands since the last call to the init_pipeline method.

the method no return. always succeeds.

Back to TOC

Automatic Error Logging

By default the underlying ngx_lua module does error logging when socket errors happen. If you are already doing proper error handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off ngx_lua's lua_socket_log_errors directive, that is,

    lua_socket_log_errors off;

Back to TOC

Limitations

  • This library cannot be used in code contexts like set_by_lua*, log_by_lua*, and header_filter_by_lua* where the ngx_lua cosocket API is not available.
  • The resty.memcached object instance cannot be stored in a Lua variable at the Lua module level, because it will then be shared by all the concurrent requests handled by the same nginx worker process (see http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker ) and result in bad race conditions when concurrent requests are trying to use the same resty.memcached instance. You should always initiate resty.memcached objects in function local variables or in the ngx.ctx table. These places all have their own data copies for each request.

Back to TOC

TODO

  • implement the memcached pipelining API.
  • implement the UDP part of the memcached ascii protocol.

Back to TOC

Author

Yichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc.

Back to TOC

Copyright and License

This module is licensed under the BSD license.

Copyright (C) 2012-2017, by Yichun "agentzh" Zhang (章亦春) [email protected], OpenResty Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Back to TOC

See Also

Back to TOC

More Repositories

1

openresty

High Performance Web Platform Based on Nginx and LuaJIT
C
12,431
star
2

lua-nginx-module

Embed the Power of Lua into NGINX HTTP servers
C
11,224
star
3

nginx-tutorials

Nginx Tutorials
Perl
2,864
star
4

lua-resty-redis

Lua redis client driver for the ngx_lua based on the cosocket API
Lua
1,893
star
5

openresty-systemtap-toolkit

Real-time analysis and diagnostics tools for OpenResty (including NGINX, LuaJIT, ngx_lua, and more) based on SystemTap
Perl
1,653
star
6

headers-more-nginx-module

Set, add, and clear arbitrary output headers in NGINX http servers
C
1,636
star
7

openresty.org

Code and data for the openresty.org site
HTML
1,262
star
8

luajit2

OpenResty's Branch of LuaJIT 2
C
1,229
star
9

echo-nginx-module

An Nginx module for bringing the power of "echo", "sleep", "time" and more to Nginx's config file
C
1,162
star
10

docker-openresty

Docker tooling for OpenResty
Dockerfile
934
star
11

redis2-nginx-module

Nginx upstream module for the Redis 2.0 protocol
C
902
star
12

lua-resty-limit-traffic

Lua library for limiting and controlling traffic in OpenResty/ngx_lua
Lua
815
star
13

lua-resty-core

New FFI-based API for lua-nginx-module
Lua
797
star
14

stream-lua-nginx-module

Embed the power of Lua into NGINX TCP/UDP servers
C
723
star
15

lua-resty-mysql

Nonblocking Lua MySQL driver library for ngx_lua or OpenResty
Lua
703
star
16

stapxx

Simple macro language extentions to systemtap
Perl
692
star
17

sregex

A non-backtracking NFA/DFA-based Perl-compatible regex engine matching on large data streams
C
616
star
18

lua-resty-upstream-healthcheck

Health Checker for Nginx Upstream Servers in Pure Lua
Lua
513
star
19

lua-resty-websocket

WebSocket support for the ngx_lua module (and OpenResty)
Lua
503
star
20

lua-upstream-nginx-module

Nginx C module to expose Lua API to ngx_lua for Nginx upstreams
C
499
star
21

srcache-nginx-module

Transparent subrequest-based caching layout for arbitrary nginx locations.
C
474
star
22

opm

OpenResty Package Manager
Lua
458
star
23

test-nginx

Data-driven test scaffold for Nginx C module and OpenResty Lua library development
Perl
438
star
24

lua-resty-lrucache

Lua-land LRU Cache based on LuaJIT FFI
Lua
437
star
25

lua-resty-string

String utilities and common hash functions for ngx_lua and LuaJIT
Lua
426
star
26

lua-resty-upload

Streaming reader and parser for http file uploading based on ngx_lua cosocket
Lua
401
star
27

set-misc-nginx-module

Various set_xxx directives added to nginx's rewrite module (md5/sha1, sql/json quoting, and many more)
C
388
star
28

drizzle-nginx-module

an nginx upstream module that talks to mysql and drizzle by libdrizzle
C
336
star
29

openresty-gdb-utils

GDB Utilities for OpenResty (including Nginx, ngx_lua, LuaJIT, and more)
Python
335
star
30

lua-resty-balancer

A generic consistent hash implementation for OpenResty/Lua
Lua
325
star
31

lua-resty-dns

DNS resolver for the nginx lua module
Lua
321
star
32

programming-openresty

Programming OpenResty Book
Perl
317
star
33

lua-resty-lock

Simple nonblocking lock API for ngx_lua based on shared memory dictionaries
Lua
304
star
34

openresty-devel-utils

Utilities for nginx module development
Perl
266
star
35

resty-cli

Fancy command-line utilities for OpenResty
Perl
263
star
36

replace-filter-nginx-module

Streaming regular expression replacement in response bodies
C
258
star
37

memc-nginx-module

An extended version of the standard memcached module that supports set, add, delete, and many more memcached commands.
C
213
star
38

encrypted-session-nginx-module

encrypt and decrypt nginx variable values
C
198
star
39

openresty-packaging

Official OpenResty packaging source and scripts for various Linux distributions and other systems
Makefile
176
star
40

rds-json-nginx-module

An nginx output filter that formats Resty DBD Streams generated by ngx_drizzle and others to JSON
C
153
star
41

xss-nginx-module

Native support for cross-site scripting (XSS) in an nginx
C
148
star
42

mockeagain

Mocking ideally slow network that only allows reading and/or writing one byte at a time
C
129
star
43

lua-resty-shell

Lua module for nonblocking system shell command executions
Perl
124
star
44

lua-tablepool

Lua table recycling pools for LuaJIT
Perl
112
star
45

lua-redis-parser

Lua module for parsing raw redis responses
C
93
star
46

openresty-survey

OpenResty Web App for OpenResty User Survey
HTML
90
star
47

lua-ssl-nginx-module

NGINX C module that extends ngx_http_lua_module for enhanced SSL/TLS capabilities
Lua
86
star
48

opsboy

A rule-based sysadmin tool that helps setting up complex environment for blank machines
Perl
85
star
49

no-pool-nginx

replace nginx's pool mechanism with plain malloc & free to help tools like valgrind
Shell
77
star
50

stream-echo-nginx-module

TCP/stream echo module for NGINX (a port of ngx_http_echo_module)
C
69
star
51

meta-lua-nginx-module

Meta Lua Nginx Module supporting both Http Lua Module and Stream Lua Module
C
66
star
52

array-var-nginx-module

Add support for array-typed variables to nginx config files
C
66
star
53

lemplate

OpenResty/Lua template framework implementing Perl's TT2 templating language
Perl
54
star
54

openresty-con

JavaScript
48
star
55

nginx-dtrace

An nginx fork that adds dtrace USDT probes
C
44
star
56

orbpf-ko

The orbpf (eBPF+) Linux kernel module from OpenResty Inc.
C
37
star
57

lua-resty-memcached-shdict

Powerful memcached client with a shdict caching layer and many other features
Lua
33
star
58

lua-resty-signal

Lua library for killing or sending signals to UNIX processes
Perl
32
star
59

lua-resty-shdict-simple

Simple applicaton-oriented interface to the OpenResty shared dictionary API
Perl
32
star
60

luajit2-test-suite

OpenResty's LuaJIT test suite based on Mike Pall's LuaJIT tests
Lua
29
star
61

ngx_postgres

OpenResty's fork of FRiCKLE/ngx_postgres
C
26
star
62

rds-csv-nginx-module

Nginx output filter module to convert Resty-DBD-Streams (RDS) to Comma-Separated Values (CSV)
C
22
star
63

showman-samples

Sample screenplay files for generating our public video tutorials using OpenResty Showman
20
star
64

lua-rds-parser

Resty DBD Stream (RDS) parser for Lua written in C
C
19
star
65

redis-nginx-module

8
star
66

AB-test-http

test http requests between two systems.
Perl
5
star
67

transparency

2
star