123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- package queue
- import (
- "git.haoqitour.com/haoqi/go-common/utils"
- "os"
- "os/signal"
- "syscall"
- )
- type ChanWorker struct {
- ID int
- WorkerPool chan chan interface{}
- JobChannel chan interface{}
- quit chan bool
- }
- func NewChanWorker(workerId, capacity int, workerPool chan chan interface{}) *ChanWorker {
- var jobChannel chan interface{}
- if capacity < 0 {
- jobChannel = make(chan interface{})
- } else {
- jobChannel = make(chan interface{}, capacity)
- }
- return &ChanWorker{
- ID: workerId,
- WorkerPool: workerPool,
- JobChannel: jobChannel,
- quit: make(chan bool),
- }
- }
- func (w *ChanWorker) Start(callback func(workerId int, msg interface{})) {
- go func(w *ChanWorker, callback func(workerId int, msg interface{})) {
- defer utils.DefaultGoroutineRecover(nil, `chan池工作对象消息处理`)
- for {
-
- w.WorkerPool <- w.JobChannel
- select {
- case msg := <-w.JobChannel:
- callback(w.ID, msg)
- case <-w.quit:
- return
- }
- }
- }(w, callback)
- w.closeWait()
- }
- func (w *ChanWorker) closeWait() {
- go func(w *ChanWorker) {
- defer utils.DefaultGoroutineRecover(nil, `chan池关闭`)
- var c chan os.Signal
- var s os.Signal
- c = make(chan os.Signal, 1)
- signal.Notify(c, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
- for {
- s = <-c
- switch s {
- case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
- w.quit <- true
- return
- default:
- return
- }
- }
- }(w)
- }
- type ChanDispatcher struct {
- MsgQueue chan interface{}
- WorkerPool chan chan interface{}
- maxWorkers int
- capacity int
- }
- func NewChanDispatcher(msgQueue chan interface{}, maxWorkers int) *ChanDispatcher {
- return &ChanDispatcher{
- MsgQueue: msgQueue,
- WorkerPool: make(chan chan interface{}, maxWorkers),
- maxWorkers: maxWorkers,
- capacity: -1,
- }
- }
- func NewChanDispatcherWithCapacity(msgQueue chan interface{}, maxWorkers, capacity int) *ChanDispatcher {
- return &ChanDispatcher{
- MsgQueue: msgQueue,
- WorkerPool: make(chan chan interface{}, maxWorkers),
- maxWorkers: maxWorkers,
- capacity: capacity,
- }
- }
- func (d *ChanDispatcher) Run(callback func(workerId int, msg interface{})) {
- for i := 0; i < d.maxWorkers; i++ {
- worker := NewChanWorker(i, d.capacity, d.WorkerPool)
- worker.Start(callback)
- }
- d.dispatch()
- }
- func (d *ChanDispatcher) dispatch() {
- go func(d *ChanDispatcher) {
- defer utils.DefaultGoroutineRecover(nil, `chan池调度`)
- for {
- select {
- case msg := <-d.MsgQueue:
-
- jobChannel := <-d.WorkerPool
-
- jobChannel <- msg
- }
- }
- }(d)
- }
|