You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1022 B

2 years ago
package xserver
import (
"context"
"github.com/nsqio/go-nsq"
"sync"
)
2 years ago
func NewConsumer(nsqHost string) *Consumer {
return &Consumer{
2 years ago
consumers: make([]*nsq.Consumer, 0),
host: nsqHost,
}
}
2 years ago
type Consumer struct {
2 years ago
consumers []*nsq.Consumer
host string
wg sync.WaitGroup
}
2 years ago
func (c *Consumer) Name() string {
2 years ago
return "consumer"
}
2 years ago
func (s *Consumer) Start() error {
2 years ago
for _, v := range s.consumers {
if err := v.ConnectToNSQD(s.host); err != nil {
return err
}
}
return nil
}
2 years ago
func (s *Consumer) Shutdown(ctx context.Context) error {
2 years ago
for _, v := range s.consumers {
v.Stop()
}
s.wg.Wait()
return nil
}
2 years ago
func (s *Consumer) Register(topic, channel string, fun func(msg *nsq.Message) error) error {
2 years ago
consumer, err := nsq.NewConsumer(topic, channel, nsq.NewConfig())
if err != nil {
return err
}
consumer.AddHandler(nsq.HandlerFunc(func(msg *nsq.Message) error {
s.wg.Add(1)
defer s.wg.Done()
return fun(msg)
}))
s.consumers = append(s.consumers, consumer)
return nil
}