github.com/searKing/golang/go@v1.2.117/x/dispatch/chan_dispatch.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package dispatch 6 7 import "context" 8 9 type ChanDispatch struct { 10 readerChan chan<- any 11 *Dispatch 12 } 13 14 func NewChanDispatch(handler Handler, concurrentReadMax int) *ChanDispatch { 15 return NewChanDispatch3(handler, concurrentReadMax, -1) 16 } 17 func NewChanDispatch3(handler Handler, concurrentReadMax int, concurrentHandleMax int) *ChanDispatch { 18 if concurrentReadMax < 0 { 19 return nil 20 } 21 readerChan := make(chan any, concurrentReadMax) 22 return &ChanDispatch{ 23 readerChan: readerChan, 24 Dispatch: NewDispatch3(ReaderFunc(func(ctx context.Context) (any, error) { 25 select { 26 case msg := <-readerChan: 27 return msg, nil 28 case <-ctx.Done(): 29 return nil, nil 30 } 31 }), handler, concurrentHandleMax), 32 } 33 } 34 func (thiz *ChanDispatch) SendMessage(message any) bool { 35 select { 36 case thiz.readerChan <- message: 37 return true 38 default: 39 return false 40 } 41 }