Skip to content
This repository has been archived by the owner on Apr 25, 2022. It is now read-only.

Commit

Permalink
在线人数统计api
Browse files Browse the repository at this point in the history
  • Loading branch information
CodFrm committed Mar 28, 2019
1 parent 1ce3bca commit 96c7171
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
13 changes: 7 additions & 6 deletions src/server/listen.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ var path = require('path');
var fs = require('fs');
const http = require('http');
const https = require('https');
const redis = require('./redis');
const redisCli = require('./redis');

var privateKey = fs.readFileSync(path.join(__dirname, './certificate/private.key'), 'utf8');
var certificate = fs.readFileSync(path.join(__dirname, './certificate/file.crt'), 'utf8');
Expand All @@ -33,6 +33,7 @@ httpsServer.listen(SSLPORT, function () {


var mooc = new moocModel();
var redis = new redisCli();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
Expand All @@ -51,9 +52,10 @@ app.use(express.static(path.join(__dirname, 'static'), {
}));

//在线人数中间件
app.use(function (req, res) {
app.use(function (req, res, next) {
var ip = getClientIp(req);
redis.zadd("cxmooc:online", Date.parse(new Date()), ip);
redis.onlineAdd(ip);
next();
});

app.get('/', function (req, res) {
Expand Down Expand Up @@ -150,14 +152,13 @@ function mergeAnswer(source, answer) {
}

app.get('/update', function (req, res) {
var time = Date.parse(new Date());
redis.zcount("cxmooc:online", time - (5 * 60 * 1000), time, function (err, res) {
redis.onlineNum(function (err, data) {
res.send({
version: config.version,
url: config.update,
enforce: config.enforce,
injection: config.injection,
onlinenum: res
onlinenum: data
});
});
})
Expand Down
13 changes: 11 additions & 2 deletions src/server/redis.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
var redis = require('redis');

module.exports = function () {
var client = redis.createClient({ "host": "127.0.0.1", "port": "6379" });
var client = redis.createClient(6379,"127.0.0.1");
client.on("error", function (err) {
console.log("Redis error:" + err);
});
return client;
this.onlineAdd = function (ip) {
client.zadd("cxmooc:online", [Date.parse(new Date()), ip]);
}
this.onlineNum = function (call) {
var time = Date.parse(new Date());
client.zcount("cxmooc:online", [time - (5 * 60 * 1000), time], function (err, res) {
call(err, res)
});
}
return this
}

0 comments on commit 96c7171

Please sign in to comment.