package main
import (
"fmt"
"net/http"
"sync"
"time"
)
func main() {
http.HandleFunc("/test", func(writer http.ResponseWriter, request *http.Request) {
startTime := time.Now()
taskHandler()
fmt.Println("共计耗时:", time.Since(startTime).String())
})
if err := http.ListenAndServe(":18083", nil); err != nil {
panic(any(err))
}
}
func taskHandler() {
//模拟总任务数量
taskNums := 7
//定义最大可运行中的任务数量, 也可以理解为同时运行的最大goroutine数量
maxRuntimeTask := 3
wg := &sync.WaitGroup{}
wg.Add(taskNums)
//定义一个总调度完成后的通知队列, 在wg.wait()后来发送消息
noticeChan := make(chan struct{}, 1)
//定义一个协程池, 容量为maxRuntimeTask
poolChan := make(chan struct{}, maxRuntimeTask)
//定义一个任务完成通知队列, 容量为maxRuntimeTask
taskNoticeChan := make(chan struct{}, maxRuntimeTask)
defer func() {
//所有的goroutine都已经完成, 作用时监听者收到消息后会做出一个停止继续监听的动作
noticeChan <- struct{}{}
//关闭相关的通道队列
close(taskNoticeChan)
close(poolChan)
close(noticeChan)
}()
//这里单独起一个协程去做监听工作
go func() {
f
golang 多协程控制请求API频次/频率 X秒内请求X次
于 2022-11-03 14:22:57 首次发布
本文介绍了一个使用Go语言实现的任务调度器,通过限制并发任务数来避免资源过载。该调度器采用goroutine池和通知队列的方式进行任务管理,并通过定时检查释放空闲资源。

最低0.47元/天 解锁文章
1187

被折叠的 条评论
为什么被折叠?



