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) } }