Debian Codegraph @

README.markdown

raw
1 Name
2 ====
3
4 lua-resty-memcached - Lua memcached client driver for the ngx_lua based on the cosocket API
5
6 Table of Contents
7 =================
8
9 * [Name](#name)
10 * [Status](#status)
11 * [Description](#description)
12 * [Synopsis](#synopsis)
13 * [Methods](#methods)
14 * [new](#new)
15 * [connect](#connect)
16 * [sslhandshake](#sslhandshake)
17 * [set](#set)
18 * [set_timeout](#set_timeout)
19 * [set_timeouts](#set_timeouts)
20 * [set_keepalive](#set_keepalive)
21 * [get_reused_times](#get_reused_times)
22 * [close](#close)
23 * [add](#add)
24 * [replace](#replace)
25 * [append](#append)
26 * [prepend](#prepend)
27 * [get](#get)
28 * [gets](#gets)
29 * [cas](#cas)
30 * [touch](#touch)
31 * [flush_all](#flush_all)
32 * [delete](#delete)
33 * [incr](#incr)
34 * [decr](#decr)
35 * [stats](#stats)
36 * [version](#version)
37 * [quit](#quit)
38 * [verbosity](#verbosity)
39 * [init_pipeline](#init_pipeline)
40 * [commit_pipeline](#commit_pipeline)
41 * [cancel_pipeline](#cancel_pipeline)
42 * [Automatic Error Logging](#automatic-error-logging)
43 * [Limitations](#limitations)
44 * [TODO](#todo)
45 * [Author](#author)
46 * [Copyright and License](#copyright-and-license)
47 * [See Also](#see-also)
48
49 Status
50 ======
51
52 This library is considered production ready.
53
54 Description
55 ===========
56
57 This Lua library is a memcached client driver for the ngx_lua nginx module:
58
59 http://wiki.nginx.org/HttpLuaModule
60
61 This Lua library takes advantage of ngx_lua's cosocket API, which ensures
62 100% nonblocking behavior.
63
64 Note that at least [ngx_lua 0.5.0rc29](https://github.com/chaoslawful/lua-nginx-module/tags) or [OpenResty 1.0.15.7](http://openresty.org/#Download) is required.
65
66 Synopsis
67 ========
68
69 ```lua
70 lua_package_path "/path/to/lua-resty-memcached/lib/?.lua;;";
71
72 server {
73 location /test {
74 content_by_lua '
75 local memcached = require "resty.memcached"
76 local memc, err = memcached:new()
77 if not memc then
78 ngx.say("failed to instantiate memc: ", err)
79 return
80 end
81
82 memc:set_timeout(1000) -- 1 sec
83
84 -- or connect to a unix domain socket file listened
85 -- by a memcached server:
86 -- local ok, err = memc:connect("unix:/path/to/memc.sock")
87
88 local ok, err = memc:connect("127.0.0.1", 11211)
89 if not ok then
90 ngx.say("failed to connect: ", err)
91 return
92 end
93
94 local ok, err = memc:flush_all()
95 if not ok then
96 ngx.say("failed to flush all: ", err)
97 return
98 end
99
100 local ok, err = memc:set("dog", 32)
101 if not ok then
102 ngx.say("failed to set dog: ", err)
103 return
104 end
105
106 local res, flags, err = memc:get("dog")
107 if err then
108 ngx.say("failed to get dog: ", err)
109 return
110 end
111
112 if not res then
113 ngx.say("dog not found")
114 return
115 end
116
117 ngx.say("dog: ", res)
118
119 -- put it into the connection pool of size 100,
120 -- with 10 seconds max idle timeout
121 local ok, err = memc:set_keepalive(10000, 100)
122 if not ok then
123 ngx.say("cannot set keepalive: ", err)
124 return
125 end
126
127 -- or just close the connection right away:
128 -- local ok, err = memc:close()
129 -- if not ok then
130 -- ngx.say("failed to close: ", err)
131 -- return
132 -- end
133 ';
134 }
135 }
136 ```
137
138 [Back to TOC](#table-of-contents)
139
140 Methods
141 =======
142
143 The `key` argument provided in the following methods will be automatically escaped according to the URI escaping rules before sending to the memcached server.
144
145 [Back to TOC](#table-of-contents)
146
147 new
148 ---
149 `syntax: memc, err = memcached:new(opts?)`
150
151 Creates a memcached object. In case of failures, returns `nil` and a string describing the error.
152
153 It accepts an optional `opts` table argument. The following options are supported:
154
155 * `key_transform`
156
157 an array table containing two functions for escaping and unescaping the
158 memcached keys, respectively. By default,
159 the memcached keys will be escaped and unescaped as URI components, that is
160
161 ```lua
162 memached:new{
163 key_transform = { ngx.escape_uri, ngx.unescape_uri }
164 }
165 ```
166
167 [Back to TOC](#table-of-contents)
168
169 connect
170 -------
171 `syntax: ok, err = memc:connect(host, port)`
172
173 `syntax: ok, err = memc:connect("unix:/path/to/unix.sock")`
174
175 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.
176
177 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.
178
179 [Back to TOC](#table-of-contents)
180
181 sslhandshake
182 ------------
183
184 **syntax:** *session, err = memc:sslhandshake(reused_session?, server_name?, ssl_verify?, send_status_req?)*
185
186 Does SSL/TLS handshake on the currently established connection. See the
187 [tcpsock.sslhandshake](https://github.com/openresty/lua-nginx-module#tcpsocksslhandshake)
188 API from OpenResty for more details.
189
190 [Back to TOC](#table-of-contents)
191
192 set
193 ---
194 `syntax: ok, err = memc:set(key, value, exptime, flags)`
195
196 Inserts an entry into memcached unconditionally. If the key already exists, overrides it.
197
198 The `value` argument could also be a Lua table holding multiple Lua
199 strings that are supposed to be concatenated as a whole
200 (without any delimiters). For example,
201
202 ```lua
203 memc:set("dog", {"a ", {"kind of"}, " animal"})
204 ```
205
206 is functionally equivalent to
207
208 ```lua
209 memc:set("dog", "a kind of animal")
210 ```
211
212 The `exptime` parameter is optional and defaults to `0` (meaning never expires). The expiration time is in seconds.
213
214 The `flags` parameter is optional and defaults to `0`.
215
216 [Back to TOC](#table-of-contents)
217
218 set_timeout
219 ----------
220 `syntax: ok, err = memc:set_timeout(timeout)`
221
222 Sets the timeout (in ms) protection for subsequent operations, including the `connect` method.
223
224 Returns 1 when successful and nil plus a string describing the error otherwise.
225
226 [Back to TOC](#table-of-contents)
227
228 set_timeouts
229 ----------
230 `syntax: ok, err = memc:set_timeouts(connect_timeout, send_timeout, read_timeout)`
231
232 Sets the timeouts (in ms) for connect, send and read operations respectively.
233
234 Returns 1 when successful and nil plus a string describing the error otherwise.
235
236 set_keepalive
237 ------------
238 `syntax: ok, err = memc:set_keepalive(max_idle_timeout, pool_size)`
239
240 Puts the current memcached connection immediately into the ngx_lua cosocket connection pool.
241
242 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.
243
244 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
245
246 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.
247
248 [Back to TOC](#table-of-contents)
249
250 get_reused_times
251 ----------------
252 `syntax: times, err = memc:get_reused_times()`
253
254 This method returns the (successfully) reused times for the current connection. In case of error, it returns `nil` and a string describing the error.
255
256 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.
257
258 [Back to TOC](#table-of-contents)
259
260 close
261 -----
262 `syntax: ok, err = memc:close()`
263
264 Closes the current memcached connection and returns the status.
265
266 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
267
268
269 [Back to TOC](#table-of-contents)
270
271 add
272 ---
273 `syntax: ok, err = memc:add(key, value, exptime, flags)`
274
275 Inserts an entry into memcached if and only if the key does not exist.
276
277 The `value` argument could also be a Lua table holding multiple Lua
278 strings that are supposed to be concatenated as a whole
279 (without any delimiters). For example,
280
281 ```lua
282 memc:add("dog", {"a ", {"kind of"}, " animal"})
283 ```
284
285 is functionally equivalent to
286
287 ```lua
288 memc:add("dog", "a kind of animal")
289 ```
290
291 The `exptime` parameter is optional and defaults to `0` (meaning never expires). The expiration time is in seconds.
292
293 The `flags` parameter is optional, defaults to `0`.
294
295 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
296
297 [Back to TOC](#table-of-contents)
298
299 replace
300 -------
301 `syntax: ok, err = memc:replace(key, value, exptime, flags)`
302
303 Inserts an entry into memcached if and only if the key does exist.
304
305 The `value` argument could also be a Lua table holding multiple Lua
306 strings that are supposed to be concatenated as a whole
307 (without any delimiters). For example,
308
309 ```lua
310 memc:replace("dog", {"a ", {"kind of"}, " animal"})
311 ```
312
313 is functionally equivalent to
314
315 ```lua
316 memc:replace("dog", "a kind of animal")
317 ```
318
319 The `exptime` parameter is optional and defaults to `0` (meaning never expires). The expiration time is in seconds.
320
321 The `flags` parameter is optional, defaults to `0`.
322
323 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
324
325 [Back to TOC](#table-of-contents)
326
327 append
328 ------
329 `syntax: ok, err = memc:append(key, value, exptime, flags)`
330
331 Appends the value to an entry with the same key that already exists in memcached.
332
333 The `value` argument could also be a Lua table holding multiple Lua
334 strings that are supposed to be concatenated as a whole
335 (without any delimiters). For example,
336
337 ```lua
338 memc:append("dog", {"a ", {"kind of"}, " animal"})
339 ```
340
341 is functionally equivalent to
342
343 ```lua
344 memc:append("dog", "a kind of animal")
345 ```
346
347 The `exptime` parameter is optional and defaults to `0` (meaning never expires). The expiration time is in seconds.
348
349 The `flags` parameter is optional, defaults to `0`.
350
351 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
352
353 [Back to TOC](#table-of-contents)
354
355 prepend
356 -------
357 `syntax: ok, err = memc:prepend(key, value, exptime, flags)`
358
359 Prepends the value to an entry with the same key that already exists in memcached.
360
361 The `value` argument could also be a Lua table holding multiple Lua
362 strings that are supposed to be concatenated as a whole
363 (without any delimiters). For example,
364
365 ```lua
366 memc:prepend("dog", {"a ", {"kind of"}, " animal"})
367 ```
368
369 is functionally equivalent to
370
371 ```lua
372 memc:prepend("dog", "a kind of animal")
373 ```
374
375 The `exptime` parameter is optional and defaults to `0` (meaning never expires). The expiration time is in seconds.
376
377 The `flags` parameter is optional and defaults to `0`.
378
379 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
380
381 [Back to TOC](#table-of-contents)
382
383 get
384 ---
385 `syntax: value, flags, err = memc:get(key)`
386 `syntax: results, err = memc:get(keys)`
387
388 Get a single entry or multiple entries in the memcached server via a single key or a table of keys.
389
390 Let us first discuss the case When the key is a single string.
391
392 The key's value and associated flags value will be returned if the entry is found and no error happens.
393
394 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.
395
396 If the entry is not found, then three `nil` values will be returned.
397
398 Then let us discuss the case when the a Lua table of multiple keys are provided.
399
400 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.
401
402 In case of errors, `nil` will be returned, and the second return value will be a string describing the error.
403
404 [Back to TOC](#table-of-contents)
405
406 gets
407 ----
408 `syntax: value, flags, cas_unique, err = memc:gets(key)`
409
410 `syntax: results, err = memc:gets(keys)`
411
412 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.
413
414 This method is usually used together with the `cas` method.
415
416 [Back to TOC](#table-of-contents)
417
418 cas
419 ---
420 `syntax: ok, err = memc:cas(key, value, cas_unique, exptime?, flags?)`
421
422 Just like the `set` method but does a check and set operation, which means "store this data but
423 only if no one else has updated since I last fetched it."
424
425 The `cas_unique` argument can be obtained from the `gets` method.
426
427 [Back to TOC](#table-of-contents)
428
429 touch
430 ---
431 `syntax: ok, err = memc:touch(key, exptime)`
432
433 Update the expiration time of an existing key.
434
435 Returns `1` for success or `nil` with a string describing the error otherwise.
436
437 This method was first introduced in the `v0.11` release.
438
439 [Back to TOC](#table-of-contents)
440
441 flush_all
442 ---------
443 `syntax: ok, err = memc:flush_all(time?)`
444
445 Flushes (or invalidates) all the existing entries in the memcached server immediately (by default) or after the expiration
446 specified by the `time` argument (in seconds).
447
448 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
449
450 [Back to TOC](#table-of-contents)
451
452 delete
453 ------
454 `syntax: ok, err = memc:delete(key)`
455
456 Deletes the key from memcached immediately.
457
458 The key to be deleted must already exist in memcached.
459
460 In case of success, returns `1`. In case of errors, returns `nil` with a string describing the error.
461
462 [Back to TOC](#table-of-contents)
463
464 incr
465 ----
466 `syntax: new_value, err = memc:incr(key, delta)`
467
468 Increments the value of the specified key by the integer value specified in the `delta` argument.
469
470 Returns the new value after incrementation in success, and `nil` with a string describing the error in case of failures.
471
472 [Back to TOC](#table-of-contents)
473
474 decr
475 ----
476 `syntax: new_value, err = memc:decr(key, value)`
477
478 Decrements the value of the specified key by the integer value specified in the `delta` argument.
479
480 Returns the new value after decrementation in success, and `nil` with a string describing the error in case of failures.
481
482 [Back to TOC](#table-of-contents)
483
484 stats
485 -----
486 `syntax: lines, err = memc:stats(args?)`
487
488 Returns memcached server statistics information with an optional `args` argument.
489
490 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.
491
492 If the `args` argument is omitted, general server statistics is returned. Possible `args` argument values are `items`, `sizes`, `slabs`, among others.
493
494 [Back to TOC](#table-of-contents)
495
496 version
497 -------
498 `syntax: version, err = memc:version(args?)`
499
500 Returns the server version number, like `1.2.8`.
501
502 In case of error, it returns `nil` with a string describing the error.
503
504 [Back to TOC](#table-of-contents)
505
506 quit
507 ----
508 `syntax: ok, err = memc:quit()`
509
510 Tells the server to close the current memcached connection.
511
512 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.
513
514 Generally you can just directly call the `close` method to achieve the same effect.
515
516 [Back to TOC](#table-of-contents)
517
518 verbosity
519 ---------
520 `syntax: ok, err = memc:verbosity(level)`
521
522 Sets the verbosity level used by the memcached server. The `level` argument should be given integers only.
523
524 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.
525
526 [Back to TOC](#table-of-contents)
527
528 init_pipeline
529 ---------
530 `syntax: err = memc:init_pipeline(n?)`
531
532 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.
533
534 The optional params `n` is buffer tables size. default value 4
535
536 [Back to TOC](#table-of-contents)
537
538 commit_pipeline
539 ---------
540 `syntax: results, err = memc:commit_pipeline()`
541
542 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.
543
544 This method success return a lua table. failed return a lua string describing the error upon failures.
545
546 [Back to TOC](#table-of-contents)
547
548 cancel_pipeline
549 ---------
550 `syntax: memc:cancel_pipeline()`
551
552 Quits the pipelining mode by discarding all existing buffer Memcache commands since the last call to the init_pipeline method.
553
554 the method no return. always succeeds.
555
556 [Back to TOC](#table-of-contents)
557
558 Automatic Error Logging
559 =======================
560
561 By default the underlying [ngx_lua](http://wiki.nginx.org/HttpLuaModule) module
562 does error logging when socket errors happen. If you are already doing proper error
563 handling in your own Lua code, then you are recommended to disable this automatic error logging by turning off [ngx_lua](http://wiki.nginx.org/HttpLuaModule)'s [lua_socket_log_errors](http://wiki.nginx.org/HttpLuaModule#lua_socket_log_errors) directive, that is,
564
565 ```nginx
566 lua_socket_log_errors off;
567 ```
568
569 [Back to TOC](#table-of-contents)
570
571 Limitations
572 ===========
573
574 * This library cannot be used in code contexts like `set_by_lua*`, `log_by_lua*`, and
575 `header_filter_by_lua*` where the ngx\_lua cosocket API is not available.
576 * The `resty.memcached` object instance cannot be stored in a Lua variable at the Lua module level,
577 because it will then be shared by all the concurrent requests handled by the same nginx
578 worker process (see
579 http://wiki.nginx.org/HttpLuaModule#Data_Sharing_within_an_Nginx_Worker ) and
580 result in bad race conditions when concurrent requests are trying to use the same `resty.memcached` instance.
581 You should always initiate `resty.memcached` objects in function local
582 variables or in the `ngx.ctx` table. These places all have their own data copies for
583 each request.
584
585 [Back to TOC](#table-of-contents)
586
587 TODO
588 ====
589
590 * implement the memcached pipelining API.
591 * implement the UDP part of the memcached ascii protocol.
592
593 [Back to TOC](#table-of-contents)
594
595 Author
596 ======
597
598 Yichun "agentzh" Zhang (章亦春) <[email protected]>, OpenResty Inc.
599
600 [Back to TOC](#table-of-contents)
601
602 Copyright and License
603 =====================
604
605 This module is licensed under the BSD license.
606
607 Copyright (C) 2012-2017, by Yichun "agentzh" Zhang (章亦春) <[email protected]>, OpenResty Inc.
608
609 All rights reserved.
610
611 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
612
613 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
614
615 * 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.
616
617 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.
618
619 [Back to TOC](#table-of-contents)
620
621 See Also
622 ========
623 * the ngx_lua module: http://wiki.nginx.org/HttpLuaModule
624 * the memcached wired protocol specification: http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt
625 * the [lua-resty-redis](https://github.com/agentzh/lua-resty-redis) library.
626 * the [lua-resty-mysql](https://github.com/agentzh/lua-resty-mysql) library.
627
628 [Back to TOC](#table-of-contents)
629