我有一个类,它向Kafka
生成消息(使用zio-kafka
):
case class MyObject(name: String, otherObject: OtherObject)
class MyProducer(config: KafkaConfiguration) {
val layer: ZLayer[Any, Throwable, Producer] = config.layer() //it creates layer
def produceEvent(e: MyObject): RIO[Producer, Unit] = {
val message = new ProducerRecord(topic, e)
Producer.produce(message, Serde.int, Serde.Json).unit
}
}
object MyProducer {
val layer: ZLayer[SomeConfig, Throwable, MyProducer] = ZLayer(for { ... } yield new MyProducer(config)
}
字符串
现在我想在其他地方使用这个produceEvent
方法:
class A(producer: MyProducer) {
def doSmth(): ZIO[Producer, Throwable, Unit] {
for {
// some logic
_ <- producer.produceEvent(event)
} yield ()
}
}
型
问题是在运行时我得到一个错误:
Defect in zio.Environment: Could not find Producer inside Environment
型
我不知道如何向scope提供Producer
。我正确地提供了MyProducer
,但是我需要返回ZIO[Producer, Throwable, Unit]
。也许有其他解决方案可以从环境中“剪切”这个Producer,然后返回Task[Unit]
?
1条答案
按热度按时间4uqofj5v1#
实际上,将
Producer
保持在MyProducer
本地是有意义的。您可以立即“提供”:
字符串