Ngx+Lua+Redis 快速存储POST数据

系统几万台设备有windows有安卓还有linux系统,每个设备三分钟就会向服务器post设备的硬件信息,数据格式json,后台管理界面只需要最新的数据,不需要历史数据,业务逻辑非常简单,PHP代码就几行,已经优化到极致了,但是架不住频率太高了。服务器负载就被这个的简单逻辑给耗尽。历史原因客户端已经不可能修改,只能在服务端进行优化了。

做法也很简单就是不用php-fpm,nginx接收到数据,直接把post数据存储到redis里面,供管理后台直接使用。

ngx如何连接redis请参考我的另一篇文件
Ngx+Lua+Redis 实时IP黑名单系统https://blog.csdn.net/hangbobo/article/details/142763400在这里我只接上代码

复制代码
local my_cache = ngx.shared.my_cache
local redis_connect=loadstring(my_cache:get("redis_connect"))
local red=redis_connect()
red:hincrby('store_ip:02','hardware',1)

local auth_header = ngx.req.get_headers()["Authorization"]
if string.len(auth_header) > 8 then
    local token = string.sub(auth_header,8)
    if string.len(token) > 0 then
        ngx.req.read_body() 
        
        local data = ngx.req.get_body_data()
        local cjson = require "cjson.safe"
        local obj = cjson.decode(data)
        obj.time=os.date("%Y-%m-%d %H:%M:%S", ngx.time())
        data=cjson.encode(obj)
        red:hset('hardware',token,data)
        ngx.say('{"msg":"succeed","status_code":200,"data":['..data..']}')
        ngx.exit(200)
    end
end
ngx.exit(404)

解析json代码并增加当前时间这个是非必须的,只是为了验证数据是不是最新提交的。

我的设备唯id是,通过header头的"Authorization" 传递的,你需要结合你你的实际代码。

代码存储为 /www/server/nginx/conf/hardware.lua

nginx配置

复制代码
lua_shared_dict my_cache 10m;
server
{
    listen 80;
    listen 443 ssl;
    http2 on;
    ...........
    
    default_type 'application/json';    
    access_by_lua_file /www/server/nginx/conf/access.lua; 

    location /boxs/hardware {
        access_by_lua_file /www/server/nginx/conf/hardware.lua;
    }

    ...........
}
相关推荐
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1232 天前
matlab画图工具
开发语言·matlab
dustcell.2 天前
haproxy七层代理
java·开发语言·前端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月2 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237172 天前
C语言-数组练习进阶
c语言·开发语言·算法
Railshiqian2 天前
给android源码下的模拟器添加两个后排屏的修改
android·开发语言·javascript
雪人不是菜鸡2 天前
简单工厂模式
开发语言·算法·c#