app.lua 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. local mysql = mysql
  2. local encode = encode
  3. local random = math.random
  4. local min = math.min
  5. local insert = table.insert
  6. local sort = table.sort
  7. local template = require'resty.template'
  8. local ngx = ngx
  9. local ngx_print = ngx.print
  10. template.caching(false)
  11. -- Compile template, disable cache, enable plain text view to skip filesystem loading
  12. local view = template.compile([[<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>{% for _,f in ipairs(fortunes) do %}<tr><td>{{ f.id }}</td><td>{{ f.message }}</td></tr>{% end %}</table></body></html>]], nil, true)
  13. local mysqlconn = {
  14. host = os.getenv("DBIP"),
  15. port = 3306,
  16. database = "hello_world",
  17. user = "benchmarkdbuser",
  18. password = "benchmarkdbpass"
  19. }
  20. local _M = {}
  21. function _M.db()
  22. local db = mysql:new()
  23. assert(db:connect(mysqlconn))
  24. ngx_print(encode(db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]))
  25. db:set_keepalive(0, 256)
  26. end
  27. function _M.queries()
  28. local db = mysql:new()
  29. assert(db:connect(mysqlconn))
  30. local num_queries = tonumber(ngx.var.arg_queries) or 1
  31. -- May seem like a stupid branch, but since we know that
  32. -- at a benchmark it will always be taken one way,
  33. -- it doesn't matter. For me, after a small warmup, the performance
  34. -- is identical to a version without the branch
  35. -- http://wiki.luajit.org/Numerical-Computing-Performance-Guide
  36. if num_queries < 2 then
  37. ngx_print(encode({db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]}))
  38. else
  39. local worlds = {}
  40. num_queries = min(500, num_queries)
  41. for i=1, num_queries do
  42. worlds[#worlds+1] = db:query('SELECT * FROM World WHERE id = '..random(1,10000))[1]
  43. end
  44. ngx_print( encode(worlds) )
  45. end
  46. db:set_keepalive(0, 256)
  47. end
  48. function _M.fortunes()
  49. local db = mysql:new()
  50. assert(db:connect(mysqlconn))
  51. local fortunes = db:query('SELECT * FROM Fortune')
  52. insert(fortunes, {
  53. id = 0,
  54. message = "Additional fortune added at request time."
  55. })
  56. sort(fortunes, function(a, b)
  57. return a.message < b.message
  58. end)
  59. local res = view{fortunes=fortunes}
  60. ngx.header['Content-Length'] = #res
  61. ngx_print(res)
  62. db:set_keepalive(0, 256)
  63. end
  64. return _M