Commit df518388 by 杨树贤

再次优化

parent 720fb45b
Showing with 23 additions and 4 deletions
...@@ -146,9 +146,27 @@ func CommonController(ctx *gin.Context) map[string]interface{} { ...@@ -146,9 +146,27 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
} }
// 开启一个协程,等待所有任务完成,然后关闭channel // 开启一个协程,等待所有任务完成,然后关闭channel
// 使用 context 来控制这个等待协程的生命周期
go func() {
// 创建一个 done channel 用于通知 wg.Wait() 完成
done := make(chan struct{})
go func() { go func() {
wg.Wait() wg.Wait()
close(done)
}()
// 等待 wg.Wait() 完成或 context 取消
select {
case <-done:
// 所有协程都正常完成
close(ch) close(ch)
case <-ctxWithTimeout.Done():
// context 超时,不再等待剩余协程
// 等待一小段时间让协程有机会退出
time.Sleep(300 * time.Millisecond)
close(ch)
logger.Log("等待协程完成超时,强制关闭channel", "sku", 1)
}
}() }()
//异步map最后转成map //异步map最后转成map
...@@ -156,7 +174,7 @@ func CommonController(ctx *gin.Context) map[string]interface{} { ...@@ -156,7 +174,7 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
for { for {
select { select {
case GoodsRes, ok := <-ch: case GoodsRes, ok := <-ch:
if !ok { // channel被关闭,说明所有协程都已执行完毕 if !ok { // channel被关闭,说明所有协程都已执行完毕或超时
return temp return temp
} }
GoodsRes.Range(func(k, v interface{}) bool { GoodsRes.Range(func(k, v interface{}) bool {
...@@ -169,14 +187,15 @@ func CommonController(ctx *gin.Context) map[string]interface{} { ...@@ -169,14 +187,15 @@ func CommonController(ctx *gin.Context) map[string]interface{} {
// context 超时或被取消 // context 超时或被取消
logger.Log("协程整体处理超时,所有子协程已收到取消信号", "sku", 1) logger.Log("协程整体处理超时,所有子协程已收到取消信号", "sku", 1)
// 关键:继续从 channel 读取已经发送的数据,避免协程阻塞 // 继续从 channel 读取已经发送的数据,避免协程阻塞
// 设置一个短暂的清理超时 // 等待 channel 被关闭(由上面的 wg.Wait() 协程关闭)
cleanupTimeout := time.After(200 * time.Millisecond) cleanupTimeout := time.After(500 * time.Millisecond)
for { for {
select { select {
case GoodsRes, ok := <-ch: case GoodsRes, ok := <-ch:
if !ok { if !ok {
// channel 已关闭,所有协程都已退出 // channel 已关闭,所有协程都已退出
logger.Log("channel已关闭,返回结果", "sku", 1)
return temp return temp
} }
// 收集已经发送的数据 // 收集已经发送的数据
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment