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

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
}
// 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 := "<img src=" + a + " alt=\"" + a + "\" data-href=\"\" style=\"width: 100%;height: auto;\"/>"
bots := bot.Bot{
Keyword: getBotKeyWorld(a),
Content: &content,
CreateBy: userName,
}
sem <- struct{}{}
go func(a string) {
defer func() { <-sem }()
content := "<img src=" + a + " alt=\"" + a + "\" data-href=\"\" style=\"width: 100%;height: auto;\"/>"
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)
}
}