我的项目使用Nodejs作为代理服务器与外部API进行通信。了解如何在Node.js和服务器发送事件中使用Redis
API通过Redis发送产品更新(pub/sub);代理服务器处理消息并通过SSE(服务器发送事件)将其发送给客户端。
这是我第一次使用Redis和SSE,在网上寻找教程似乎很容易实现,我做到了。
在客户端上我刚刚创建的EventSource
和我收到的更新我用它做什么:
// Client Side
var source = new EventSource('/redis'); // /redis is path to proxy server
source.addEventListener('items', handleItemsCallback, false);
source.addEventListener('users', handleUsersCallback, false);
source.addEventListener('customers', handleCustomersCallback, false);
// Function sample...
function handleItemsCallback (msg) {
// Do something with msg...
}
在代理服务器上我创建了路由控制器来/redis
处理Redis的消息:
exports.redisUpdates = function (req, res) {
// Redis Authentication
var redisURL = url.parse(process.env.REDISCLOUD_URL);
var client = redis.createClient(redisURL.port, redisURL.hostname, {ignore_subscribe_messages: false});
client.auth(redisURL.auth.split(":")[1]);
// let request last as long as possible
req.socket.setTimeout(0);
// Subscribe to channels
client.subscribe('items', 'users', 'customers');
// Handle messages
client.on('message', function (channel, message) {
res.write('retry: 5000\n');
res.write('event: ' + channel + '\n');
res.write('data: ' + message + '\n\n');
res.flush(); // If I do not add this it doesn't push updates to the client (?)
});
//send headers for event-stream connection
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
};
使用在本地开发环境中它工作正常,但在生产中使用它产生几种不同的错误,应用程序是在托管的Heroku和Heroku Metrics显示几个H18,H12,H27错误;
有时/redis
呼叫返回状态503
;
我想了解的是,如果我正确使用这些服务,为什么所有的教程别提res.flush()
,我发现它由我自己来让它工作的第一次...