2021-07-16 04:10:34 +00:00
|
|
|
package queue
|
|
|
|
|
|
|
|
import (
|
|
|
|
"runtime"
|
|
|
|
|
|
|
|
"github.com/appleboy/gorush/logx"
|
|
|
|
)
|
|
|
|
|
|
|
|
type (
|
|
|
|
// A Queue is a message queue.
|
|
|
|
Queue struct {
|
|
|
|
workerCount int
|
|
|
|
routineGroup *routineGroup
|
|
|
|
quit chan struct{}
|
|
|
|
worker Worker
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewQueue returns a Queue.
|
2021-07-16 11:26:19 +00:00
|
|
|
func NewQueue(w Worker, workerNum int) *Queue {
|
2021-07-16 04:10:34 +00:00
|
|
|
q := &Queue{
|
2021-07-16 08:30:01 +00:00
|
|
|
workerCount: runtime.NumCPU(),
|
2021-07-16 04:10:34 +00:00
|
|
|
routineGroup: newRoutineGroup(),
|
|
|
|
quit: make(chan struct{}),
|
2021-07-16 08:30:01 +00:00
|
|
|
worker: w,
|
2021-07-16 04:10:34 +00:00
|
|
|
}
|
|
|
|
|
2021-07-16 11:26:19 +00:00
|
|
|
if workerNum > 0 {
|
|
|
|
q.workerCount = workerNum
|
|
|
|
}
|
|
|
|
|
2021-07-16 04:10:34 +00:00
|
|
|
return q
|
|
|
|
}
|
|
|
|
|
|
|
|
// Capacity for queue max size
|
|
|
|
func (q *Queue) Capacity() int {
|
|
|
|
return q.worker.Capacity()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Usage for count of queue usage
|
|
|
|
func (q *Queue) Usage() int {
|
|
|
|
return q.worker.Usage()
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start to enable all worker
|
|
|
|
func (q *Queue) Start() {
|
|
|
|
q.startWorker()
|
|
|
|
}
|
|
|
|
|
2021-07-16 11:26:19 +00:00
|
|
|
// Shutdown stops all queues.
|
|
|
|
func (q *Queue) Shutdown() {
|
|
|
|
q.worker.Shutdown()
|
2021-07-16 04:10:34 +00:00
|
|
|
close(q.quit)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait all process
|
|
|
|
func (q *Queue) Wait() {
|
|
|
|
q.routineGroup.Wait()
|
|
|
|
}
|
|
|
|
|
2021-07-16 11:26:19 +00:00
|
|
|
// Queue to queue all job
|
|
|
|
func (q *Queue) Queue(job interface{}) error {
|
|
|
|
return q.worker.Queue(job)
|
2021-07-16 04:10:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (q *Queue) startWorker() {
|
|
|
|
for i := 0; i < q.workerCount; i++ {
|
|
|
|
go func(num int) {
|
|
|
|
q.routineGroup.Run(func() {
|
|
|
|
logx.LogAccess.Info("started the worker num ", num)
|
|
|
|
q.worker.Run(q.quit)
|
|
|
|
logx.LogAccess.Info("closed the worker num ", num)
|
|
|
|
})
|
|
|
|
}(i)
|
|
|
|
}
|
|
|
|
}
|