我有两个卡夫卡主题my_priorized_topic
和my_not_so_priorized_topic
。我想在EventProcessor.doLogic
上使用互斥锁,并始终优先处理来自my_prioritized_topic
的消息之前来自my_not_so_prioritized_topic
的句柄消息
有人可以给我一些指导,如何用Kotlin(也许是协程)解决这个问题吗?
class EventProcessor {
fun doLogic(message: String) {
... // code which cannot be parallelized
}
}
class KafkaConsumers(private val eventProcessor: EventProcessor) {
@KafkaConsumer(topic = "my_priorized_topic")
fun consumeFromPriorizedTopic(message: String) {
eventProcessor.doLogic(message)
}
@KafkaConsumer(topic = "my_not_so_priorized_topic")
fun consumeFromNotSoPrioritizedTopic(message: String) {
eventProcessor.doLogic(message)
}
}
答案 0 :(得分:0)
您可以为高优先级任务和低优先级任务创建两个Channel
。然后,要使用通道中的事件,请使用协程的select表达式,然后将高优先级任务通道放在首位。
示例(字符串是偶数):
fun process(value: String) {
// do what you want with the event
}
suspend fun selectFromHighAndLow(highPriorityChannel: ReceiveChannel<String>, lowPriorityChannel: ReceiveChannel<String>): String =
select<String> {
highPriorityChannel.onReceive { value ->
value
}
lowPriorityChannel.onReceive { value ->
value
}
}
val highPriorityChannel = Channel<String>()
val lowPriorityChannel = Channel<String>()
while (true) {
process(selectFromHighAndLow(highPriorityChannel, lowPriorityChannel))
}
要将内容发送到这些频道,可以使用channel.send(event)
。