APISIX插件调用C方法开发入门
一、前置知识
1、需要了解APISIX的插件开发,即通过lua语言开发APISIX的个性化插件的方法,若不会可自行百度。
2、需要了解Lua、Luajit、Lua的ffi
3、需要C、C++的Linux环境,保证可以使用GCC、G++编译指令
二、入门案例
1、新建calcmath.cpp
#include <iostream>
#include <cmath>
#include <stdio.h>
//using namespace std;
extern "C" {
float isquare(float val);
double isqrt(double val);
void ivecadd(double* a, double* b, int len);
}
float isquare(float val)
{
return val*val;
}
double isqrt(double val)
{
return sqrt(val);
}
void ivecadd(double* a, double* b, int len)
{
for (int i = ; i < len; ++i)
{
a[i] = a[i] + b[i];
}
}
以上代码包含简单的三个函数,isquare计算平方,isqrt计算开方,ivecadd计算两个数组对应元素之和。
2、使用命令,编译该cpp文件为.so结尾的动态库
g++ -shared -fPIC -o libcalcmath.so calcmath.cpp
此时当前文件夹内会生成libcalcmath.so,为了调用便利,我们把它复制一份到/usr/local/lib下,方便插件寻找。
3、我们编写Lua插件,暂时可命名为helloworld.lua,使用ffi调用我们在c++/c里面实现的函数
local core = require("apisix.core")
local ffi = require("ffi")
local calcmath = {}
local plugin_name = "helloworld"
local schema = {
type = "object",
properties = {
content = {
type = "string"
}
}
}
local _M = {
version = 0.2,
priority = 5000,
name = plugin_name,
schema = schema
}
-- int testzkfun();
-- float isquare666(float val);
ffi.cdef[[
float isquare(float val);
double isqrt(double val);
void ivecadd(double* a, double* b, int len);
]]
calcmath.C = ffi.load('calcmath')
local testval = calcmath.C.isquare(5)
local testval1 = calcmath.C.isqrt(25)
function _M.access(conf, ctx)
-- print helloworld
core.log.warn("helloworld,newland test.....begin......")
core.log.warn(testval)
core.log.warn(testval1)
core.log.warn("helloworld,newland test.....end......")
end
return _M
4、使用命令,创建一个使用该插件的路由地址
curl http://127.0.0.1:9080/apisix/admin/routes/3 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -i -d '
{
"uri": "/test1",
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:8080": 1
}
}
"plugins": {
"helloworld": {
},
}
}'
5、访问该路由地址,然后到apisix的error.log日志下查看打印