Python 浮士德出版卡夫卡主题的例子
我很好奇你应该如何表达你想要一条信息传递给浮士德的卡夫卡主题。他们自述中的示例似乎没有针对某个主题:Python 浮士德出版卡夫卡主题的例子,python,apache-kafka,faust,Python,Apache Kafka,Faust,我很好奇你应该如何表达你想要一条信息传递给浮士德的卡夫卡主题。他们自述中的示例似乎没有针对某个主题: import faust class Greeting(faust.Record): from_name: str to_name: str app = faust.App('hello-app', broker='kafka://localhost') topic = app.topic('hello-topic', value_type=Greeting) @app.a
import faust
class Greeting(faust.Record):
from_name: str
to_name: str
app = faust.App('hello-app', broker='kafka://localhost')
topic = app.topic('hello-topic', value_type=Greeting)
@app.agent(topic)
async def hello(greetings):
async for greeting in greetings:
print(f'Hello from {greeting.from_name} to {greeting.to_name}')
@app.timer(interval=1.0)
async def example_sender(app):
await hello.send(
value=Greeting(from_name='Faust', to_name='you'),
)
if __name__ == '__main__':
app.main()
在上面的代码中,我希望hello.send
可以向主题发布消息,但它似乎没有
有许多从主题读取的示例,以及许多使用cli推送特别消息的示例。在对文档进行梳理之后,我没有看到任何明确的以代码发布主题的示例。我是不是疯了,上面的代码应该能用?你可以使用
sink
告诉浮士德在哪里传递代理函数的结果。如果需要,还可以同时使用多个主题作为接收器
@app.agent(topic_to_read_from, sink=[destination_topic])
async def fetch(records):
async for record in records:
result = do_something(record)
yield result
send()
函数是调用以写入主题的正确函数。您甚至可以指定一个特定的分区,就像等价的JavaAPI调用一样
以下是send()
方法的参考:
所以我们需要向
接收器
主题以外的主题发送消息
我们找到的最简单的方法是:foo=等待我的主题。尽快发送(value=“wtfm8”)
您也可以直接使用send
,如下所示,使用asyncio事件循环
loop = asyncio.get_event_loop()
foo = await ttopic.send(value="wtfm8??")
loop.run_until_complete(foo)
如果您只想要一个浮士德制作人(而不是消费者/接收器),那么原始问题实际上有正确的代码,这里有一个功能齐全的脚本,它将消息发布到任何卡夫卡/浮士德消费者都可以使用的“浮士德测试”卡夫卡主题 像这样运行下面的代码:
python faust_producer.py worker
"""Simple Faust Producer"""
import faust
if __name__ == '__main__':
"""Simple Faust Producer"""
# Create the Faust App
app = faust.App('faust_test_app', broker='localhost:9092')
topic = app.topic('faust_test')
# Send messages
@app.timer(interval=1.0)
async def send_message(message):
await topic.send(value='my message')
# Start the Faust App
app.main()
我不知道这有多重要,但我在学习浮士德时遇到了这个问题。从我所读到的,这里是正在发生的事情:
topic = app.topic('hello-topic', value_type=Greeting)
这里的误解是,您创建的主题就是您试图使用/阅读的主题。您当前创建的主题没有任何作用
await hello.send(
value=Greeting(from_name='Faust', to_name='you'),
)
这实际上创建了一个中间的kstream,它将值发送给hello(问候语)函数。当流中有新消息时,将调用def hello(…),并将处理正在发送的消息
@app.agent(topic)
async def hello(greetings):
async for greeting in greetings:
print(f'Hello from {greeting.from_name} to {greeting.to_name}')
这是从hello.send(…)接收kafka流,并将其简单地打印到控制台(没有对创建的“主题”的输出)。在这里,您可以向新主题发送消息。因此,您可以执行以下操作,而不是打印:
topic.send(value = "my message!")
或者:
以下是您正在做的事情:
topic.send(value = "my message!")
hello.send
是asyncio
的一部分,我认为,不是Faust函数。。。浮士德主要用于流处理,而不是流“生产”。这意味着您在主题中已经有了数据,Kafka Streams的工作原理与上面的示例发送者类似,它确实将数据发布到“hello topic”。您可以通过kafka-console-consumer检查这一点。您好,我喜欢代理装饰器中的sink
参数。但是你如何测试它呢?如果我直接在agent.Hm中使用send,我只能通过模拟主题来进行单元测试。也许在测试中制作一个faust应用程序和代理,用于侦听接收器主题并验证那里的输出?文档中有一些建议,我最终使用并测试了单元测试中的产量输出。在集成测试中,我可以测试卡夫卡主题中的输出