SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
NGINX + Lua
Using NGINX/OpenResty
with embedded Lua
Epifanov Ivan,
Lead Developer
Lua
• Fast
• Light (241K)
• Simple
• Powerfull
• Embeddable
• Portable
Lua do Pesadelo
(Nightmare Moon)
Who uses Lua?
• Games: WoW, Angry Birds, Baldur's
Gate, Civilization V, Crysis, HoMM V,
L.A. Noire, etc.
• Software: Lightroom, MySQL proxy,
MySQL Workbench, Celestia, Far
Manager, GIMP, MediaWiki, etc.
• Misc.: Mercedes Autos, LG Smart TV,
Space Shuttle Gas Detection, etc.
LuaJIT
• JIT compilation for lua code
• High performance (3-100x)
• Low memory footprint
• Crossplatform
• Cross-architecture (x86, ARM, MIPS,
PPC
• local ffi = require("ffi")
ffi.cdef[[
int printf(const char *fmt, ...);
]]
ffi.C.printf("Hello %s!", "world")
OpenResty/NGINX-LUA
• NGINX bundle with luajit and additional
modules.
• Developed by TaoBao and CloudFlare
• Access to every processing stage of
nginx
• Non-blocking without callback-hell
• co-sockets, shared pool and sub-
requests
Full control
• init_by_lua(file)
• init_worker_by_lua(file)
• set_by_lua(file)
• log_by_lua(file)
• content_by_lua(file)
• header_filter_by_lua(file)
• access_by_lua(file)
• rewrite_by_lua(file)
What
• Databases: lua-resty-redis, lua-resty-
mysql, etc.
• Templates: lua-resty-template, etlua
• Frameworks: Lapis
• Preprocessors: Moonscript
(coffiescript-like syntax)
Where
• Image Server, for image resizes (now)
• Image Server, for queue, API, control
(in the future)
• Mobile detection
• EDGE-side block cache
• Maybe parts of SSO API, like cookie-
setter
For example...
Redis RESTfull api for userscores
• GET /scores
return userid list
• GET/PUT/POST/DELETE /scores/<id>
manipulate user scores
Init
http {
...
init_by_lua '
json = require "cjson";
redis = require "resty.redis"
';
...
server {
...
set $redis_host "192.168.2.104";
set $redis_port "6379";
set $redis_pass "nightmaremoon";
...
}
...
}
Init
local red = redis:new()
local ok, err = red:connect(ngx.var.redis_host, ngx.var.redis_port)
if not ok then
ngx.say("failed to connect: ", err)
return
end
local ok, err = red:auth(ngx.var.redis_pass)
if not ok then
ngx.say("failed to auth: ", err)
return
end
GET /scores
local keys, err = red:keys("*")
local scores = {}
for i, key in ipairs(keys) do
scores[key] = red:get(key)
end
ngx.header.content_type = "text/plain"
ngx.say(json.encode(scores))
GET /score/<userid>
location ~* ^/keys/(?<key>.*)$
{
content_by_lua '
-- ... (connect and auth)
local val, err = red:get("user:score:" ..
ngx.var.key)
ngx.say(json.encode({ value = val }))
';
}
DELETE /scores/<userid>
local method = ngx.req.get_method()
if method == "GET" then
...
elseif method == "PUT" then
...
elseif method == "DELETE" then
red:delete("user:score:" .. ngx.var.key)
ngx.say(json.encode({result = "success"}))
end
PUT /scores/<userid>
data =
json.decode(ngx.req.get_body_data())
red:set("user:score:" .. ngx.var.key,
data.value)
ngx.req.set_method(ngx.HTTP_GET)
ngx.exec("/scores/" .. ngx.var.key)
GET /scores/max
local max = 0
local keys = redis.call('keys', 'user:score:*');
for i, key in ipairs(keys) do
local value = tonumber(redis.call('get', key));
if value > max then
max = value
end
end
return max
GET /scores/max
local sha, err = red:script("load","...")
local val, err = red:evalsha(sha, 0)
ngx.say(json.encode({ max = val }))
GET /scores/max/<id1>,...,<idN>
local max = 0
for key in string.gmatch(ngx.var.key, '([^,]+)') do
local res = ngx.location.capture("/scores/" .. key)
data = json.decode(res.body)
if tonumber(data.value) > max then
max = tonumber(data.value)
end
end
ngx.say(json.encode({ max = max }))
What to read
• https://gist.github.com/isage/509d99cf4
def36014f5c
• http://wiki.nginx.org/HttpLuaModule
• http://openresty.org
• search github for lua-resty*
??????
Questions?
PROFIT!
2015, Epifanov Ivan
http://github.com/isage/

Weitere ähnliche Inhalte

Was ist angesagt?

Openstack at NTT Feb 7, 2011
Openstack at NTT Feb 7, 2011Openstack at NTT Feb 7, 2011
Openstack at NTT Feb 7, 2011
Open Stack
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational Databases
Karel Minarik
 

Was ist angesagt? (20)

{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com
 
Redis - Usability and Use Cases
Redis - Usability and Use CasesRedis - Usability and Use Cases
Redis - Usability and Use Cases
 
Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)Functional Operations (Functional Programming at Comcast Labs Connect)
Functional Operations (Functional Programming at Comcast Labs Connect)
 
Node.js - A Quick Tour II
Node.js - A Quick Tour IINode.js - A Quick Tour II
Node.js - A Quick Tour II
 
Introduction to redis - version 2
Introduction to redis - version 2Introduction to redis - version 2
Introduction to redis - version 2
 
Using Logstash, elasticsearch & kibana
Using Logstash, elasticsearch & kibanaUsing Logstash, elasticsearch & kibana
Using Logstash, elasticsearch & kibana
 
From zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and ElasticsearchFrom zero to hero - Easy log centralization with Logstash and Elasticsearch
From zero to hero - Easy log centralization with Logstash and Elasticsearch
 
Openstack at NTT Feb 7, 2011
Openstack at NTT Feb 7, 2011Openstack at NTT Feb 7, 2011
Openstack at NTT Feb 7, 2011
 
Everything as Code with Terraform
Everything as Code with TerraformEverything as Code with Terraform
Everything as Code with Terraform
 
Dirty - How simple is your database?
Dirty - How simple is your database?Dirty - How simple is your database?
Dirty - How simple is your database?
 
Paris Redis Meetup Introduction
Paris Redis Meetup IntroductionParis Redis Meetup Introduction
Paris Redis Meetup Introduction
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍
 
Redis modules 101
Redis modules 101Redis modules 101
Redis modules 101
 
Redis
RedisRedis
Redis
 
tdc2012
tdc2012tdc2012
tdc2012
 
Redis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational DatabasesRedis — The AK-47 of Post-relational Databases
Redis — The AK-47 of Post-relational Databases
 
Object Storage with Gluster
Object Storage with GlusterObject Storage with Gluster
Object Storage with Gluster
 
Ground Control to Nomad Job Dispatch
Ground Control to Nomad Job DispatchGround Control to Nomad Job Dispatch
Ground Control to Nomad Job Dispatch
 

Andere mochten auch

Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
Tony Fabeen
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014
ryanerickson
 
淺入淺出 GDB
淺入淺出 GDB淺入淺出 GDB
淺入淺出 GDB
Jim Chang
 
Gdb tutorial-handout
Gdb tutorial-handoutGdb tutorial-handout
Gdb tutorial-handout
Suraj Kumar
 
Las16 309 - lua jit arm64 port - status
Las16 309 - lua jit arm64 port - statusLas16 309 - lua jit arm64 port - status
Las16 309 - lua jit arm64 port - status
Linaro
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
Tony Fabeen
 
LAS16-400K2: TianoCore – Open Source UEFI Community Update
LAS16-400K2: TianoCore – Open Source UEFI Community UpdateLAS16-400K2: TianoCore – Open Source UEFI Community Update
LAS16-400K2: TianoCore – Open Source UEFI Community Update
Linaro
 

Andere mochten auch (20)

Nginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with LuaNginx Scripting - Extending Nginx Functionalities with Lua
Nginx Scripting - Extending Nginx Functionalities with Lua
 
Socket programming, and openresty
Socket programming, and openrestySocket programming, and openresty
Socket programming, and openresty
 
Nginx+lua在阿里巴巴的使用
Nginx+lua在阿里巴巴的使用Nginx+lua在阿里巴巴的使用
Nginx+lua在阿里巴巴的使用
 
Hacking Nginx at Taobao
Hacking Nginx at TaobaoHacking Nginx at Taobao
Hacking Nginx at Taobao
 
Lua tech talk
Lua tech talkLua tech talk
Lua tech talk
 
Lua as a business logic language in high load application
Lua as a business logic language in high load applicationLua as a business logic language in high load application
Lua as a business logic language in high load application
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUN
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014
 
Nginx lua
Nginx luaNginx lua
Nginx lua
 
淺入淺出 GDB
淺入淺出 GDB淺入淺出 GDB
淺入淺出 GDB
 
Gdb tutorial-handout
Gdb tutorial-handoutGdb tutorial-handout
Gdb tutorial-handout
 
Las16 309 - lua jit arm64 port - status
Las16 309 - lua jit arm64 port - statusLas16 309 - lua jit arm64 port - status
Las16 309 - lua jit arm64 port - status
 
Learn C Programming Language by Using GDB
Learn C Programming Language by Using GDBLearn C Programming Language by Using GDB
Learn C Programming Language by Using GDB
 
Perl在nginx里的应用
Perl在nginx里的应用Perl在nginx里的应用
Perl在nginx里的应用
 
基于OpenResty的百万级长连接推送
基于OpenResty的百万级长连接推送基于OpenResty的百万级长连接推送
基于OpenResty的百万级长连接推送
 
The basics and design of lua table
The basics and design of lua tableThe basics and design of lua table
The basics and design of lua table
 
高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践高性能Web服务器Nginx及相关新技术的应用实践
高性能Web服务器Nginx及相关新技术的应用实践
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
LAS16-400K2: TianoCore – Open Source UEFI Community Update
LAS16-400K2: TianoCore – Open Source UEFI Community UpdateLAS16-400K2: TianoCore – Open Source UEFI Community Update
LAS16-400K2: TianoCore – Open Source UEFI Community Update
 
OAuth and OpenID Connect for Microservices
OAuth and OpenID Connect for MicroservicesOAuth and OpenID Connect for Microservices
OAuth and OpenID Connect for Microservices
 

Ähnlich wie Nginx-lua

Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014
SergeyLerg
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
Simon Su
 

Ähnlich wie Nginx-lua (20)

Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
Building an ActionScript Game Server with over 15,000 Concurrent Connections
Building an ActionScript Game Server with over 15,000 Concurrent ConnectionsBuilding an ActionScript Game Server with over 15,000 Concurrent Connections
Building an ActionScript Game Server with over 15,000 Concurrent Connections
 
JavaScript in 2015
JavaScript in 2015JavaScript in 2015
JavaScript in 2015
 
Red Hat Forum Tokyo - OpenStack Architecture
Red Hat Forum Tokyo - OpenStack ArchitectureRed Hat Forum Tokyo - OpenStack Architecture
Red Hat Forum Tokyo - OpenStack Architecture
 
Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014Game Development with Corona SDK and Lua - Lua Workshop 2014
Game Development with Corona SDK and Lua - Lua Workshop 2014
 
Workshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - SuestraWorkshop Infrastructure as Code - Suestra
Workshop Infrastructure as Code - Suestra
 
Node.js
Node.jsNode.js
Node.js
 
Docker deploy
Docker deployDocker deploy
Docker deploy
 
Getting started with RDO Havana
Getting started with RDO HavanaGetting started with RDO Havana
Getting started with RDO Havana
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
0x01 - Breaking into Linux VMs for Fun and Profit
0x01 - Breaking into Linux VMs for Fun and Profit0x01 - Breaking into Linux VMs for Fun and Profit
0x01 - Breaking into Linux VMs for Fun and Profit
 
Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014Next Generation DevOps in Drupal: DrupalCamp London 2014
Next Generation DevOps in Drupal: DrupalCamp London 2014
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
Automating complex infrastructures with Puppet
Automating complex infrastructures with PuppetAutomating complex infrastructures with Puppet
Automating complex infrastructures with Puppet
 
Comredis
ComredisComredis
Comredis
 
Perl on Amazon Elastic MapReduce
Perl on Amazon Elastic MapReducePerl on Amazon Elastic MapReduce
Perl on Amazon Elastic MapReduce
 
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
From Zero To Production (NixOS, Erlang) @ Erlang Factory SF 2016
 
Nko workshop - node js crud & deploy
Nko workshop - node js crud & deployNko workshop - node js crud & deploy
Nko workshop - node js crud & deploy
 
R-House (LSRC)
R-House (LSRC)R-House (LSRC)
R-House (LSRC)
 

Kürzlich hochgeladen

scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
jaanualu31
 

Kürzlich hochgeladen (20)

Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Engineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planesEngineering Drawing focus on projection of planes
Engineering Drawing focus on projection of planes
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Learn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic MarksLearn the concepts of Thermodynamics on Magic Marks
Learn the concepts of Thermodynamics on Magic Marks
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086Minimum and Maximum Modes of microprocessor 8086
Minimum and Maximum Modes of microprocessor 8086
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 

Nginx-lua

  • 1. NGINX + Lua Using NGINX/OpenResty with embedded Lua Epifanov Ivan, Lead Developer
  • 2. Lua • Fast • Light (241K) • Simple • Powerfull • Embeddable • Portable Lua do Pesadelo (Nightmare Moon)
  • 3. Who uses Lua? • Games: WoW, Angry Birds, Baldur's Gate, Civilization V, Crysis, HoMM V, L.A. Noire, etc. • Software: Lightroom, MySQL proxy, MySQL Workbench, Celestia, Far Manager, GIMP, MediaWiki, etc. • Misc.: Mercedes Autos, LG Smart TV, Space Shuttle Gas Detection, etc.
  • 4. LuaJIT • JIT compilation for lua code • High performance (3-100x) • Low memory footprint • Crossplatform • Cross-architecture (x86, ARM, MIPS, PPC • local ffi = require("ffi") ffi.cdef[[ int printf(const char *fmt, ...); ]] ffi.C.printf("Hello %s!", "world")
  • 5. OpenResty/NGINX-LUA • NGINX bundle with luajit and additional modules. • Developed by TaoBao and CloudFlare • Access to every processing stage of nginx • Non-blocking without callback-hell • co-sockets, shared pool and sub- requests
  • 6. Full control • init_by_lua(file) • init_worker_by_lua(file) • set_by_lua(file) • log_by_lua(file) • content_by_lua(file) • header_filter_by_lua(file) • access_by_lua(file) • rewrite_by_lua(file)
  • 7. What • Databases: lua-resty-redis, lua-resty- mysql, etc. • Templates: lua-resty-template, etlua • Frameworks: Lapis • Preprocessors: Moonscript (coffiescript-like syntax)
  • 8. Where • Image Server, for image resizes (now) • Image Server, for queue, API, control (in the future) • Mobile detection • EDGE-side block cache • Maybe parts of SSO API, like cookie- setter
  • 9. For example... Redis RESTfull api for userscores • GET /scores return userid list • GET/PUT/POST/DELETE /scores/<id> manipulate user scores
  • 10. Init http { ... init_by_lua ' json = require "cjson"; redis = require "resty.redis" '; ... server { ... set $redis_host "192.168.2.104"; set $redis_port "6379"; set $redis_pass "nightmaremoon"; ... } ... }
  • 11. Init local red = redis:new() local ok, err = red:connect(ngx.var.redis_host, ngx.var.redis_port) if not ok then ngx.say("failed to connect: ", err) return end local ok, err = red:auth(ngx.var.redis_pass) if not ok then ngx.say("failed to auth: ", err) return end
  • 12. GET /scores local keys, err = red:keys("*") local scores = {} for i, key in ipairs(keys) do scores[key] = red:get(key) end ngx.header.content_type = "text/plain" ngx.say(json.encode(scores))
  • 13. GET /score/<userid> location ~* ^/keys/(?<key>.*)$ { content_by_lua ' -- ... (connect and auth) local val, err = red:get("user:score:" .. ngx.var.key) ngx.say(json.encode({ value = val })) '; }
  • 14. DELETE /scores/<userid> local method = ngx.req.get_method() if method == "GET" then ... elseif method == "PUT" then ... elseif method == "DELETE" then red:delete("user:score:" .. ngx.var.key) ngx.say(json.encode({result = "success"})) end
  • 15. PUT /scores/<userid> data = json.decode(ngx.req.get_body_data()) red:set("user:score:" .. ngx.var.key, data.value) ngx.req.set_method(ngx.HTTP_GET) ngx.exec("/scores/" .. ngx.var.key)
  • 16. GET /scores/max local max = 0 local keys = redis.call('keys', 'user:score:*'); for i, key in ipairs(keys) do local value = tonumber(redis.call('get', key)); if value > max then max = value end end return max
  • 17. GET /scores/max local sha, err = red:script("load","...") local val, err = red:evalsha(sha, 0) ngx.say(json.encode({ max = val }))
  • 18. GET /scores/max/<id1>,...,<idN> local max = 0 for key in string.gmatch(ngx.var.key, '([^,]+)') do local res = ngx.location.capture("/scores/" .. key) data = json.decode(res.body) if tonumber(data.value) > max then max = tonumber(data.value) end end ngx.say(json.encode({ max = max }))
  • 19. What to read • https://gist.github.com/isage/509d99cf4 def36014f5c • http://wiki.nginx.org/HttpLuaModule • http://openresty.org • search github for lua-resty*