线上接口易遭受爬虫、CC攻击、高频恶意请求,导致服务瘫痪。阿里云WAF提供全方位Web防护,搭配自定义代码限流,可实现双层防护,彻底保障接口安全稳定运行。
分享FC函数接口限流防护代码,实现单IP访问频次限制、非法请求拦截。
核心实操代码:
import time
全局IP访问记录
ip_cache = {}
def handler(event, context):
# 获取客户端IP
client_ip = event.get("requestContext", {}).get("sourceIp", "")
now = int(time.time())
limit_second = 10
limit_count = 15
# IP限流逻辑
if client_ip not in ip_cache:
ip_cache[client_ip] = {"count": 1, "time": now}
else:
diff = now - ip_cache[client_ip]["time"]
if diff < limit_second:
if ip_cache[client_ip]["count"] > limit_count:
return {
"statusCode": 403,
"headers": {"Content-Type": "application/json"},
"body": '{"msg":"请求过于频繁,已被限流"}'
}
ip_cache[client_ip]["count"] += 1
else:
ip_cache[client_ip] = {"count": 1, "time": now}
return {"statusCode": 200, "body": "请求成功"}
搭配阿里云WAF控制台开启CC防护、爬虫防护、恶意IP封禁、SQL注入拦截,双重防护线上业务安全,彻底规避恶意攻击风险。