配置nginx stream TCP反向代理,在server中配置preread_by_lua_file,lua脚本只有在连接建立时执行一次,再发送报文就不执行了,现在想过滤每个数据报文,具体配置如下:

stream {
lua_code_cache on;
log_format basic '$remote_addr [$time_local] '
'$protocol $status $bytes_sent $bytes_received '
'$session_time $upstream_addr';
access_log logs/stream-access.log basic;
upstream mqtt {
server 127.0.0.1:8883 max_fails=3 fail_timeout=30s;
}

server {
listen 8001 so_keepalive=2m:2s:3;
proxy_connect_timeout 1s;
proxy_pass mqtt;
#proxy_timeout 60s;
preread_by_lua_file "/usr/local/openresty/nginx/mqtt-proxy.lua";
}
}

    stream特别MQTT都是长连接,preread自然仅在初始连接时有效,并且仅仅是用来做最初检查。你如果要过滤所有报文,意味着你必须读取socket传入的数据,这会导致socket内的数据无法向后传递

    It is possible to acquire the raw request socket using ngx.req.socket and receive data from or send data to the client. However, keep in mind that calling the receive() method of the request socket will consume the data from the buffer and such consumed data will not be seen by handlers further down the chain.

    所以,如果要过滤的话,你可能不能用单纯的反向处理,而是需要将服务器作为一个独立的MQTT服务器,接受数据,然后同时作为一个mqtt client转发数据到目标mqtt服务器。

      Write a Reply...