Application-level Filtering FastStream also allows you to specify the message processing way using message headers, body type or something else. The filter
feature enables you to consume various messages with different schemas within a single event stream.
Tip
Message must be consumed at ONCE (crossing filters are not allowed)
As an example, let's create a subscriber for both JSON
and non-JSON
messages:
Kafka RabbitMQ NATS
from faststream import FastStream
from faststream.kafka import KafkaBroker
broker = KafkaBroker ( "localhost:9092" )
app = FastStream ( broker )
@broker . subscriber (
"test-topic" ,
filter = lambda msg : msg . content_type == "application/json" ,
)
async def handle ( name : str , user_id : int ):
assert name == "John"
assert user_id == 1
@broker . subscriber ( "test-topic" )
async def default_handler ( msg : str ):
assert msg == "Hello, FastStream!"
from faststream import FastStream
from faststream.rabbit import RabbitBroker
broker = RabbitBroker ( "amqp://guest:guest@localhost:5672/" )
app = FastStream ( broker )
@broker . subscriber (
"test-queue" ,
filter = lambda msg : msg . content_type == "application/json" ,
)
async def handle ( name : str , user_id : int ):
assert name == "John"
assert user_id == 1
@broker . subscriber ( "test-queue" )
async def default_handler ( msg : str ):
assert msg == "Hello, FastStream!"
from faststream import FastStream
from faststream.nats import NatsBroker
broker = NatsBroker ( "nats://localhost:4222" )
app = FastStream ( broker )
@broker . subscriber (
"test-subject" ,
filter = lambda msg : msg . content_type == "application/json" ,
)
async def handle ( name : str , user_id : int ):
assert name == "John"
assert user_id == 1
@broker . subscriber ( "test-subject" )
async def default_handler ( msg : str ):
assert msg == "Hello, FastStream!"
Note
A subscriber without a filter is a default subscriber. It consumes messages that have not been consumed yet.
For now, the following message will be delivered to the handle
function
And this one will be delivered to the default_handler
Last update: 2023-09-21