我正在使用NodeJS和Redis编写事件驱动的发布/订阅应用程序。我需要一个如何在Redis中的数据值更改时通知Web客户端的示例。
使用express,socket.io,node_redis,最后但并非最不重要的是使用media fire中的示例代码。
首先,你应该(如果你还没有这样做还)安装的node.js + NPM在30秒(以正确的方式,因为你应该 不 运行NPM作为 根 ):
echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc . ~/.bashrc mkdir ~/local mkdir ~/node-latest-install cd ~/node-latest-install curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1 ./configure --prefix=~/local make install # ok, fine, this step probably takes more than 30 seconds... curl http://npmjs.org/install.sh | sh
安装node + npm后,应通过以下命令安装依赖项:
npm install express npm install socket.io npm install hiredis redis # hiredis to use c binding for redis => FAST :)
您可以从mediafire下载完整样本。
unzip pbsb.zip # can also do via graphical interface if you prefer.
./app.js
const PORT = 3000; const HOST = 'localhost'; var express = require('express'); var app = module.exports = express.createServer(); app.use(express.staticProvider(__dirname + '/public')); const redis = require('redis'); const client = redis.createClient(); const io = require('socket.io'); if (!module.parent) { app.listen(PORT, HOST); console.log("Express server listening on port %d", app.address().port) const socket = io.listen(app); socket.on('connection', function(client) { const subscribe = redis.createClient(); subscribe.subscribe('pubsub'); // listen to messages from channel pubsub subscribe.on("message", function(channel, message) { client.send(message); }); client.on('message', function(msg) { }); client.on('disconnect', function() { subscribe.quit(); }); }); }
./public/index.html
<html> <head> <title>PubSub</title> <script src="/socket.io/socket.io.js"></script> <script src="/javascripts/jquery-1.4.3.min.js"></script> </head> <body> <div id="content"></div> <script> $(document).ready(function() { var socket = new io.Socket('localhost', {port: 3000, rememberTransport: false/*, transports: ['xhr-polling']*/}); var content = $('#content'); socket.on('connect', function() { }); socket.on('message', function(message){ content.prepend(message + '<br />'); }) ; socket.on('disconnect', function() { console.log('disconnected'); content.html("<b>Disconnected!</b>"); }); socket.connect(); }); </script> </body> </html>
cd pbsb node app.js
最好是启动谷歌浏览器(因为有websockets支持,但不是必需的)。造访http://localhost:3000以查看示例(开始时您除了PubSub标题以外什么都看不到)。
http://localhost:3000
PubSub
但是在publish频道上pubsub您应该会看到一条消息。下面我们发布"Hello world!"到浏览器。
publish
pubsub
"Hello world!"
publish pubsub "Hello world!"