snapshot of https://github.com/ThreeDotsLabs/watermill.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
master / ci (push) Failing after 0s
Some checks failed
master / ci (push) Failing after 0s
This commit is contained in:
97
_examples/pubsubs/nats-core/main.go
Normal file
97
_examples/pubsubs/nats-core/main.go
Normal file
@@ -0,0 +1,97 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/ThreeDotsLabs/watermill"
|
||||
"github.com/ThreeDotsLabs/watermill-nats/v2/pkg/nats"
|
||||
"github.com/ThreeDotsLabs/watermill/message"
|
||||
nc "github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
natsURL := "nats://nats:4222"
|
||||
marshaler := &nats.GobMarshaler{}
|
||||
logger := watermill.NewStdLogger(false, false)
|
||||
options := []nc.Option{
|
||||
nc.RetryOnFailedConnect(true),
|
||||
nc.Timeout(30 * time.Second),
|
||||
nc.ReconnectWait(1 * time.Second),
|
||||
}
|
||||
|
||||
jsConfig := nats.JetStreamConfig{Disabled: true}
|
||||
|
||||
subscriber, err := nats.NewSubscriber(
|
||||
nats.SubscriberConfig{
|
||||
URL: natsURL,
|
||||
CloseTimeout: 30 * time.Second,
|
||||
AckWaitTimeout: 30 * time.Second,
|
||||
NatsOptions: options,
|
||||
Unmarshaler: marshaler,
|
||||
JetStream: jsConfig,
|
||||
},
|
||||
logger,
|
||||
)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
c := make(chan os.Signal)
|
||||
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-c
|
||||
fmt.Println("\r- Ctrl+C pressed in Terminal - closing subscriber")
|
||||
subscriber.Close()
|
||||
os.Exit(0)
|
||||
}()
|
||||
|
||||
messages, err := subscriber.Subscribe(context.Background(), "example_topic_nats")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
go process(messages)
|
||||
|
||||
publisher, err := nats.NewPublisher(
|
||||
nats.PublisherConfig{
|
||||
URL: natsURL,
|
||||
NatsOptions: options,
|
||||
Marshaler: marshaler,
|
||||
JetStream: jsConfig,
|
||||
},
|
||||
logger,
|
||||
)
|
||||
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_nats", 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()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user