我正在访问状态存储以对其进行查询,并且不得不用try / catch块包装store()
语句以重试它,因为有时我会遇到此异常:
org.apache.kafka.streams.errors.InvalidStateStoreException: Cannot get state store customers-store because the stream thread is PARTITIONS_REVOKED, not RUNNING
at org.apache.kafka.streams.state.internals.StreamThreadStateStoreProvider.stores(StreamThreadStateStoreProvider.java:49)
at org.apache.kafka.streams.state.internals.QueryableStoreProvider.getStore(QueryableStoreProvider.java:57)
at org.apache.kafka.streams.KafkaStreams.store(KafkaStreams.java:1053)
at com.codependent.kafkastreams.customer.service.CustomerService.getCustomer(CustomerService.kt:75)
at com.codependent.kafkastreams.customer.service.CustomerServiceKt.main(CustomerService.kt:108)
这是用于检索商店的代码(完整代码在github repo上):
fun getCustomer(id: String): Customer? {
var keyValueStore: ReadOnlyKeyValueStore<String, Customer>? = null
while(keyValueStore == null) {
try {
keyValueStore = streams.store(CUSTOMERS_STORE, QueryableStoreTypes.keyValueStore<String, Customer>())
} catch (ex: InvalidStateStoreException) {
ex.printStackTrace()
}
}
val customer = keyValueStore.get(id)
return customer
}
这是主程序:
fun main(args: Array<String>) {
val customerService = CustomerService("main", "localhost:9092")
customerService.initializeStreams()
customerService.createCustomer(Customer("53", "Joey"))
val customer = customerService.getCustomer("53")
println(customer)
customerService.stopStreams()
}
在先前的执行完成之后,异常会随机运行该程序几次。注意:我对正在执行的Kafka集群不做任何事情,而是使用其默认配置。
答案 0 :(得分:0)
在您访问商店时,Kafka Streams应用程序正在重新平衡,并且当时无法访问状态商店。您要确保仅在应用程序状态为“正在运行”而不是“重新平衡”时查询商店。
您可以做的是在尝试从商店读取数据之前检查应用程序的状态:
if(streams.state() == State.RUNNING) {
keyValueStore = streams.store(...);
val customer = keyValueStore.get(id);
return customer;
}
还有一种KafkaStreams.setStateListener
方法可用于注册KafkStreams.StateListener
实现。每次应用程序更改其状态时,都会调用StateListener.onChange
方法。