Apache APISIX 插件开发完全指南
apisix The Cloud-Native API Gateway 项目地址: https://gitcode.com/gh_mirrors/ap/apisix
前言
Apache APISIX 作为云原生 API 网关,其强大的插件系统是其核心优势之一。本文将全面介绍如何在 APISIX 中开发自定义插件,从基础概念到高级功能实现,帮助开发者掌握插件开发的完整流程。
插件开发基础
插件放置路径
APISIX 提供了灵活的插件加载机制,开发者可以通过两种方式添加新功能:
- 直接修改源码(不推荐):直接修改 APISIX 源代码并重新发布
- 外部加载方式(推荐):通过配置
extra_lua_path
和extra_lua_cpath
加载自定义代码
推荐的项目目录结构示例:
├── example
│ └── apisix
│ ├── plugins
│ │ └── custom-plugin.lua
│ └── stream
│ └── plugins
│ └── custom-plugin.lua
在 conf/config.yaml
中添加配置:
apisix:
extra_lua_path: "/path/to/example/?.lua"
覆盖内置方法
如需覆盖内置方法,可配置 lua_module_hook
:
apisix:
extra_lua_path: "/path/to/example/?.lua"
lua_module_hook: "my_hook"
插件核心开发
插件定义
每个插件需要定义以下基本属性:
local plugin_name = "custom-plugin"
local _M = {
version = 0.1,
priority = 100, -- 优先级设置
name = plugin_name,
schema = schema, -- 配置schema
metadata_schema = metadata_schema, -- 元数据schema
}
优先级说明:
- 数值越大优先级越高
- 建议新插件使用1-99之间的优先级
- 可通过控制API查看现有插件优先级
配置校验
使用JSON Schema定义配置格式并进行校验:
local schema = {
type = "object",
properties = {
param1 = {type = "number", minimum = 0},
param2 = {type = "string"},
},
required = {"param1"},
}
function _M.check_schema(conf)
return core.schema.check(schema, conf)
end
敏感数据加密
对于密码等敏感信息,可配置自动加密:
encrypt_fields = {"password", "db.password"}
需在config.yaml中启用加密:
apisix:
data_encryption:
enable: true
keyring:
- encryption_key_1
- encryption_key_2
插件执行阶段
APISIX插件可在以下阶段执行:
- rewrite阶段:适合认证逻辑
- access阶段:适合在代理到上游前执行的逻辑
- delayed_body_filter:APISIX特有阶段,在body_filter之后执行
重要限制:
- 不能在rewrite和access阶段直接调用
ngx.exit
等退出函数 - 如需退出,应返回状态码和正文
功能实现
核心方法实现
插件主要实现阶段方法:
function _M.rewrite(conf, ctx)
-- rewrite阶段逻辑
end
function _M.access(conf, ctx)
-- access阶段逻辑
end
参数说明:
conf
:插件配置参数ctx
:请求上下文信息
公共API注册
插件可注册公共接口:
function _M.api()
return {
{
methods = {"GET"},
uri = "/apisix/plugin/custom/endpoint",
handler = handler_func,
}
}
end
注意:需要通过public-api插件显式暴露这些接口
控制API注册
注册仅供内网访问的API:
function _M.control_api()
return {
{
methods = {"GET"},
uris = {"/v1/plugin/custom/internal"},
handler = internal_handler,
}
}
end
自定义变量
注册全局可用变量:
core.ctx.register_var("custom_var", function(ctx)
-- 计算变量值
return value
end)
测试开发
APISIX使用test-nginx框架进行测试,测试用例通常包含三部分:
- 程序代码:Nginx location配置
- 输入:HTTP请求信息
- 输出检查:响应状态、头部、正文等
示例测试用例:
=== TEST 1: basic test
--- config
location /t {
content_by_lua_block {
-- 测试代码
}
}
--- request
GET /t
--- response_body
expected output
--- no_error_log
[error]
最佳实践
- 命名规范:插件名应具有唯一性且能清晰表达功能
- 错误处理:完善的参数校验和错误处理机制
- 性能考量:避免在插件中执行耗时操作
- 资源清理:在destroy方法中释放资源
- 文档完善:为插件编写清晰的使用文档
总结
通过本文,我们全面了解了Apache APISIX插件开发的各个方面。从基础配置到高级功能实现,从核心逻辑编写到测试用例开发,掌握这些知识后,开发者可以高效地为APISIX开发各种功能插件,扩展网关能力。
apisix The Cloud-Native API Gateway 项目地址: https://gitcode.com/gh_mirrors/ap/apisix
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考