生产消息模型的优雅停止
package main import ( "fmt" "os" "os/signal" "syscall" "time" ) func main() { readCh := make(chan int, 100) //生产者写数据 go func() { for i := 0; i <= 10; i++ { readCh <- i } }() //监听进程退出信号 go func() { signalCh := make(chan os.Signal, 1) signal.Notify(signalCh, syscall.SIGINT, syscall.SIGTERM) // 等待接收终止信号 <-signalCh close(readCh) fmt.Println("stop begin,time: ", time.Now()) }() //消费者遍历chan处理数据 flag := true for flag { func() { select { case val, run := <-readCh: //readCh只有有数据,run就会为true if !run { flag = false return } time.Sleep(time.Second) fmt.Println("step2 val: ", val, "run: ", run) } }() } fmt.Println("stop end,time: ", time.Now()) }
等风起的那一天,我已准备好一切