Git Product home page Git Product logo

lua-resty-memcached's Introduction

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

lua-resty-memcached's People

Contributors

agentzh avatar bakins avatar cyberty avatar edwardbetts avatar elvinefendi avatar ghedo avatar pushrax avatar syzh avatar thibaultcha avatar xiaocang avatar zhuizhuhaomeng avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lua-resty-memcached's Issues

"module" is deprecated in Lua 5.2

I now you write mostly for 5.1 and the nginx stuff only supports 5.1. I've stopped using "module." I actually find the "create and return a table" method of doing Lua modules gives a little more control over what is exposed and allows the global environment to stay clean. I may do a fork using that method.

How to use the connect pool properly?

Hi there, Happy new year

The code basically comes from the Synopsis:

local memcached = require "resty.memcached"
local memc, err = memcached:new()

if not memc then
    ngx.log(ngx.ERR, err)
    ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
end

memc:set_timeout(3000)

local ok, err = memc:connect("127.0.0.1", 11211)
if not ok then
    ngx.log(ngx.ERR, err)
    ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)
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
local ok, err = memc:set_keepalive(100000, 100)
if not ok then
    ngx.say("cannot set keepalive: ", err)
    return
end

I tryed pressure test, the nginx config have 4 nginx worker, So I expect memcache will keep 400 connections after the test is done, but I got 0.

I tried a similar test using lua-resty-redis and found the result normal

Specify a bucket

Hey... i am trying this binding for connect a couchbase cluster...
how i can specify a custom bucket instead "default bucket" ?

Salutes

How to decode deflate data from memcached?

Hello,

I put data to memcached from php, it automatically uses a compression of data if it's size is too large. It allows to save a lot of space.

But when I try to read this data from resty.memcached I see compressed data and I have no idea how to decompress it. Could you please suggest me a solution which can help me?

Best regards,
Yahook

travis memcached problem

Hi, sorry to bother you.

It requires to start a memcached listening at the default port(11211) when I trigger the test by prove -r t in local environment.
I am really confused that .travis.yml doesn't declare:

services:
  - memcached

How is it possible to pass test in travis-ci environment?

idle connections to memcached

Hi,
I have the following code executed on each request:

    access_by_lua_block {
      local memcached = require "resty.memcached"
      local memc = memcached:new()
      memc:set_timeout(3000) -- 3 sec
      local ok = memc:connect("127.0.0.1", 11211)
      local myvar = memc:get(othervar)
      ### do something
      local ok, err = memc:close()
    }

put operation is happening in other internal location in case proxy origin receives 302 redirect

    access_by_lua_block {
      local memcached = require "resty.memcached"
      local memc = memcached:new()
      memc:set_timeout(1000) -- 1 sec
      local ok = memc:connect("127.0.0.1", 11211)
      ### do something
      local ok, err = memc:set(stringone, stringtwo, 604800)
      local ok, err = memc:close()
    }

Recently I noticed that connections are not really closed but stay idle for some time. And it's count is pretty high.
I have memcached running in docker contrainer like this

memcached -c 10000 -t 8

nginx itself handles 4k rps nonstop

And netstat shows this

netstat -an | grep 11211 
tcp        0      0 0.0.0.0:11211           0.0.0.0:*               LISTEN     
tcp        0      0 127.0.0.1:62334         127.0.0.1:11211         TIME_WAIT  
tcp        0      0 127.0.0.1:59430         127.0.0.1:11211         TIME_WAIT  
tcp        0      0 127.0.0.1:61444         127.0.0.1:11211         TIME_WAIT  
tcp        0      0 172.17.0.1:11638        172.17.0.2:11211        TIME_WAIT  
tcp        0      0 127.0.0.1:45352         127.0.0.1:11211         TIME_WAIT  
tcp        0      0 127.0.0.1:62010         127.0.0.1:11211         TIME_WAIT  
tcp        0      0 127.0.0.1:56390         127.0.0.1:11211         TIME_WAIT  
tcp        0      0 172.17.0.1:31884        172.17.0.2:11211        TIME_WAIT  
tcp        0      0 172.17.0.1:64364        172.17.0.2:11211        TIME_WAIT  
...

netstat -an | grep -c 11211 
31836

lua module version is 0.16

Please help me solve this issue, thank you in advance.

How to use prefix with ":" in key

Hello! I'm new in lua, and have an issue: I have data in memcached, putted by PHP with prefix with colon, such as 'appname:' . Key example is 'appname:08d1effdff9b03e8f54e55a72c703471'

So, with lua I need get data from memcached, but memc:get('appname:08d1effdff9b03e8f54e55a72c70347') not works (return nil). But if key is without colon, as memc:get('08d1effdff9b03e8f54e55a72c703471') , it works fine.

How can I use keys with prefix like 'appname:value' in lua?

reading protobuf values

I am trying to read memcached values that are protocol buffers, however I always get a nil result with no error. If I set a key with a test string myself from lua-resty I can read it back. I can also echo get KEY | nc memcached_server 11211 and see that the protobuf encoded value is present. Seems like a common use case, am I missing a config option?

Clusters / Multiple Memcache Hosts

We are planing on using OpenResty in production for dynamic configuration of caching.
Currently we have a POC using MySQL but I would like to cache the query results in Memcached to prevent stress on the MySQL host.

This whole setup will be in AWS so naturally we are using AWS's ElastiCache service.
AWS provisions multiple hosts that should be all used in a cluster configuration.

I can't seem to find any information regarding to connecting to a cluster of Memcache hosts, is this something supported or should we just pick one of the hosts and roll with it.

Also sorry for #37, fat fingered the enter key and that created the empty issue.

URI Escaping the key before doing a 'get'

I ran into an issue where I could not retrieve a value from memcache. I looked at the code and the key is being uri escaped before the get. Is that required?

The key I was using is of the form: "[key_name]"

How to use SASL Authentication Protocol ?

I am using memcache on ALIYUN which is a cloud memcache service.
but unfortunately,this project seems not support "SASL Authentication Protocol".
can you add this feature to this project or is there any hack solution?

thank you very much:)

Getting key's token always failed by the gets method.

Hey, I got a problem... Maybe it's stupid, but I don't know where to find help, so created this issue. Why do I always get nil value by the gets method? Here is the code which copied from your demo.

location = /hi {
    content_by_lua_block {
    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)
    
    local ok, err = memc:connect("10.23.233.12", 8201)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end

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

    -- get key's token
    local data, flags, token, err = memc:gets("dog")
    if not token then
        ngx.say("failed to get token")
        return
    end

   local ok, err = memc:cas("dog", data + 1, token)
    if not ok then
        ngx.say("failed to set dog ", err)
        return
    end

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

    ngx.say("dog: ", res)
    }
}

failed to connect: memcached could not be resolved

First of all, I wanna thank the OpenResty team for this great work.

Let me introduce:
I'm using the OpenResty and memcached over the docker container, both of them are the from the official image: FROM openresty/openresty:buster-fat and FROM memcached.
These docker container are managed by a docker-compose.yml file, I named the memcached service "memcached" and expose the prot "11211".

I'm pretty sure that the network between those two containers is valid and usable.
Because I tried it the way right here https://github.com/openresty/memc-nginx-module#synopsis, using the memc-nginx-module, this is the snippets of code (nginx.conf):

http {
        ... ...
	# 连接到 memcached servers
	upstream backend {
		server memcached:11211;
		keepalive 1024;
	}
        ... ...
}
server {
        location / {
                # 将数据设置到 memcached https://github.com/openresty/memc-nginx-module#set-memc_key-memc_flags-memc_exptime-memc_value
                set $memc_cmd set;
                set $memc_key "testing";
                set $memc_flags 12345;
                set $memc_value 'my_value';
                 memc_pass backend;
        }
}

it's like your document say is "Returns 201 Created if the upstream memcached server replies STORED".

But when I use the lua-resty-memcached to connect the memcached with the same host and port, I got

2020/03/14 20:22:50 [error] 8#8: *1 [lua] recognize_env.lua:16: get_memcached(): failed to connect: memcached could not be resolved (3: Host not found), client: 192.168.48.1, server: localhost, request: "GET / HTTP/1.1", host: "localhost:8080"

in the error.log.

This is the .lua file snippets of code for connect to the memcached :

local memcached = require "resty.memcached"  
local memc, err = memcached:new()  
memc:set_timeout(1000) -- 1 sec  
if not memc then   
    ngx.log(ngx.ERR, "failed to instantiate memc: ", err)  
    ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)  
end  
-- 连接  
local ok, err = memc:connect("memcached", 11211)  
if not ok then  
    ngx.log(ngx.ERR, "failed to connect: ", err)  
    ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)  
end 
-- set 数据到 memc  
local ok, err = memc:set("dog", "a kind of animal")  
if not ok then  
    ngx.log(ngx.ERR, "failed to set memc: ", err)  
    ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE)  
end  

It's basically a copy of your document...

But I still couldn't connect to memcached with lua-resty-memcached.

Is there anything that needs to be changed? What did I do wrong?

SASL Authentication Protocol

hi all:

I need a new protocol for the memcahed SASL Authentication.

but current version does not provide,  who can help me to realize.

thanks all !

Few test case failures on rhel 7.6 ppc64le

Hi All,

I had build the nginx binary on rhel 7.6 ppc64le (version 1.17.1.1rc0) from source code - https://github.com/openresty/openresty.
Please note that, I had copied and used ppc64le compiled LuaJIT code while building openresty (nginx).

Below command I used to compile the openresty -

./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC" --with-http_image_filter_module --with-http_dav_module  --with-http_auth_request_module --with-poll_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-http_ssl_module --with-http_iconv_module  --with-http_drizzle_module --with-http_postgres_module --with-http_addition_module --add-module=/usr/openresty/openresty_test_modules/nginx-eval-module --add-module=/usr/openresty/openresty_test_modules/replace-filter-nginx-module

And then tried to execute the test cases for 'lua-resty-memcached' like below -

# pwd
/usr/openresty/openresty/openresty-1.17.1.1rc0/build/lua-resty-memcached-0.14
# prove -r t/

NOTE: The 'lua-resty-memcached' version downloaded from openresty bundle is 0.14

And I am getting below kind of errors -

# prove -r t/
t/mock.t ...... 1/40
#   Failed test 'TEST 2: continue using the obj when read timeout happens - tcp_query ok'
#   at /usr/local/share/perl5/Test/Nginx/Util.pm line 188.
#          got: ''
#     expected: 'get foo
# '

#   Failed test 'TEST 2: continue using the obj when read timeout happens - TCP query length ok'
#   at /usr/local/share/perl5/Test/Nginx/Util.pm line 1276.
#          got: '0'
#     expected: '9'
TEST 2: continue using the obj when read timeout happens - WARNING: killing the child process 19031 with force... at /usr/local/share/perl5/Test/Nginx/Util.pm line 609.
t/mock.t ...... 23/40 # Looks like you failed 2 tests of 40.
t/mock.t ...... Dubious, test returned 2 (wstat 512, 0x200)
Failed 2/40 subtests
t/sanity.t .... 18/220 WARNING: TEST 38: gets (multiple key) + change only unescape key - 2019/10/14 15:55:53 [warn] 19202#0: *1 [lua] _G write guard:12: __newindex(): writing a global lua variable ('identity') which may lead to race conditions between concurrent requests, so prefer the use of 'local' variables
t/sanity.t .... 73/220
#   Failed test 'ERROR: client socket timed out - TEST 29: connect timeout
# '
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 2062.

#   Failed test 'TEST 29: connect timeout - status code ok'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 948.
#          got: ''
#     expected: '200'

#   Failed test 'TEST 29: connect timeout - response_body - response is expected (repeated req 0, req 0)'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 1589.
#          got: ''
#     expected: 'failed to connect: timeout
# '

#   Failed test 'TEST 29: connect timeout - pattern "lua tcp socket connect timed out" should match a line in error.log (req 0)'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 1213.
t/sanity.t .... 77/220
#   Failed test 'ERROR: client socket timed out - TEST 29: connect timeout
# '
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 2062.

#   Failed test 'TEST 29: connect timeout - status code ok'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 948.
#          got: ''
#     expected: '200'

#   Failed test 'TEST 29: connect timeout - response_body - response is expected (repeated req 1, req 0)'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 1589.
#          got: ''
#     expected: 'failed to connect: timeout
# '

#   Failed test 'TEST 29: connect timeout - pattern "lua tcp socket connect timed out" should match a line in error.log (req 1)'
#   at /usr/local/share/perl5/Test/Nginx/Socket.pm line 1213.
t/sanity.t .... 146/220 WARNING: TEST 37: change escape method - 2019/10/14 15:56:05 [warn] 19339#0: *1 [lua] _G write guard:12: __newindex(): writing a global lua variable ('identity') which may lead to race conditions between concurrent requests, so prefer the use of 'local' variables
t/sanity.t .... Failed 8/220 subtests
t/tableset.t .. ok
t/touch.t ..... ok
t/version.t ... ok

Test Summary Report
-------------------
t/mock.t    (Wstat: 512 Tests: 40 Failed: 2)
  Failed tests:  4-5
  Non-zero exit status: 2
t/sanity.t  (Wstat: 0 Tests: 222 Failed: 10)
  Failed tests:  73-80, 221-222
  Parse errors: Bad plan.  You planned 220 tests but ran 222.
Files=5, Tests=288, 50 wallclock secs ( 0.11 usr  0.00 sys +  2.25 cusr  0.69 csys =  3.05 CPU)
Result: FAIL

Please help suggest if I need to export any specific environment or should try any compiler flag/somehow increase the timeout value to make these test cases pass.

nginx version (compiled with libdrizzle 1.0 and radius, mariadb, postgresql services setup) -

# nginx -V
nginx version: openresty/1.17.1.1rc0
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/openresty/nginx --with-cc-opt='-O2 -DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC' --add-module=../ngx_devel_kit-0.3.1rc1 --add-module=../iconv-nginx-module-0.14 --add-module=../echo-nginx-module-0.61 --add-module=../xss-nginx-module-0.06 --add-module=../ngx_coolkit-0.2 --add-module=../set-misc-nginx-module-0.32 --add-module=../form-input-nginx-module-0.12 --add-module=../encrypted-session-nginx-module-0.08 --add-module=../drizzle-nginx-module-0.1.11 --add-module=../ngx_postgres-1.0 --add-module=../srcache-nginx-module-0.31 --add-module=../ngx_lua-0.10.15 --add-module=../ngx_lua_upstream-0.07 --add-module=../headers-more-nginx-module-0.33 --add-module=../array-var-nginx-module-0.05 --add-module=../memc-nginx-module-0.19 --add-module=../redis2-nginx-module-0.15 --add-module=../redis-nginx-module-0.3.7 --add-module=../rds-json-nginx-module-0.15 --add-module=../rds-csv-nginx-module-0.09 --add-module=../ngx_stream_lua-0.0.7 --with-ld-opt=-Wl,-rpath,/usr/local/openresty/luajit/lib --with-http_image_filter_module --with-http_dav_module --with-http_auth_request_module --with-poll_module --with-stream --with-stream_ssl_module --with-stream_ssl_preread_module --with-http_ssl_module --with-http_addition_module --add-module=/usr/openresty/openresty_test_modules/nginx-eval-module --add-module=/usr/openresty/openresty_test_modules/replace-filter-nginx-module --with-stream --with-stream_ssl_preread_module

get slow

hi,经测试发现get数据非常慢,请问你有遇到过么?
发现都在上百毫米
2013/02/26 11:47:21 [notice] 23797#0: *574 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.145000
2013/02/26 11:47:21 [notice] 23795#0: *609 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.168000
2013/02/26 11:47:21 [notice] 23797#0: *255 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.145000
2013/02/26 11:47:21 [notice] 23795#0: *675 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.168000
2013/02/26 11:47:21 [notice] 23797#0: *173 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.149000
2013/02/26 11:47:21 [notice] 23800#0: *704 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.146000
2013/02/26 11:47:21 [notice] 23798#0: *14 [lua] memca.lua:44: memcached_get(): memcache_get_get: 0.163000

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.