Disclaimer: The code below is just a general guidelines and I am not pasting full code so you would have to fill in the blanks if you want to use it.
Continuing http://neopatel.blogspot.com/2014/02/redis-publish-subscribe-to-nodejs.html finally I was able to write the nodejs app that would listen to events from redis and publish message to browser. The architecture looks like
1) Your browser will use SockJS javascript library to connect to the nodejs server and it would then listen to events. The normal html code looks like
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
isOpen = false;
var newConn = function(){
var sockjs_url = 'https://xxx.com/push';
var sockjs = new SockJS(sockjs_url);
sockjs.onopen = function(){
sockjs.send(JSON.stringify({"userName": "kpatel@acme.com", "sessionId": "e1930358-87d2-4d2b-86b6-2b2373acfaf1"}));
isOpen = true;
console.log('Connected.');
};
sockjs.onmessage = function(e){
console.log("Got message:" + e);
if(e.data == 'fileSystemEvent'){
si.call = si.fn();
}
};
sockjs.onclose = function(){
var recInterval = setInterval(function(){
newConn();
if(isOpen) clearInterval(recInterval);
}
, 15000
);
console.log('Closed.');
console.log('Connecting...');
};
};
newConn();
</script>
2) Now on server first thing you need is a c10K server like nginx or haproxy.
I had to install nginx1.4.3 because the default that came with sudo apt-get didnt had the websocket support.
I just used this to install nginx 1.4.3
wget http://nginx.org/download/nginx-1.4.3.tar.gz
tar xvzf nginx-1.4.3.tar.gz
cd nginx-1.4.3
./configure \
--user=nginx \
--group=nginx \
--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-pcre \
--with-file-aio \
--with-http_realip_module \
--without-http_scgi_module \
--without-http_uwsgi_module \
--without-http_fastcgi_module
make
sudo make install
3) Then I had to add the below upgrade headers to make nginx upgrade the http socket to websocket
location /push {
proxy_pass http://localhost:8090;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Host $http_host;
# WebSocket support (nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
4) I started the nodejs server on 8090 port and tomcat was on 8080. Now bare bones nodejs wont give you everything you need so you need several packages. I installed all of them using
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
sudo npm install -g redis sockjs socket.io winston
a) I used winston for logging like log4j is in java
b) redis package to talk to redis
c) sockjs for sockjs connections code
I just installed the modules globally as this is a scratch app
5) Inside nodejs app when a connection comes the client will pass username and sessionid. so nodejs needs to validate that sessionid with tomcat and then add it to a local map. Then when it receives the redis event it needs to just write it to the socket associated with the username or reject it if there is no open connection to the user.
var sockjs = require('sockjs');
var http = require('http');
var redis = require('redis');
// Store all connected sessions
var sessionMap = {};
// Create redis client
var redisClient = redis.createClient(6379, '127.0.0.1');
// Create sockjs server
var sockjsServer = sockjs.createServer();
// Sockjs server
sockjsServer.on('connection', function(conn) {
conn.on('data', function(message){
var data = JSON.parse(message || "{}");
// call function to check if current user is exist in db
result = validateSession(data.userName, data.sessionId, function(response){
logger.info("Got response" + response);
if(response.success === true){
addConnectionToSessionMap(conn,data.sessionId,data.userName);
conn.write(JSON.stringify({success:true, statusCode:response.statusCode}));
} else {
logger.info("Got error: " + response.message);
conn.write(JSON.stringify({success:false, statusCode:response.statusCode}));
conn.end();
}
});
});
conn.on('close', function(){
// remove connection from Maps if connection is closed
if(connMap[conn.id]){
removeConnection(conn, '');
conn.end();
}
logger.info("Closing...");
});
});
redisClient.subscribe(config.redis_push_channel);
// Push incoming message to all connected users
redisClient.on("message", function(channel, message){
var data = JSON.parse(message || "{}");
//figure out the connections to write message based on users and write message to them
//conn.write(data)
});
// Create http server
var server = http.createServer();
// Hook sockjs in to http server
sockjsServer.installHandlers(server, {prefix:'/push'});
server.listen(8090);
6) But coming from java world nodejs seemed fragile as it would just kill itself on every exception
so that when I added logging and in winston I added "exitOnError: false"
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new winston.transports.File({ filename: __dirname + '/logs/push.log', json: false })
],
exceptionHandlers: [
new winston.transports.File({ filename: __dirname + '/logs/push.log', json: false })
],
exitOnError: false
});
7) also nodejs wont have usual startup/stop things like tomcat has so you need to cook up your own something like
export NODE_PATH=/usr/lib/node_modules
nohup node push_server.js 1>>"nohup.out" 2>&1 &
echo $! > push.pid"
In short I am still excited for nodejs because if your startup has JS skills then JS developers can quickly start pitching into nodejs code and write server code.
Also being event model it scales pretty fine similar to the way c10k servers like nginx and haproxy scales. To me bigger learning was event based programming where you just write what happens on what event and let the framework take care of things. Good thing was that the browser has a live connection and I can publish message to redis when a file is added and in browser console logs for all users I can see the event instantly :).
Continuing http://neopatel.blogspot.com/2014/02/redis-publish-subscribe-to-nodejs.html finally I was able to write the nodejs app that would listen to events from redis and publish message to browser. The architecture looks like
1) Your browser will use SockJS javascript library to connect to the nodejs server and it would then listen to events. The normal html code looks like
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
isOpen = false;
var newConn = function(){
var sockjs_url = 'https://xxx.com/push';
var sockjs = new SockJS(sockjs_url);
sockjs.onopen = function(){
sockjs.send(JSON.stringify({"userName": "kpatel@acme.com", "sessionId": "e1930358-87d2-4d2b-86b6-2b2373acfaf1"}));
isOpen = true;
console.log('Connected.');
};
sockjs.onmessage = function(e){
console.log("Got message:" + e);
if(e.data == 'fileSystemEvent'){
si.call = si.fn();
}
};
sockjs.onclose = function(){
var recInterval = setInterval(function(){
newConn();
if(isOpen) clearInterval(recInterval);
}
, 15000
);
console.log('Closed.');
console.log('Connecting...');
};
};
newConn();
</script>
2) Now on server first thing you need is a c10K server like nginx or haproxy.
I had to install nginx1.4.3 because the default that came with sudo apt-get didnt had the websocket support.
I just used this to install nginx 1.4.3
wget http://nginx.org/download/nginx-1.4.3.tar.gz
tar xvzf nginx-1.4.3.tar.gz
cd nginx-1.4.3
./configure \
--user=nginx \
--group=nginx \
--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--conf-path=/etc/nginx/nginx.conf \
--pid-path=/var/run/nginx.pid \
--lock-path=/var/run/nginx.lock \
--error-log-path=/var/log/nginx/error.log \
--http-log-path=/var/log/nginx/access.log \
--with-http_gzip_static_module \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-pcre \
--with-file-aio \
--with-http_realip_module \
--without-http_scgi_module \
--without-http_uwsgi_module \
--without-http_fastcgi_module
make
sudo make install
3) Then I had to add the below upgrade headers to make nginx upgrade the http socket to websocket
location /push {
proxy_pass http://localhost:8090;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header Host $http_host;
# WebSocket support (nginx 1.4)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
4) I started the nodejs server on 8090 port and tomcat was on 8080. Now bare bones nodejs wont give you everything you need so you need several packages. I installed all of them using
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
sudo npm install -g redis sockjs socket.io winston
a) I used winston for logging like log4j is in java
b) redis package to talk to redis
c) sockjs for sockjs connections code
I just installed the modules globally as this is a scratch app
5) Inside nodejs app when a connection comes the client will pass username and sessionid. so nodejs needs to validate that sessionid with tomcat and then add it to a local map. Then when it receives the redis event it needs to just write it to the socket associated with the username or reject it if there is no open connection to the user.
var sockjs = require('sockjs');
var http = require('http');
var redis = require('redis');
// Store all connected sessions
var sessionMap = {};
// Create redis client
var redisClient = redis.createClient(6379, '127.0.0.1');
// Create sockjs server
var sockjsServer = sockjs.createServer();
// Sockjs server
sockjsServer.on('connection', function(conn) {
conn.on('data', function(message){
var data = JSON.parse(message || "{}");
// call function to check if current user is exist in db
result = validateSession(data.userName, data.sessionId, function(response){
logger.info("Got response" + response);
if(response.success === true){
addConnectionToSessionMap(conn,data.sessionId,data.userName);
conn.write(JSON.stringify({success:true, statusCode:response.statusCode}));
} else {
logger.info("Got error: " + response.message);
conn.write(JSON.stringify({success:false, statusCode:response.statusCode}));
conn.end();
}
});
});
conn.on('close', function(){
// remove connection from Maps if connection is closed
if(connMap[conn.id]){
removeConnection(conn, '');
conn.end();
}
logger.info("Closing...");
});
});
redisClient.subscribe(config.redis_push_channel);
// Push incoming message to all connected users
redisClient.on("message", function(channel, message){
var data = JSON.parse(message || "{}");
//figure out the connections to write message based on users and write message to them
//conn.write(data)
});
// Create http server
var server = http.createServer();
// Hook sockjs in to http server
sockjsServer.installHandlers(server, {prefix:'/push'});
server.listen(8090);
6) But coming from java world nodejs seemed fragile as it would just kill itself on every exception
so that when I added logging and in winston I added "exitOnError: false"
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new winston.transports.File({ filename: __dirname + '/logs/push.log', json: false })
],
exceptionHandlers: [
new winston.transports.File({ filename: __dirname + '/logs/push.log', json: false })
],
exitOnError: false
});
7) also nodejs wont have usual startup/stop things like tomcat has so you need to cook up your own something like
export NODE_PATH=/usr/lib/node_modules
nohup node push_server.js 1>>"nohup.out" 2>&1 &
echo $! > push.pid"
In short I am still excited for nodejs because if your startup has JS skills then JS developers can quickly start pitching into nodejs code and write server code.
Also being event model it scales pretty fine similar to the way c10k servers like nginx and haproxy scales. To me bigger learning was event based programming where you just write what happens on what event and let the framework take care of things. Good thing was that the browser has a live connection and I can publish message to redis when a file is added and in browser console logs for all users I can see the event instantly :).
Comments
Post a Comment