l-export-async/coroutine/README.md

50 lines
1.7 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 协程启动管理器
目前的主要作用是:
1. 简化写法不用自己再defer记录日志
2. 优雅关闭
3. 统一管理方便后面扩展
4. 支持固定队列协程:定义最大数量,超过时会阻塞启动,直接有空闲的时候才会启动
todolist:
* [ ]. 控coroutine的状态数量时长
## 使用步骤
1. 交给kratos管理生命周期
```go
// 1. 打开main.go
// 2. newApp方法中注入logHelper *log.Helper
// 3. 按如下代码提供给kratos管理生命周期
coroutineServer := coroutine.NewServer(logHelper)
serverOption := kratos.Server(
// 省略之前的一些已有变量...
coroutineServer,
)
```
2. 使用示例
```go
doDesc := "我是闭包中能访问到的变量,可以直接使用"
coroutine.Run("我是任务名称", func() {
// 模拟执行
fmt.Printf("开始:%s\n", doDesc)
time.Sleep(1 * time.Second)
fmt.Printf("开始:%s\n", doDesc)
})
// 在Run里面会开启协程不要自己在这里使用go关键字开启协程
// 错误示例go coroutine.Run("我是任务名称", func() {})
```
3固定队列使用示例
```go
maxTaskCnt := 10 // 最大并行任务数量。超过时阻塞启动方,直到有有任务执行完成
f := NewFixed(maxTaskCnt)
doDesc := "我是闭包中能访问到的变量,可以直接使用"
f.Run("我是任务名称", func() {
// 模拟执行
fmt.Printf("开始:%s\n", doDesc)
time.Sleep(1 * time.Second)
fmt.Printf("开始:%s\n", doDesc)
})
// 在Run里面会开启协程不要自己在这里使用go关键字开启协程
// 错误示例go coroutine.Run("我是任务名称", func() {})
```