Publisher Direct Usage#
The Publisher Object provides a full-featured way to publish messages. It has an AsyncAPI representation and includes testability features.
This method creates a reusable Publisher object that can be used directly to publish a message:
Pros and Cons
AsyncAPI support - AsyncAPI is a specification for describing asynchronous APIs used in messaging applications. This method supports the specification render.
Testing support - This method has full Testing support.
Broker availability from Context - You can leverage FastStream's Context, a built-in Dependency Injection (DI) container, to work with brokers or other external services.
Optional publication - You can create optional publications.
Reusable - This method is reusable.
It is something in the middle between broker publish and object decorator. It has an AsyncAPI representation and testability features (like the object decorator), but allows you to send different messages to different outputs (like the broker publish).
@broker.subscriber("in")
async def handle(msg) -> str:
await publisher1.publish("Response-1")
await publisher2.publish("Response-2")
Overriding the Destination#
The destination passed to broker.publisher(...) is only a default. Every publisher.publish(...) call accepts the same destination arguments as broker.publish(...), and a value passed there overrides the one from the constructor for that single call:
The constructor argument still matters: the AsyncAPI schema describes the publisher by it, and the test mock is attached to it. If a publisher never publishes to its default destination, it is probably broker publish you want.
Note
When using this method, FastStream doesn't reuse the incoming correlation_id to mark outgoing messages with it. You should set it manually if it is required: