|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from natsrpy import Nats |
| 4 | +from natsrpy.js import PullConsumerConfig, PushConsumerConfig, StreamConfig |
| 5 | + |
| 6 | + |
| 7 | +async def main() -> None: |
| 8 | + """Main function to run the example.""" |
| 9 | + nats = Nats(["nats://localhost:4222"]) |
| 10 | + await nats.startup() |
| 11 | + |
| 12 | + js = await nats.jetstream() |
| 13 | + |
| 14 | + stream = await js.streams.create_or_update( |
| 15 | + StreamConfig( |
| 16 | + name="stream-example", |
| 17 | + subjects=["stream.example.>"], |
| 18 | + description="Stream example", |
| 19 | + ), |
| 20 | + ) |
| 21 | + |
| 22 | + # Push and pull consumers have different configurations. |
| 23 | + # If you supply PushConsumerConfig, you will get a push consumer, |
| 24 | + # and otherwise you will get a PullConsumer. |
| 25 | + # |
| 26 | + # They have different APIs. |
| 27 | + pull_consumer = await stream.consumers.create( |
| 28 | + PullConsumerConfig( |
| 29 | + name="example-pull", |
| 30 | + durable_name="example-pull", |
| 31 | + ), |
| 32 | + ) |
| 33 | + push_consumer = await stream.consumers.create( |
| 34 | + PushConsumerConfig( |
| 35 | + name="example-push", |
| 36 | + deliver_subject="example-push", |
| 37 | + durable_name="example-push", |
| 38 | + ), |
| 39 | + ) |
| 40 | + |
| 41 | + # We publish a single message |
| 42 | + await js.publish("stream.example.test", "message for stream") |
| 43 | + |
| 44 | + # We use messages() to get async iterator which we |
| 45 | + # use to get messages for push_consumer. |
| 46 | + async for push_message in await push_consumer.messages(): |
| 47 | + print(f"[FROM_PUSH] {push_message.payload}") # noqa: T201 |
| 48 | + await push_message.ack() |
| 49 | + break |
| 50 | + |
| 51 | + # Pull consumers have to request batches of messages. |
| 52 | + for pull_message in await pull_consumer.fetch(max_messages=10): |
| 53 | + print(f"[FROM_PULL] {pull_message.payload}") # noqa: T201 |
| 54 | + await pull_message.ack() |
| 55 | + |
| 56 | + # Cleanup |
| 57 | + await stream.consumers.delete(push_consumer.name) |
| 58 | + await stream.consumers.delete(pull_consumer.name) |
| 59 | + await js.streams.delete(stream.name) |
| 60 | + |
| 61 | + # Don't forget to call shutdown. |
| 62 | + await nats.shutdown() |
| 63 | + |
| 64 | + |
| 65 | +if __name__ == "__main__": |
| 66 | + asyncio.run(main()) |
0 commit comments