首页 > 解决方案 > Nginx/NChan PubSub - 如何修改传入消息

问题描述

我寻求一个简单的 pubsub 服务器来处理我的 Android 应用程序相对适度的发布/订阅需求,这导致我选择了 Nchan——一个 Nginx 扩展。NChan 非常灵活且易于设置。在大多数情况下,我已经能够通过它的文档工作并理解所需的一切。但是,有一个问题仍然困扰着我:

NChan 的一项功能是在允许将传入消息发布并提供给其他客户端之前将其转发给上游处理。文档的消息转发部分指出

上游响应代码确定发布将如何进行:304 Not Modified 将消息按接收到的方式发布,不进行修改。204 No Content 丢弃消息 200 OK 用于修改消息。此 HTTP 响应中包含的消息不是原始传入消息,而是发布

我必须看看它是如何工作的测试堆栈如下

我的 Nginx 配置

location ~ /pub/(\w+)$ 
{
 nchan_publisher;
 nchan_channel_id "$1"; #first capture of the location match
 nchan_publisher_upstream_request /beforepub;
}

location = /beforepub 
{
 proxy_pass https://another-example.com/beforepub/;
 proxy_set_header X-Publisher-Type $nchan_publisher_type;
 proxy_set_header X-Prev-Message-Id $nchan_prev_message_id;
 proxy_set_header X-Channel-Id $nchan_channel_id;
 proxy_set_header X-Original-URI $request_uri;
 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 proxy_set_header Upgrade $http_upgrade;
 proxy_set_header Connection "upgrade";
} 

我实质上是在接收入站消息并将其转发到以下脚本处理它 /beforepub/的同一服务器上。index.php

我想对这条转发的消息做两件事之一

“记录一些信息:在本地数据库中,通常与X-Channel-ID标头相关,然后返回204标头,以便不发布任何内容

<?php
 header("HTTP/1.1 204 OK");
 $channelID = getallheaders()['X-Channel-ID'];
 //inspect and record the channel ID
?>

返回修改后的响应

<?php
 header("HTTP/1.1 200 OK");
 $headers = getallheaders();
 $channelID = $headers['X-Channel-ID'];
 //return a response dependendent on the channelID
 echo "modified response";
?>

希望该频道的其他订阅者看到的内容将被修改响应

为了在我使用的第一个实例中测试这种行为

NChan 可以接受使用wsshttp(s)协议的 pubsub 连接。我wss用于subSimple Websocket Client、SWC上的连接和Advanced REST 客户端ARChttps上的 pub 连接。

有了这个,我通过SWC在“alpha 通道”上订阅消息

wss://example.com:443/sub/alpha

在ARC和 POST的同一“alpha 通道”上连接并发布消息,并将其发布到https://example.com/pub/alpha内容为 POST的 url original content。我发现SWC正在返回一个空响应

[2020-01-30 18:04:14.204]

我不清楚这是否是因为我的 Nginx 代理设置错误,或者只是完全误解了现在 NChan 转发应该可以工作。

标签: nginxpublish-subscribenchan

解决方案


推荐阅读