您的当前位置:首页正文

socket.io+redis+nodejs+nginx集群部署

2024-11-08 来源:个人技术集锦

nginx配置


worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    #gzip  on;
    upstream backend {

             ip_hash;

             server 127.0.0.1:3000;

             server 127.0.0.1:3002;
         }
    server {
        listen       80;
        server_name  localhost;
    # 匹配到/static/路径 匹配到public目录下的static
        location /static/ {
            root public/;
        }
    location / {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_http_version 1.1;
        proxy_pass http://backend;
        proxy_redirect off;
    }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

}

redis.js

// redis
var ioRedis = require('ioredis');
// redis充当sub用来订阅redis通道
var redis = new ioRedis();
//  注意是不同的redis实例
//  用来发布消息
var pub = new ioRedis();
exports.redis = redis;
exports.pub = pub;

warn.js

var socketio = require('socket.io');
var adapter = require('socket.io-redis');
var warn;
// 当前连接用户,偷懒了,应该放到redis里共享
global.user = [];
var num = 0;
var redis = require('../redis/redis.js').redis;
var pub = require('../redis/redis.js').pub;
var hgk = adapter({ pubClient: pub, subClient: redis, key: 'hgk@2017', withChannelMultiplexing: true });
// 未封装的用法
// redis.subscribe('hgk', function(err, count) {
//   console.log('channel count:' + count);
// })
global.io;
exports.listen = function(server) {
  io = socketio(server);
  io.adapter(hgk);
  warn = io.of('/warnTips');
  warn.on('connection', function(socket) {
    // 添加redis.on message事件,每增加一个socket就增加一个回掉函数(未封装用法)
    // redis.on('message', function(channel, message) {
    //     console.log('Receive message %s from channel %s', message, channel);
    //     socket.emit('warn', 'message')
    //   })
    user.push({account:num,socketID:socket.id});
    num+=1;
    socket.on('account', function(data) {
      console.log('save account:' + data + 'socketId:'+socket.id);
    })
    socket.on('hgk', function(data) {
      console.log(data);
      warn.emit('warn', data);
    })
    warn.adapter.remoteJoin(socket.id, 'room1', function(err) {
      if (err) { console.log('unknown id') }
      console.log('join success:' + socket.id);
    });
    warn.adapter.customHook = function(data, cb) {
      warn.emit('warn', data);
      cb('hello ' + data);
    }
    socket.on('disconnect',function(){
        for (var i = user.length - 1; i >= 0; i--) {
          if(user[i].socketID === socket.id){
            var dis = user.splice(i,1);
            console.log('del:'+dis);
          }
        }
        console.log('断开链接');
    })
  });
}

app.js

  // websocket全网告示快捷入口
app.use('/warn', function(req, res, next) {
  var time = req.body.time;
  var message = req.body.message;
  var msg = {
      time,
      message
    }
    // pub.publish('hgk','aaaaaaa1');
    // res.end('hello world')
  io.of('/warnTips').adapter.customRequest(JSON.srtringify(msg), function(err, replies) {
    console.log(replies); // an array ['hello john', ...] with one element per node
  });
  io.of('/warnTips').adapter.clients(function (error, clients) {
    if (error) throw error;
    console.log(clients); // => [Anw2LatarvGVVXEIAAAD]
    res.end('hello world! clients in room1:' + clients.length +'-------'+JSON.stringify(user));
  });
})

完整项目请参考

Top