카테고리 없음
APISIX + Lua + RESTHeart 이용해서 MongoDB (조회/등록/삭제/수정)
ipxy
2025. 4. 16. 07:48
728x90
APISIX + Lua (LUR: Lua Runtime) + RESTHeart 조합으로, API Gateway 단계에서 MongoDB REST API를 이용해 조회/등록/삭제/수정
✅ 구조 개요
APISIX에서 Lua 플러그인을 이용하여 RESTHeart에 HTTP 요청을 보내고, 결과를 클라이언트에 전달하는 방식입니다:
[Client] ---> [APISIX + Lua Plugin] ---> [RESTHeart (MongoDB REST API)]
1. APISIX Lua 플러그인 예제 구성
1-1. 기본 구조 (rest-crud.lua)
local http = require("resty.http")
local cjson = require("cjson.safe")
local _M = {}
function _M.access(conf, ctx)
local method = ctx.var.request_method
local uri_args = ngx.req.get_uri_args()
local path = uri_args["path"] or "/users"
local id = uri_args["id"]
local url = "http://restheart.default.svc" .. path
if id then
url = url .. "/" .. id
end
local httpc = http.new()
local res, err
if method == "GET" then
res, err = httpc:request_uri(url, {
method = "GET"
})
elseif method == "POST" then
ngx.req.read_body()
local body = ngx.req.get_body_data()
res, err = httpc:request_uri(url, {
method = "POST",
body = body,
headers = {
["Content-Type"] = "application/json"
}
})
elseif method == "PUT" then
ngx.req.read_body()
local body = ngx.req.get_body_data()
res, err = httpc:request_uri(url, {
method = "PUT",
body = body,
headers = {
["Content-Type"] = "application/json"
}
})
elseif method == "DELETE" then
res, err = httpc:request_uri(url, {
method = "DELETE"
})
end
if not res then
return 500, { message = "request to RESTHeart failed: " .. (err or "unknown") }
end
ngx.status = res.status
ngx.header["Content-Type"] = "application/json"
ngx.say(res.body)
return ngx.exit(res.status)
end
return _M
2. APISIX 플러그인 등록
conf/config.yaml 또는 대시보드를 통해 커스텀 Lua 플러그인으로 등록합니다.
예를 들어 /apisix/plugins/rest-crud.lua 경로에 저장하고, config.yaml에 다음과 같이 추가:
plugins:
- rest-crud
APISIX 재시작 후 사용 가능.
3. 플러그인 적용 예시
curl -X PUT http://localhost:9180/apisix/admin/routes/999 \
-H "X-API-KEY: your-admin-token" \
-H "Content-Type: application/json" \
-d '{
"uri": "/crud",
"plugins": {
"rest-crud": {}
},
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:80": 1
}
}
}'
4. 클라이언트 사용 예시
조회 (GET)
curl "http://localhost:9080/crud?path=/users&id=user123"
등록 (POST)
curl -X POST "http://localhost:9080/crud?path=/users" \
-H "Content-Type: application/json" \
-d '{"_id": "user123", "name": "홍길동", "email": "hong@test.com"}'
수정 (PUT)
curl -X PUT "http://localhost:9080/crud?path=/users&id=user123" \
-H "Content-Type: application/json" \
-d '{"name": "김철수", "email": "chulsoo@test.com"}'
삭제 (DELETE)
curl -X DELETE "http://localhost:9080/crud?path=/users&id=user123"
✅ 보완 팁
기능 | 설명 |
인증 필요 시 | headers["Authorization"] = "Basic ..." or "Bearer ..." 추가 |
RESTHeart URL 고정 | Lua에 상수로 지정하거나 플러그인 config로 받아 처리 가능 |
에러 핸들링 | res.status 검사하여 JSON 에러 메시지로 통일 가능 |
속도 향상 | httpc:set_timeout(1000) 등 설정 추가 |
728x90