master
parent
3272f7090d
commit
155c071770
3 changed files with 60 additions and 0 deletions
@ -0,0 +1,54 @@ |
||||
package xserver |
||||
|
||||
import ( |
||||
"context" |
||||
"github.com/nsqio/go-nsq" |
||||
"sync" |
||||
) |
||||
|
||||
func NewConsumer(nsqHost string) *consumer { |
||||
return &consumer{ |
||||
consumers: make([]*nsq.Consumer, 0), |
||||
host: nsqHost, |
||||
} |
||||
} |
||||
|
||||
type consumer struct { |
||||
consumers []*nsq.Consumer |
||||
host string |
||||
wg sync.WaitGroup |
||||
} |
||||
|
||||
func (c *consumer) Name() string { |
||||
return "consumer" |
||||
} |
||||
|
||||
func (s *consumer) Start() error { |
||||
for _, v := range s.consumers { |
||||
if err := v.ConnectToNSQD(s.host); err != nil { |
||||
return err |
||||
} |
||||
} |
||||
return nil |
||||
} |
||||
func (s *consumer) Shutdown(ctx context.Context) error { |
||||
for _, v := range s.consumers { |
||||
v.Stop() |
||||
} |
||||
s.wg.Wait() |
||||
return nil |
||||
} |
||||
|
||||
func (s *consumer) Register(topic, channel string, fun func(msg *nsq.Message) error) error { |
||||
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 |
||||
} |
Loading…
Reference in new issue