A Simple Go Example
Here’s a short Go snippet showing how to set up a stream and publish a message:
js, _ := nc.JetStream() // Create a stream js.AddStream(&nats.StreamConfig{ Name: "ORDERS", Subjects: []string{"orders.*"}, }) // Publish a message js.Publish("orders.created", []byte("Order #123 created"))
And consuming messages:
// Create a durable consumer sub, _ := js.PullSubscribe("orders.*", "worker1") // Fetch messages msgs, _ := sub.Fetch(10) for _, msg := range msgs { fmt.Println(string(msg.Data)) msg.Ack() }
Final Thoughts
JetStream adds persistence and streaming to the lightweight core of NATS. It keeps the simplicity of subjects and subscriptions, but also gives you more reliability, durability, and control over your data flow.
Category: NATS