我有一个抽象的存根类,它需要是子类才能添加spring注释。
abstract class ConsumerStub<TYPE>{
val receivedMessages: MutableMap<String, TYPE> = ConcurrentHashMap()
open fun processMessage(@Payload payload: TYPE, record: ConsumerRecord<String, *>) {
this.receivedMessages[record.key()] = payload
}
fun receivedMessageWithKey(key: String): Boolean = this.receivedMessages.contains(key)
fun receivedMessageWithKeyCallable(key: String): Callable<Boolean> = Callable { receivedMessageWithKey(key) }
fun getReceiveMessageWithKey(key: String): TYPE? = this.receivedMessages[key]
fun reset() {
this.receivedMessages.clear()
}
}
例如:
open class WorkflowRequestConsumerStub: ConsumerStub<InternalWorkflowRequest>() {
@KafkaListener(
id = "xyzRequestConsumerStub",
topics = ["abc-workflow-requests"]
)
override fun processMessage(
@Payload payload: InternalWorkflowRequest,
record: ConsumerRecord<String, *>
) {
super.processMessage(payload, record)
}
}
我看到了ReceivedMessages的某些非常奇怪的行为。 经过调试后,我意识到似乎有2个receiveMessages实例。
stub.reset()引发空指针异常
更改代码以初始化reset()中的receiveMessages之后,processMessage()和ReceivedMessageWithKey()看到2个不同的具有不同objectIds的receiveMessages。
怎么回事?在java中,子类应该有权访问超级域中的所有受保护成员,因此我认为对kotlin也是如此。
更新:这在定义实现中的接收消息摘要和覆盖时按预期工作。如果这是在Kotlin中应该做的事情,那真的很糟糕。在这种情况下,无需考虑地图。