使用redis记录页面访问量

最近看过redis基本用法之后做了自己网站的访问量记录,下面是服务端代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
const ioredis = require('ioredis');
const koa = require('koa');
const koaRouter = require('koa-router');
const bodyParser = require('koa-bodyparser');

const app = new koa();
const router = new koaRouter();
const connRedis = new ioredis({
port: 6379,
host: '127.0.0.1',
password: 'xxxxxxxxx',
db: 1
});

const redis = new Proxy(connRedis, {
get(target, name) {
const redis = function() {
const args = arguments || [];
return new Promise((rel, rej) => {
return connRedis[name](...args, (err, result) => {
if (err) return rej(err);
return rel(result);
});
});
};
return redis.bind(connRedis);
}
});

app.use(bodyParser());

app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', 'https://blog.pingvim.com');
ctx.set('Access-Control-Allow-Methods', 'GET');
await next();
});

router.get('/xxxx', async ctx => {
const {host, pathname} = ctx.request.query;

if (!host || !pathname) {
ctx.body = 'fail';
return;
}

const count = await redis.hget(host, pathname);
if (count) {
redis.hincrby(host, pathname, 1);
ctx.body = Number.parseInt(count) + 1;
} else {
redis.hmset(host, pathname, 1);
ctx.body = 1;
}
return;
});

app.use(router.routes());
app.listen(xxxx);

◀        
        ▶