Toggle navigation
Toggle navigation
This project
Loading...
Sign in
fe
/
yohobuy-node
·
Commits
Go to a project
GitLab
Go to group
Project
Activity
Files
Commits
Pipelines
0
Builds
0
Graphs
Milestones
Issues
1
Merge Requests
0
Members
Labels
Wiki
Forks
Network
Create a new issue
Download as
Email Patches
Plain Diff
Browse Files
Authored by
姜枫
8 years ago
Commit
0522f20871c13ab75cdbd9e61c29d431121cb54a
1 parent
d6723dd1
添加请求限制中间件
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
43 additions
and
0 deletions
app.js
doraemon/middleware/limiter.js
app.js
View file @
0522f20
...
...
@@ -51,6 +51,9 @@ if (config.zookeeperServer) {
require
(
'yoho-zookeeper'
)(
config
.
zookeeperServer
,
'pc'
,
app
.
locals
.
pc
=
{},
global
.
yoho
.
cache
);
}
// 请求限制中间件
app
.
use
(
require
(
'./doraemon/middleware/limiter'
));
app
.
set
(
'subdomain offset'
,
2
);
app
.
use
(
global
.
yoho
.
hbs
({
extname
:
'.hbs'
,
...
...
doraemon/middleware/limiter.js
0 → 100644
View file @
0522f20
'use strict'
;
const
cache
=
global
.
yoho
.
cache
.
master
;
const
_
=
require
(
'lodash'
);
const
logger
=
global
.
yoho
.
logger
;
module
.
exports
=
(
req
,
res
,
next
)
=>
{
let
remoteIp
=
req
.
get
(
'X-Forwarded-For'
)
||
''
;
if
(
remoteIp
.
indexOf
(
','
)
>
0
)
{
let
arr
=
remoteIp
.
split
(
','
);
remoteIp
=
arr
[
0
];
}
if
(
remoteIp
&&
!
_
.
get
(
req
.
app
.
locals
,
'pc.sys.noLimiter'
))
{
// 判断获取remoteIp成功,并且开关未关闭
let
key
=
`
pc
:
limiter
:
$
{
remoteIp
}
`
;
logger
.
debug
(
`
request
limiter
key
=
$
{
key
}
`
);
cache
.
getAsync
(
key
).
then
(
result
=>
{
if
(
result
&&
_
.
isNumber
(
result
))
{
if
(
result
>
20
)
{
// 判断 qps
res
.
status
(
403
).
end
();
}
else
{
cache
.
incrAsync
(
key
,
1
);
// qps + 1
next
();
}
}
else
{
cache
.
setAsync
(
key
,
1
,
1
);
// 设置key,1s失效
next
();
}
}).
catch
(
e
=>
{
logger
.
error
(
`
request
limiter
get
key
[
$
{
key
}]
from
cache
error
.
`
,
e
);
next
();
});
}
else
{
next
();
}
};
...
...
Please
register
or
login
to post a comment