Created
October 28, 2013 01:55
-
-
Save markselby/7190301 to your computer and use it in GitHub Desktop.
Nginx LUA script for accessing a Redis request cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local redis = require "resty.redis" | |
local red = redis:new() | |
red:set_timeout(1000) -- 1 sec | |
local ok, err = red:connect("127.0.0.1", 6379) | |
if not ok then | |
ngx.log(ngx.ERR, "Redis failed to connect") | |
return ngx.exit(ngx.HTTP_SERVICE_UNAVAILABLE) | |
end | |
uri = ngx.var.uri | |
meta = uri.."-meta" | |
content = uri.."-content" | |
-- First get the info hash | |
local arr, err = red:hgetall(meta) | |
if not arr then | |
return ngx.exit(ngx.HTTP_NOT_FOUND) -- NOT FOUND | |
end | |
hash = red:array_to_hash(arr) | |
local ttl, err = red:ttl(content) | |
if ttl > 0 then | |
ngx.header.Cache_Control = "max-age="..ttl | |
end | |
if hash['etag'] then | |
if ngx.req.get_headers()["If-None-Match"] == hash['etag'] then | |
return ngx.exit(ngx.HTTP_NOT_MODIFIED) -- NOT MODIFIED | |
end | |
ngx.header.ETag = hash['etag'] | |
end | |
if hash['content_type'] then | |
ngx.header.Content_Type = hash['content_type'] | |
end | |
if hash['content_encoding'] then | |
ngx.header.Content_Encoding = hash['content_encoding'] | |
end | |
if hash['content_length'] then | |
ngx.header.Content_Length = hash['content_length'] | |
end | |
-- Get the actual content now we know the user needs it | |
local body, err = red:get(content) | |
if not body then | |
return ngx.exit(ngx.HTTP_NOT_FOUND) -- 404 to continue to the upstream | |
end | |
if body == ngx.null then | |
return ngx.exit(ngx.HTTP_NOT_FOUND) | |
end | |
ngx.header.Source = "Redis" | |
ngx.print(body) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment