Saturday, February 12, 2011

NodeJS- Routing / Redis

This is an example for multiple listening ports.

 var http = require('http');  
var connect = require('connect');
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World from 8124\n');
}).listen(8124);
var server = connect.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World from 3000');
}).listen(3000);
console.log('Server running at http://127.0.0.1:8124 & 3000');


2. Redis Example

 var redis = require('redis'),  
redis_client = redis.createClient();
redis_client.on('error', function(err) {
console.log("Error: " + err);
});
redis_client.set("Hello", "World", redis.print);
redis_client.hset("Hash", "field1", "value1", redis.print);
redis_client.hset(["Hash", "field2", "value2"], redis.print);
redis_client.hkeys("Hash", function(err, replies) {
console.log(replies.length + " replies:");
replies.forEach(function(reply, i) {
console.log(" " + i + ": " + reply);
});
// redis_client.quit();
});
var instruction = {
"id": "test1",
"musl": [ "1.mus", "2.mus", "3.mus"],
"hosts": {
"host_0": "a1",
"host_1": "a2"
}
};

/// --> this is not supported. (no nested object.)
redis_client.hmset("Inst1", instruction);


redis_client.hgetall("Inst1", function(err, obj) {
console.dir(obj);
});
var str_instruction = JSON.stringify(instruction);
console.log("str: " + str_instruction);
redis_client.set("instruction", str_instruction);
redis_client.get("instruction", function(err, value) {
console.log("get: " + value);
console.dir(JSON.parse(value));
});
// Publish/Subscribe
redis_client.on('message', function(channel, message) {
console.log("client1 channel " + channel + ": " + message);
});
redis_client.subscribe('testengine');


3. Redis PubSub Example

 var redis = require("redis"),  
client1 = redis.createClient(), client2 = redis.createClient(),
msg_count = 0;
client1.on("subscribe", function (channel, count) {
client2.publish("a nice channel", "I am sending a message.");
client2.publish("a nice channel", "I am sending a second message.");
client2.publish("a nice channel", "I am sending my last message.");
});
client1.on("message", function (channel, message) {
console.log("client1 channel " + channel + ": " + message);
msg_count += 1;
if (msg_count === 3) {
client1.unsubscribe();
client1.end();
client2.end();
}
});
client1.incr("did a thing");
client1.subscribe("a nice channel");

No comments: