Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
2 contributors

Users who have contributed to this file

@m110 @maclav3
83 lines (69 sloc) 1.9 KB
// Sources for https://watermill.io/docs/getting-started/
package main
import (
"context"
"log"
"time"
stan "github.com/nats-io/stan.go"
"github.com/ThreeDotsLabs/watermill"
"github.com/ThreeDotsLabs/watermill-nats/pkg/nats"
"github.com/ThreeDotsLabs/watermill/message"
)
func main() {
subscriber, err := nats.NewStreamingSubscriber(
nats.StreamingSubscriberConfig{
ClusterID: "test-cluster",
ClientID: "example-subscriber",
QueueGroup: "example",
DurableName: "my-durable",
SubscribersCount: 4, // how many goroutines should consume messages
CloseTimeout: time.Minute,
AckWaitTimeout: time.Second * 30,
StanOptions: []stan.Option{
stan.NatsURL("nats://nats-streaming:4222"),
},
Unmarshaler: nats.GobMarshaler{},
},
watermill.NewStdLogger(false, false),
)
if err != nil {
panic(err)
}
messages, err := subscriber.Subscribe(context.Background(), "example.topic")
if err != nil {
panic(err)
}
go process(messages)
publisher, err := nats.NewStreamingPublisher(
nats.StreamingPublisherConfig{
ClusterID: "test-cluster",
ClientID: "example-publisher",
StanOptions: []stan.Option{
stan.NatsURL("nats://nats-streaming:4222"),
},
Marshaler: nats.GobMarshaler{},
},
watermill.NewStdLogger(false, false),
)
if err != nil {
panic(err)
}
publishMessages(publisher)
}
func publishMessages(publisher message.Publisher) {
for {
msg := message.NewMessage(watermill.NewUUID(), []byte("Hello, world!"))
if err := publisher.Publish("example.topic", msg); err != nil {
panic(err)
}
time.Sleep(time.Second)
}
}
func process(messages <-chan *message.Message) {
for msg := range messages {
log.Printf("received message: %s, payload: %s", msg.UUID, string(msg.Payload))
// we need to Acknowledge that we received and processed the message,
// otherwise, it will be resent over and over again.
msg.Ack()
}
}
You can’t perform that action at this time.