From fa10fd642b388d30b7346471d0964cf1c03722c4 Mon Sep 17 00:00:00 2001 From: taoshihan1991 <630892807@qq.com> Date: Tue, 9 Feb 2021 16:49:11 +0800 Subject: [PATCH] =?UTF-8?q?=E9=99=90=E5=88=B6=E5=8F=91=E9=80=81=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E7=9A=84=E9=A2=91=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- controller/message.go | 9 ++++++++- static/html/chat_page.html | 2 +- static/js/chat-page.js | 4 ++-- tools/limits.go | 33 +++++++++++++++++++++++++++++++++ 4 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 tools/limits.go diff --git a/controller/message.go b/controller/message.go index 9f05f6f..ea9ce3b 100644 --- a/controller/message.go +++ b/controller/message.go @@ -128,7 +128,14 @@ func SendMessageV2(c *gin.Context) { }) return } - + //限流 + if !tools.LimitFreqSingle("sendmessage:"+c.ClientIP(), 1, 2) { + c.JSON(200, gin.H{ + "code": 400, + "msg": c.ClientIP() + "发送频率过快", + }) + return + } var kefuInfo models.User var vistorInfo models.Visitor if cType == "kefu" { diff --git a/static/html/chat_page.html b/static/html/chat_page.html index 6a8c30e..cd00782 100644 --- a/static/html/chat_page.html +++ b/static/html/chat_page.html @@ -76,5 +76,5 @@ var LANG=checkLang(); - + diff --git a/static/js/chat-page.js b/static/js/chat-page.js index cdf8c81..424ccd6 100644 --- a/static/js/chat-page.js +++ b/static/js/chat-page.js @@ -109,6 +109,7 @@ new Vue({ mes.content = this.messageContent; //发送消息 $.post("/2/message",mes,function(res){ + _this.sendDisabled=false; if(res.code!=200){ _this.$message({ message: res.msg, @@ -128,7 +129,6 @@ new Vue({ _this.messageContent = ""; clearInterval(_this.timer); _this.sendSound(); - _this.sendDisabled=false; }); }, @@ -137,7 +137,7 @@ new Vue({ if(this.socketClosed||!this.socket){ return; } - console.log(this.messageContent); + //console.log(this.messageContent); var message = {} message.type = "inputing"; message.data = { diff --git a/tools/limits.go b/tools/limits.go new file mode 100644 index 0000000..76aa34e --- /dev/null +++ b/tools/limits.go @@ -0,0 +1,33 @@ +package tools + +import "time" + +var LimitQueue map[string][]int64 +var ok bool + +//单机时间滑动窗口限流法 +func LimitFreqSingle(queueName string, count uint, timeWindow int64) bool { + currTime := time.Now().Unix() + if LimitQueue == nil { + LimitQueue = make(map[string][]int64) + } + if _, ok = LimitQueue[queueName]; !ok { + LimitQueue[queueName] = make([]int64, 0) + } + //队列未满 + if uint(len(LimitQueue[queueName])) < count { + LimitQueue[queueName] = append(LimitQueue[queueName], currTime) + return true + } + //队列满了,取出最早访问的时间 + earlyTime := LimitQueue[queueName][0] + //说明最早期的时间还在时间窗口内,还没过期,所以不允许通过 + if currTime-earlyTime <= timeWindow { + return false + } else { + //说明最早期的访问应该过期了,去掉最早期的 + LimitQueue[queueName] = LimitQueue[queueName][1:] + LimitQueue[queueName] = append(LimitQueue[queueName], currTime) + } + return true +}