-
I have Jetstream created and it seems that I can publish using the connection publish as well as the natsjscontext publish. May I know the difference and the pro and cons? Thank you. var opt = new NatsOpts
{
Url = "nats://localhost:4222",
SerializerRegistry = NatsJsonSerializerRegistry.Default,
Name = "Nats_Connect",
};
var connect = new NatsConnection(opt);
var jsContext = new NatsJSContext(connect);
var streamConfig = new StreamConfig("TestStream", new[] { "TestSubject" });
await jsContext.UpdateStreamAsync(streamConfig);
await connect.PublishAsync("TestSubject", new TestPerson { Name = "Connect Publish" });
await jsContext.PublishAsync<TestPerson>("TestSubject", new TestPerson { Name = "JetStream Publish" }); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
JetStream publish returns an acknowledgment that message is persisted (at-least-once). Core (connection) publish is fire-and-forget or delivered at-most-once semantics. You should check for ack in case of errors and take action based on your application requirements: // nothing to check. fire and forget
await connect.PublishAsync("TestSubject", new TestPerson { Name = "Connect Publish" });
// check ack
var ack = await jsContext.PublishAsync<TestPerson>("TestSubject", new TestPerson { Name = "JetStream Publish" });
ack.EnsureSuccess(); // throws exception
// or
if (ack.IsSuccess())
{
// ...
} |
Beta Was this translation helpful? Give feedback.
-
also note you can get better performance with batch publishing in JetStream // dotnet add package NATS.Net
using NATS.Net;
using NATS.Client.JetStream;
using NATS.Client.JetStream.Models;
await using var nc = new NatsClient();
INatsJSContext js = nc.CreateJetStreamContext();
// Create a stream
var streamConfig = new StreamConfig(name: "example-stream", subjects: ["example-subject"]);
await js.CreateStreamAsync(streamConfig);
// Publish a message
{
PubAckResponse ack = await js.PublishAsync("foo", "Hello, JetStream!");
ack.EnsureSuccess();
}
// Publish messages concurrently
List<NatsJSPublishConcurrentFuture> futures = new();
for (var i = 0; i < 500; i++)
{
NatsJSPublishConcurrentFuture future
= await js.PublishConcurrentAsync("foo", "Hello, JetStream 1!");
futures.Add(future);
}
foreach (var future in futures)
{
await using (future)
{
PubAckResponse ack = await future.GetResponseAsync();
ack.EnsureSuccess();
}
} |
Beta Was this translation helpful? Give feedback.
yes, with core also there is no guarantee that the message will be persisted