Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #18

Merged
merged 2 commits into from May 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
39 changes: 33 additions & 6 deletions README.md
Expand Up @@ -87,8 +87,38 @@ return _M

```

> 访问结果

```shell
curl https://api.lua-china.com/index?id=1&foo=bar

{
"msg": "request args",
"status": 0,
"data": {
"foo": "bar",
"id": "1"
}
}
```

## 压力测试

### 不使用数据库只输出 json

#### 阿里云单核4G内存

```shell
ab -c 100 -n 10000 api.lua-china.com/index

---
Requests per second: 2220.06 [#/sec] (mean)
Time per request: 45.044 [ms] (mean)
---
```

> 内存基本没有变化,单核 CPU 打满

### 单次 mysql 数据库查询

#### mac 4核 i7 16G 内存 固态硬盘
Expand All @@ -111,8 +141,7 @@ Time per request: 31.992 [ms] (mean)

### 本地化

通过给 `ngx.ctx.locale` 赋值来更换语言环境,如:
`ngx.ctx.locale = zh`
使用 local 的 middleware 加在路由前,该中间件通过给 `ngx.ctx.locale` 赋值来更换语言环境:`ngx.ctx.locale = zh`

### 路由

Expand Down Expand Up @@ -213,7 +242,7 @@ local data = cjson.decode(res.body)
框架使用的 `lib/response.lua` 中的 `json` 方法通过定义数字来代表不同的`response`类型,该方法支持三四个参数

1. 第一个参数是状态码,16进制状态码对应 `config/status.lua`
2. 第二个参数是错误码文案,文案根据第一个参数对应 `config/status.lua` 中的文案
2. 第二个参数是错误码文案,默认值是根据第一个参数对应 `config/status.lua` 中的文案
3. 第三个参数是需要向前端返回的数据,可省略
4. 第四个参数是返回的 `http 状态码`,可省略,默认是200

Expand Down Expand Up @@ -524,9 +553,7 @@ table_remove(tab, {'item1', 'item2'})
> lua 中的`hash table`按`key`排序与其他语言不同,我们需要自己实现一个迭代器来遍历排好序的`table`

```lua
for k,v in pairsByKeys(hashTable) do
...
end
sort_by_key(hashTable)
```

## 代码规范
Expand Down
13 changes: 2 additions & 11 deletions bootstrap.lua
@@ -1,14 +1,5 @@
-- Github Document: https://github.com/horan-geeker/nana
-- Author: hejunwei
-- Version: v0.4.0
-- Version: v0.5.0

local Core = {}

function Core:bootstrap()
-- get helper function
require('lib.helpers'):init(_G)
-- run application
require("lib.application"):init():run()
end

Core:bootstrap()
require("lib.application"):init(_G):run()
2 changes: 2 additions & 0 deletions config/status.lua
Expand Up @@ -25,6 +25,8 @@ return {
[0x010007] = '重置密码失败,新密码不能和旧密码相同',
[0x010008] = '获取用户信息失败,系统错误',
[0x010009] = '重置密码失败,用户不存在',
[0x01000A] = '获取用户信息失败,用户未登录',
[0x01000B] = '获取用户信息失败,用户不存在',

-- notify module
[0x020001] = '发送短信验证码失败,请在60秒之后重试',
Expand Down
4 changes: 2 additions & 2 deletions controllers/notify/sms_notify_controller.lua
Expand Up @@ -20,7 +20,7 @@ function _M:guest_send_sms()
if not ok then
return response:json(1, err)
end
local res = sms_service:sendSMS(args['phone'])
local res = sms_service:send_sms(args['phone'])
if res ~= true then
return response:json(res)
end
Expand All @@ -29,7 +29,7 @@ end

function _M:user_send_sms()
local user = auth:user()
local res = sms_service:sendSMS(user.phone)
local res = sms_service:send_sms(user.phone)
if res ~= true then
return response:json(res)
end
Expand Down
3 changes: 3 additions & 0 deletions controllers/user_controller.lua
Expand Up @@ -7,6 +7,9 @@ local _M = {}

function _M:show(id)
local user = User:find(id)
if not user then
return response:json(0x01000B)
end
return response:json(0, '', user)
end

Expand Down
22 changes: 19 additions & 3 deletions lib/application.lua
@@ -1,12 +1,28 @@
local router = require('lib.router')
local request = require('lib.request')
local database = require('lib.database')

local _M = {}

function _M:init()
function _M:init(G)
-- init helper function
require('lib.helpers'):init(G)
-- init route
router:init()
return self
end

function _M:run()
-- dispatche route to controller
require('lib.router'):init()
-- match route, dispatch request to action
local http_response, http_status = router:run()
-- do some thing after run action
self:terminate(request:all(), response_content)
-- dispatch route to controller
require('lib.response'):send(http_response, http_status)
end

function _M:terminate(request, resposne)
database:close()
end

return _M
10 changes: 1 addition & 9 deletions lib/database.lua
Expand Up @@ -42,13 +42,6 @@ function _M:get_connection()
return nil, err
end
-- ngx.log(ngx.WARN, self.db_type, ' mysql connect')
-- set time zone
local query = 'SET time_zone = "'..self.time_zone..'"'
local res, err, errcode, sqlstate = db:query(query)
if not res then
ngx.log(ngx.ERR, res, err, errcode, sqlstate)
return nil, err
end
ngx.ctx[self.db_type] = db
return db, nil
end
Expand Down Expand Up @@ -79,7 +72,7 @@ end
@return bool, data, err
--]]
function _M.mysql_query(self, sql)
-- ngx.log(ngx.ERR, self.db_type, sql)
-- ngx.log(ngx.WARN, self.db_type, sql)
local db, err = self:get_connection()
if err ~= nil then
return nil, err
Expand All @@ -106,7 +99,6 @@ function _M.new(self, opts)
max_packet_size = 1024 * 1024,
db_pool_timeout = opts.pool_timeout or 1000,
db_pool_size = opts.pool_size or 1000,
time_zone = opts.time_zone or '+8:00',
db_type = opts.db_type,
}, mt)
end
Expand Down
50 changes: 18 additions & 32 deletions lib/helpers.lua
@@ -1,6 +1,3 @@
local cookie_obj = require("lib.cookie")
local cjson = require("cjson")

local _M = {}

function _M:init(G)
Expand Down Expand Up @@ -36,7 +33,7 @@ function _M:init(G)
-- remove item in table
function G.table_remove(tab, rm)
local result = tab
for k, v in pairs(rm) do
for k, v in pairs(rm) do
for a_k, a_v in pairs(result) do
-- array
if type(a_k) == 'number' then
Expand All @@ -51,8 +48,8 @@ function _M:init(G)
if v == a_k then
result[a_k] = nil
end
end
end
end
end
end
return result
end
Expand All @@ -78,29 +75,28 @@ function _M:init(G)
return string.sub(implode_str, 1, #implode_str - 1)
end
-- sort a hashTable by key
-- use example: for k,v in pairsByKeys(hashTable)
function G:pairsByKeys(f)
function G.sort_by_key(tab)
local a = {}
for n in pairs(self) do
for n in pairs(tab) do
table.insert(a, n)
end
table.sort(a, f)
table.sort(a)
local i = 0 -- iterator variable
local iter = function()
-- iterator function
i = i + 1
if a[i] == nil then
return nil
if a[i] then
return a[i], tab[a[i]]
else
return a[i], self[a[i]]
return nil
end
end
return iter
end

function G.set_cookie(key, value, expires)
local config = require("config.app")
local cookie, err = cookie_obj:new()
local cookie, err = require("lib.cookie"):new()
if not cookie then
ngx.log(ngx.ERR, err)
return false, err
Expand All @@ -123,17 +119,16 @@ function _M:init(G)
return true
end

function G:get_cookie()
local key = self
local cookie, err = cookie_obj:new()
function G.get_cookie(key)
local cookie, err = require("lib.cookie"):new()
if not cookie then
ngx.log(ngx.ERR, err)
return false
end
return cookie:get(key)
end

function G:get_local_time()
function G.get_local_time()
local config = require("config.app")
local time_zone = ngx.re.match(config.time_zone, "[0-9]+")
if time_zone == nil then
Expand All @@ -146,24 +141,15 @@ function _M:init(G)
return time_zone[0] * 3600 + ngx.time()
end

function G.purge_uri(uri)
local uri = string.gsub(uri, "?.*", "")
local uri_without_slash = remove_slash(uri)
return uri_without_slash
end

function G.remove_slash(target)
local len = string.len(target)
if string.find(target,'/', len) then
return string.sub(target, 1, len-1)
end
return target
function G.trim(str, symbol)
symbol = symbol or '%s' -- %s default match space \t \n etc..
return (string.gsub(string.gsub(str, '^' .. symbol .. '*', ""), symbol .. '*$', ''))
end

function G.hash(password)
return ngx.md5(password)
end

-- data not in order
function G.log(...)
local args = {}
Expand All @@ -172,7 +158,7 @@ function _M:init(G)
else
args = ...
end
ngx.log(ngx.WARN, cjson.encode(args))
ngx.log(ngx.WARN, require("cjson").encode(args))
end
end

Expand Down
2 changes: 0 additions & 2 deletions lib/model.lua
Expand Up @@ -20,7 +20,6 @@ local database_write = Database:new({
timeout = database_config.mysql.timeout,
db_pool_timeout = database_config.mysql.pool_timeout,
db_pool_size = database_config.mysql.pool_size,
time_zone = config.time_zone,
db_type = WRITE
})

Expand All @@ -34,7 +33,6 @@ local database_read = Database:new({
timeout = database_config.mysql.timeout,
db_pool_timeout = database_config.mysql.pool_timeout,
db_pool_size = database_config.mysql.pool_size,
time_zone = config.time_zone,
db_type = READ
})

Expand Down
8 changes: 8 additions & 0 deletions lib/request.lua
Expand Up @@ -42,4 +42,12 @@ function _M:headers()
return ngx.req.get_headers()
end

function _M:get_uri()
return string.gsub(ngx.var.request_uri, '?.*$', '')
end

function _M:get_method()
return ngx.var.request_method
end

return _M
7 changes: 7 additions & 0 deletions lib/response.lua
Expand Up @@ -28,4 +28,11 @@ function _M:error(error_message)
ngx.exit(500)
end

function _M:send(content, status)
if content ~= nil and content ~= '' then
ngx.say(content)
end
ngx.exit(status)
end

return _M