Files
OpenList/pkg/mq/mq.go
Kuingsmile fdcc2f136e chore: change module name to OpenListTeam/OpenList (#2)
* Enable blank issue

* chore(README.md): update docs (temporally)

* Update FUNDING.yml

* chore: purge README.md

* chore: change module name to OpenListTeam/OpenList

* fix: fix link errors

* chore: remove v3 in module name

* fix: resolve some conficts

* fix: resolve conficts

* docs: update with latest file

---------

Co-authored-by: ShenLin <773933146@qq.com>
Co-authored-by: Hantong Chen <cxwdyx620@gmail.com>
Co-authored-by: joshua <i@joshua.su>
Co-authored-by: Hantong Chen <70561268+cxw620@users.noreply.github.com>
2025-06-12 22:02:46 +08:00

64 lines
1.1 KiB
Go

package mq
import (
"sync"
"github.com/OpenListTeam/OpenList/pkg/generic"
)
type Message[T any] struct {
Content T
}
type BasicConsumer[T any] func(Message[T])
type AllConsumer[T any] func([]Message[T])
type MQ[T any] interface {
Publish(Message[T])
Consume(BasicConsumer[T])
ConsumeAll(AllConsumer[T])
Clear()
Len() int
}
type inMemoryMQ[T any] struct {
queue generic.Queue[Message[T]]
sync.Mutex
}
func NewInMemoryMQ[T any]() MQ[T] {
return &inMemoryMQ[T]{queue: *generic.NewQueue[Message[T]]()}
}
func (mq *inMemoryMQ[T]) Publish(msg Message[T]) {
mq.Lock()
defer mq.Unlock()
mq.queue.Push(msg)
}
func (mq *inMemoryMQ[T]) Consume(consumer BasicConsumer[T]) {
mq.Lock()
defer mq.Unlock()
for !mq.queue.IsEmpty() {
consumer(mq.queue.Pop())
}
}
func (mq *inMemoryMQ[T]) ConsumeAll(consumer AllConsumer[T]) {
mq.Lock()
defer mq.Unlock()
consumer(mq.queue.PopAll())
}
func (mq *inMemoryMQ[T]) Clear() {
mq.Lock()
defer mq.Unlock()
mq.queue.Clear()
}
func (mq *inMemoryMQ[T]) Len() int {
mq.Lock()
defer mq.Unlock()
return mq.queue.Len()
}