简体   繁体   English

REST API和实时客户端

[英]REST API and Real Time client

I want to have the following architecture: 我想要以下架构:

A JSON REST API where real time statistic data is pushed to and stored in a Redis server. 一个JSON REST API,实时统计数据被推送到Redis服务器并存储在其中。

A JSON REST API call where any number of clients (native or web) can receive this data after it has been stored - ie in real time. JSON REST API调用,其中任何数量的客户端(本机或Web)都可以在存储数据后(即实时)接收此数据。

The first client will just be a web app and I may build a native app later. 第一个客户端只是一个Web应用程序,以后我可能会构建一个本机应用程序。

I'm wondering if my only option is for the clients to poll the REST API for changes? 我想知道我的唯一选择是否是让客户端轮询REST API的更改? Ideally, I'd like the server to push updates as they arrive so I don't need to manage this polling. 理想情况下,我希望服务器在更新到达时将其推送,因此不需要管理此轮询。

Is my architecture suitable for what I want to achieve, or am I missing something? 我的体系结构是否适合我想要实现的目标,或者我缺少某些东西?

A more efficient way than polling is to use websockets, such as Faye or Socket.IO . 比轮询更有效的方法是使用websocket,例如FayeSocket.IO You can place an emit event under a data store event to immediately send data that's been stored. 您可以在数据存储事件下放置一个发射事件,以立即发送已存储的数据。

With Socket.IO, you'd do that like this: 使用Socket.IO,您可以这样做:

var io = require('socket.io').listen(80);
//note that you can listen on HTTP servers
//can also be used with Express applications, etc

//when data is stored, run this
io.sockets.emit('event', {
  object: 'that is sent to client'
});

You could then use this to tell the client that there is new data, or you could directly send the newly stored data. 然后,您可以使用它来告诉客户端有新数据,也可以直接发送新存储的数据。 Custom events can be defined, such as 可以定义自定义事件,例如

io.sockets.emit('data_receive', function (data) {...});

and would be received client side like so: 并会像这样被客户端接收:

var socket = io.connect('http://socket.location');
socket.on('data_recieve, function (data) {
  //data is whatever sent from server
});

In Faye you'd do something like this: 在Faye中,您将执行以下操作:

var http = require('http');
var faye = require('faye');

var bayeux = new faye.NodeAdapter({
  mount: '/faye',
  timeout: 45
});
bayeux.listen(8000);

Then when data is stored, you'd run: 然后,在存储数据时,您将运行:

client.publish('/path', {
  data: 'Hello world'
});

Any client that has created a client like so: 任何创建了如下客户端的客户端:

var client = new Faye.Client('http://socket:port/path');

client.subscribe('/path', function(data) {
  alert('Received data: ' + data.text);
});

Will receive the data. 将接收数据。

You have the option of Node.js and the websocket for push and pull in realtime. 您可以选择Node.js和websocket进行实时推送和拉取。 To don't manage the queuing you still have the option of MQ. 要不管理队列,您仍然可以选择MQ。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM