select
select
监听IO,和select, poll, epoll类似
ch1 := make (chan int, 1)
ch2 := make (chan int, 1)
...
select {
case <-ch1:
    fmt.Println("ch1 pop one element")
case <-ch2:
    fmt.Println("ch2 pop one element")
}
select和switch相似,但是case操作只能是io
timeout
timeout := make (chan bool, 1)
go func() {
    time.Sleep(1e9) // sleep one second
    timeout <- true
}()
ch := make (chan int)
select {
case <- ch:
case <- timeout:
    fmt.Println("timeout!")
}
default
ch1 := make (chan int, 1)
ch2 := make (chan int, 1)
select {
case <-ch1:
    fmt.Println("ch1 pop one element")
case <-ch2:
    fmt.Println("ch2 pop one element")
default:
    fmt.Println("default")
}
ch1和ch2都不成功,就会执行default,可以检测是否已经满了
ch := make (chan int, 1)
ch <- 1
select {
case ch <- 2:
default:
    fmt.Println("channel is full !")
}
ch插入2的时候,已经满了,因此执行default语句
可以应用在服务上,如果服务满了,抛出【服务繁忙,请稍微再试。】,可以通过select实现
 
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号