Lua Nginx|Openresty: use session with redis cluster


Require:
lua-resty-redis , lua-resty-lock , lua-resty-redis-cluster , lua-resty-session

Example nginx.conf

http {
    server {
        listen       8080;
        server_name  localhost;
        default_type text/html;

        lua_shared_dict sessions 100k;

	set $session_storage redis;
	set $session_redis_prefix                   sessions;
	 
	set $session_redis_cluster_name             redis-cluster;
	set $session_redis_cluster_dict             sessions;
	set $session_redis_cluster_maxredirections  5;
	set $session_redis_cluster_nodes            '5.111.72.222:6379 5.111.61.47:6379';
	
	location /test/session {
		 
		content_by_lua '
			ngx.say("<html><body><a href=/test/session/start>Start the test</a>!</body></html>")
		';
	}
	location /test/session/start {
		 
		content_by_lua '
			local session = require "resty.session".start()
			session.data.name = "OpenResty Fan"
			session:save()
			ngx.say("<html><body>Session started. ",
					"<a href=/test/session/test>Check if it is working</a>!</body></html>")
		';
	}
	location /test/session/test {
		 
		content_by_lua '
			local session = require "resty.session".open()
			ngx.say("<html><body>Session was started by <strong>",
					session.data.name or "Anonymous",
					"</strong>! <a href=/test/session/modify>Modify the session</a>.</body></html>")
		';
	}
	location /test/session/modify {
		 
		content_by_lua '
			local session = require "resty.session".start()
			session.data.name = "Lua Fan"
			session:save()
			ngx.say("<html><body>Session modified. ",
					"<a href=/test/session/modified>Check if it is modified</a>!</body></html>")
		';
	}
	location /test/session/modified {
		 
		content_by_lua '
			local session = require "resty.session".open()
			ngx.say("<html><body>Session was modified by <strong>",
					session.data.name or "Anonymous",
					"</strong>! <a href=/test/session/destroy>Destroy the session</a>.</body></html>")
		';
	}
	location /test/session/destroy {
		 
		content_by_lua '
			require "resty.session".destroy()
			ngx.say("<html><body>Session was destroyed. ",
					"<a href=/test/session/check>Is it really so</a>?</body></html>")
		';
	}
	location /test/session/check {
		 
		content_by_lua '
			local session = require "resty.session".open()
			ngx.say("<html><body>Session was really destroyed, you are known as ",
					"<strong>",
					session.data.name or "Anonymous",
					"</strong>! <a href=/test/session/>Start again</a>.</body></html>")
		';
	}

}
}

Now test http://localhost:8080/test/session

1 Comment

Leave a Reply