Created
May 12, 2011 16:32
-
-
Save dberesford/968881 to your computer and use it in GitHub Desktop.
Sample Node.js code for connecting to Redis Service in CloudFoundry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require.paths.unshift('./node_modules') | |
var http = require('http'); | |
var fs = require('fs'); | |
var redis = require("redis"); | |
var util = require('util'); | |
var server = http.createServer(function (request, response) { | |
// Redis local settings, overridden below if we're running in CloudFoundry | |
var redisPort = 6379; | |
var redisHost = '127.0.0.1'; | |
var redisPassword = ''; | |
if (process.env.VCAP_SERVICES) { | |
var vcapServices = JSON.parse(process.env.VCAP_SERVICES); | |
var cfRedis = vcapServices['redis-2.2'][0]; | |
redisHost = cfRedis.credentials.hostname; | |
redisPort = cfRedis.credentials.port; | |
redisPassword = cfRedis.credentials.password; | |
} | |
response.writeHead(200, {"Content-Type": "text/plain"}); | |
var client = redis.createClient(redisPort, redisHost); | |
if (process.env.VCAP_SERVICES) { | |
client.auth(redisPassword); | |
} | |
client.on("connect", function () { | |
if (process.env.VCAP_SERVICES) { | |
client.auth(redisPassword, function(err, res) { | |
if (err) { | |
response.end("err: " + err); | |
} | |
}); | |
} | |
}); | |
client.on("error", function (err) { | |
response.end("ERROR: " + err); | |
}); | |
client.on("ready", function (err) { | |
if (err) { | |
response.end("READY: err " + err); | |
} | |
client.get("time", function(err, reply) { | |
var t = reply; console.log(reply); | |
if (reply == undefined || reply == "") { | |
t = "Cached time: " + Date.now(); | |
client.set('time', t, function (err, reply) {}); | |
} | |
client.quit(); | |
response.end("Time: " + t); | |
}); | |
}); | |
}); | |
server.listen(process.env.VCAP_APP_PORT ||8001); | |
console.log("Server running at http://127.0.0.1:8001/"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment