Hello!
On Tue, May 13, 2014 at 10:12 PM, arthurx wrote:
> Suppose I need cjson and redis for both the access phase and content phase
> using two lua scripts, It seems that I would need to call
> local cjson = require "cjson"
> local redis = require "resty.redis"
> as well as the redis init and keepalive lines in both scripts. It just
> seems kind of redundant, since my access script is a simple key lookup. Is
> that the correct to call those library in both script or is there a way to
> reuse library between the phases?
>
The require() primitive caches loaded Lua modules in the global
package.loaded table (hooked in the Lua registry). So your Lua modules
will only get loaded once for each nginx worker process (usually just
upon the first request served) unless you turn off the lua_code_cache
directive. So it's fine to just call require() wherever you need to.
You can put your Lua code into your own Lua modules which can save the
require() calls to the cjson and resty.redis modules (but you still
need to require your own Lua module).
Also, calling set_keepalive() as soon as you finish up using your
redis connection is recommended because other concurrent requests can
have a chance to reuse the connection sooner rather than later.
Regards,
-agentzh