From 56333b363b4eed07b63abf684837820f90cb9bde Mon Sep 17 00:00:00 2001 From: Echo <1711788888@qq.com> Date: Wed, 15 Oct 2025 01:09:53 +0800 Subject: [PATCH] =?UTF-8?q?:art:=20=E4=BC=98=E5=8C=96=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=9C=BA=E5=99=A8=E4=BA=BA=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- service/bot/bot.go | 53 +++++++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/service/bot/bot.go b/service/bot/bot.go index 9315ab6..120ceae 100644 --- a/service/bot/bot.go +++ b/service/bot/bot.go @@ -210,24 +210,53 @@ func (btService *BotService) generateKeywordVariants(input string) []string { return result } +// BulkBot 支持批量异步上传机器人,避免接口超时 func (btService *BotService) BulkBot(p botReq.BulkBot, userName string) (err error) { // 上传失败的图片 var failFiles []string + // 控制并发数 + const maxGoroutines = 10 + sem := make(chan struct{}, maxGoroutines) + errCh := make(chan struct { + file string + err error + }, len(p.Files)) for _, a := range p.Files { - content := "\""" - bots := bot.Bot{ - Keyword: getBotKeyWorld(a), - Content: &content, - CreateBy: userName, - } + sem <- struct{}{} + go func(a string) { + defer func() { <-sem }() + content := "\""" + bots := bot.Bot{ + Keyword: getBotKeyWorld(a), + Content: &content, + CreateBy: userName, + } + createErr := global.GVA_DB.Create(&bots).Error + if createErr != nil { + global.GVA_LOG.Error("创建机器人失败", zap.Error(createErr)) + errCh <- struct { + file string + err error + }{file: a, err: createErr} + } else { + errCh <- struct { + file string + err error + }{file: "", err: nil} + } + }(a) + } - err = global.GVA_DB.Create(&bots).Error - if err != nil { - global.GVA_LOG.Error("创建机器人失败", zap.Error(err)) - // 记录上传失败的文件 - failFiles = append(failFiles, a) - continue + // 等待所有goroutine完成 + for i := 0; i < cap(sem); i++ { + sem <- struct{}{} + } + close(errCh) + + for res := range errCh { + if res.err != nil && res.file != "" { + failFiles = append(failFiles, res.file) } }