app.lua 2.4 KB

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