🎨 优化批量上传机器人接口

This commit is contained in:
2025-10-15 01:09:53 +08:00
parent d81e9e917e
commit 56333b363b

View File

@@ -210,24 +210,53 @@ func (btService *BotService) generateKeywordVariants(input string) []string {
return result return result
} }
// BulkBot 支持批量异步上传机器人,避免接口超时
func (btService *BotService) BulkBot(p botReq.BulkBot, userName string) (err error) { func (btService *BotService) BulkBot(p botReq.BulkBot, userName string) (err error) {
// 上传失败的图片 // 上传失败的图片
var failFiles []string 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 { for _, a := range p.Files {
content := "<img src=" + a + " alt=\"" + a + "\" data-href=\"\" style=\"width: 100%;height: auto;\"/>" sem <- struct{}{}
bots := bot.Bot{ go func(a string) {
Keyword: getBotKeyWorld(a), defer func() { <-sem }()
Content: &content, content := "<img src=" + a + " alt=\"" + a + "\" data-href=\"\" style=\"width: 100%;height: auto;\"/>"
CreateBy: userName, 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 // 等待所有goroutine完成
if err != nil { for i := 0; i < cap(sem); i++ {
global.GVA_LOG.Error("创建机器人失败", zap.Error(err)) sem <- struct{}{}
// 记录上传失败的文件 }
failFiles = append(failFiles, a) close(errCh)
continue
for res := range errCh {
if res.err != nil && res.file != "" {
failFiles = append(failFiles, res.file)
} }
} }