1 回答

TA貢獻1784條經驗 獲得超9個贊
Fiber 生成多個進程來處理傳入的請求。您需要的是在主進程中啟動清理例程并在子進程中跳過它。
纖維提供fiber.IsChild
功能:
// start a cleanup cron-job if !fiber.IsChild() { go cleanUp() }
我稍微修改了您的示例以在處理程序和清理 goroutine 中打印進程 ID:
func main() {
// 4 procs/childs max
runtime.GOMAXPROCS(4)
// start a cleanup cron-job
if !fiber.IsChild() {
go cleanUp()
}
app := fiber.New(fiber.Config{
Prefork: true,
})
app.Post("/", handleFileupload)
log.Fatal(app.Listen(":4000"))
}
func cleanUp() {
fmt.Println("Cleaning Up.. Pid:", syscall.Getpid())
for {
// deletes old files here
time.Sleep(1 * time.Second)
fmt.Println("Cleaning Up.. Pid:", syscall.Getpid())
}
}
func handleFileupload(ctx *fiber.Ctx) error {
println("Upload: pid ", syscall.Getpid())
return nil
}
結果:
Cleaning Up.. Pid: 27035
┌───────────────────────────────────────────────────┐ ┌───────────────────────────────────────────────────┐
│ Fiber v2.39.0 │ │ Child PIDs ... 27041, 27042, 27044, 27045 │
│ http://127.0.0.1:4000 │ └───────────────────────────────────────────────────┘
│ (bound on host 0.0.0.0 and port 4000) │
│ │
│ Handlers ............. 1 Processes ........... 4 │
│ Prefork ........ Enabled PID ............. 27035 │
└───────────────────────────────────────────────────┘
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
Cleaning Up.. Pid: 27035
如您所見,清理僅在主進程中運行。
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報