【发布时间】:2015-02-18 01:17:44
【问题描述】:
在 Heroku 上使用 RedisCloud 和 node.js 允许(未来)扩展到多个测功机。
通过以下操作让 Redis 正常工作: https://devcenter.heroku.com/articles/rediscloud#using-redis-from-node-js
例如,下面带有注释“打印'bar'”的行确实将'bar'写入控制台。
然后按照这个添加socket.io-redis进行缩放: https://github.com/Automattic/socket.io-redis
以上内容应该允许我使用以下内容:
io.adapter(redis({ host: 'localhost', port: 6379 }));
下面我的代码中的等价物是:
io.adapter(ioredis (redisOptions));
但是,我一直收到错误消息,说 io 没有方法“适配器”。
或者,如果我首先使用 'if' 语句检查 io.adapter 是否存在(如下面的代码所示),则条件代码永远不会执行。
谁能看到我在这里做错了什么?为什么 io.adapter 不存在?
在 package.json 中
"dependencies": {
"redis": "^0.12.1",
"express": "^3.4.8",
"socket.io": "^0.9.16",
"socket.io-redis":"^0.1.4"
}
还尝试将其添加到 package.json
"socket.io-adapter": "^0.2.0"
在 app.js(我的节点服务器代码)中:
var express = require('express')
, app = express()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
, redis = require('redis')
, ioredis = require('socket.io-redis')
, url = require('url')
, redisURL = url.parse(process.env.REDISCLOUD_URL);
后来在 app.js 中:
io.sockets.on('connection', function (socket) {
var pub1 = redis.createClient(redisURL.port, redisURL.hostname, {return_buffers: true});
var sub1 = redis.createClient(redisURL.port, redisURL.hostname, {return_buffers: true});
pub1.auth(redisURL.auth.split(":")[1]);
sub1.auth(redisURL.auth.split(":")[1]);
var redisOptions = {
pubClient: pub1,
subClient: sub1,
host: redisURL.hostname,
port: redisURL.port
};
pub1.set('foo', 'bar');
sub1.get('foo', function (err, reply) {
console.log("redis test : "+reply.toString());
// Prints 'bar'
});
if (io.adapter) {
// Never reached
io.adapter(ioredis (redisOptions));
console.log ("mylog: io.adapter found");
}
console.log ("mylog server connection event fired");
【问题讨论】:
标签: node.js sockets heroku redis