V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
爱意满满的作品展示区。
iamtsm
V2EX  ›  分享创造

怎么样写一个 API 网关

  •  
  •   iamtsm ·
    iamtsm · 2022-08-15 11:18:38 +08:00 · 2398 次点击
    这是一个创建于 614 天前的主题,其中的信息可能已经有所发展或是发生改变。

    关于我在平时摸鱼时,写了一个 API 网关的事情,事情是这样的。

    有次在修 bug 的时候,发现了一些静态化的 bug ,追查发现是运维那边 nginx lua 脚本写的一些缓存机制导致,顺带看了几眼代码,结果一发不可收拾,居然想自己也写一个,然后经过不断优化迭代就把 API 网关写出来了。有兴趣大佬了解下点点赞,欢迎一起维护

    github.com/iamtsm/tl-ops-manage

    10 条回复    2022-09-19 16:14:02 +08:00
    bugfan
        1
    bugfan  
       2022-08-15 12:38:48 +08:00
    awanganddong
        2
    awanganddong  
       2022-08-16 11:43:50 +08:00
    @bugfan 请教个简单问题,怎么用 lua 对后端业务进行处理,我直接在 nginx.conf 文件写代码没有问题,但是
    如果外接脚本就一直无效。


    server {
    listen 80;
    server_name test.com;
    root /www/test/public/;

    access_log /var/log/nginx/test.log;
    error_log /var/log/nginx/test_error.log;

    location /{
    content_by_lua_file /etc/nginx/conf.d/lua/bitian.lua;
    if (!-e $request_filename) {
    rewrite ^(.*)$ /index.php?s=/$1 last;
    }
    }
    location ~ \.php$ {
    fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    }
    }
    iamtsm
        3
    iamtsm  
    OP
       2022-08-16 15:53:32 +08:00
    @awanganddong 要看你 lua 包有没有引入正确,查下这个配置 lua_package_path
    awanganddong
        4
    awanganddong  
       2022-08-16 17:38:34 +08:00
    @iamtsm lua_package_path 这个是配置 lua 模块的。

    我在 nginx.conf 配置 lua 是可以正常执行的
    但是现在想从中抽离开来就不知道怎么处理了
    whitecosm0s
        5
    whitecosm0s  
       2022-08-16 17:46:34 +08:00
    当然是用 apijson 啦!!!
    iamtsm
        6
    iamtsm  
    OP
       2022-08-16 17:52:54 +08:00
    @awanganddong 抽到 file 和在 block 里面写是一样的,不过我看你的问题说的是外接脚本无效,就怀疑是路径问题,其实可以 ngx.log 调试下看看有没有执行到对应的 xxx.lua
    awanganddong
        7
    awanganddong  
       2022-08-17 09:53:33 +08:00
    好的,我查看下
    hobbyliu
        8
    hobbyliu  
       2022-08-19 11:29:27 +08:00
    apisix 了解一下。。
    iamtsm
        9
    iamtsm  
    OP
       2022-08-19 13:49:09 +08:00
    @hobbyliu 哈哈,这个我知道,那个是大佬写的。
    awanganddong
        10
    awanganddong  
       2022-09-19 16:14:02 +08:00
    终于知道问题出在哪里了

    location 的优先级 是高于 content_by_lua_file 的

    这个是 nginx 与 lua 优先级问题


    可以这样写

    location ~ \.php$ {

    access_by_lua_file /etc/nginx/conf.d/lua/bitian.lua;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_index index.php;
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2638 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 15:27 · PVG 23:27 · LAX 08:27 · JFK 11:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.