2025-09-19 16:17:46 +08:00
|
|
|
package rabbit
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"errors"
|
|
|
|
|
|
|
|
|
|
rmq "github.com/rabbitmq/rabbitmq-amqp-go-client/pkg/rabbitmqamqp"
|
|
|
|
|
)
|
|
|
|
|
|
2025-11-06 21:09:50 +08:00
|
|
|
func NewConsumer(ctx context.Context, tag string, xqk *XQK) (*rmq.Consumer, error) {
|
2025-09-19 16:17:46 +08:00
|
|
|
cli := client
|
|
|
|
|
if tag != "default" {
|
2025-11-06 21:09:50 +08:00
|
|
|
var err error
|
|
|
|
|
cli, err = NewClient(ctx, tag)
|
2025-09-19 16:17:46 +08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-06 21:09:50 +08:00
|
|
|
return cli.conn.NewConsumer(ctx, xqk.Queue, nil)
|
2025-09-19 16:17:46 +08:00
|
|
|
}
|
|
|
|
|
|
2025-10-11 14:56:11 +08:00
|
|
|
func Consuming(ctx context.Context, consumer *rmq.Consumer, msgChan chan<- []byte) {
|
2025-09-19 16:17:46 +08:00
|
|
|
for {
|
|
|
|
|
deliCtx, err := consumer.Receive(ctx)
|
|
|
|
|
if errors.Is(err, context.Canceled) {
|
|
|
|
|
// The consumer was closed correctly
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
// An error occurred receiving the message
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for _, data := range deliCtx.Message().Data {
|
|
|
|
|
msgChan <- data
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err = deliCtx.Accept(ctx)
|
|
|
|
|
if err != nil {
|
2025-11-20 20:58:51 +08:00
|
|
|
// accept error
|
2025-09-19 16:17:46 +08:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|