我正在尝试为我的Kafka消费者编写集成测试。我已经跟着official reference documentation了,但是当我开始测试时,我只能看到这个无限的重复:
-2019-04-03 15:47:34.002 WARN 13120 --- [main] org.apache.kafka.clients.NetworkClient:[Consumer clientId = consumer-1,groupId = my-group]与节点-1的连接不能成立。经纪人可能无法使用。
我究竟做错了什么?
我正在使用JUnit5,Spring Boot和spring-kafka
以及spring-kafka-test
。
我在@EnableKafka
课上有@Configuration
注释。
这是我的测试类的样子:
@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [TestKafkaConfig::class])
@DirtiesContext
@EmbeddedKafka(
partitions = 1,
topics = [KafkaIntegrationTest.MY_TOPIC])
class KafkaIntegrationTest {
@Autowired
private lateinit var embeddedKafka: EmbeddedKafkaBroker
@Test
fun test() {
val senderProps = KafkaTestUtils.senderProps(embeddedKafka.brokersAsString)
val template = KafkaTemplate(DefaultKafkaProducerFactory<Int, String>(senderProps))
template.defaultTopic = KafkaIntegrationTest.MY_TOPIC
template.sendDefault("foo")
}
}
我的application.yml
看起来像这样:
kafka:
consumer:
group-id: my-group
bootstrap-servers: ${BOOTSTRAP_SERVERS:localhost:9092}
value-deserializer: io.confluent.kafka.serializers.KafkaAvroDeserializer
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
properties:
schema.registry.url: ${SCHEMA_REGISTRY_URL:http://localhost:8081}
specific.avro.reader: true
我也试过设置一个MockSchemaRegistryClient
,但我得到完全相同的重复消息。 (这是我尝试设置MockSchemaRegistryClient
的方式):
@TestConfiguration
@Import(TestConfig::class)
class TestKafkaConfig {
@Autowired
private lateinit var props: KafkaProperties
@Bean
fun schemaRegistryClient() = MockSchemaRegistryClient()
@Bean
fun kafkaAvroSerializer() = KafkaAvroSerializer(schemaRegistryClient())
@Bean
fun kafkaAvroDeserializer() = KafkaAvroDeserializer(schemaRegistryClient(), props.buildConsumerProperties())
@Bean
fun producerFactory(): ProducerFactory<*, *> = DefaultKafkaProducerFactory(
props.buildProducerProperties(),
StringSerializer(),
kafkaAvroSerializer())
@Bean
fun consumerFactory(): ConsumerFactory<*, *> = DefaultKafkaConsumerFactory(
props.buildConsumerProperties(),
StringDeserializer(),
kafkaAvroDeserializer()
)
@Bean
fun kafkaListenerContainerFactory() = ConcurrentKafkaListenerContainerFactory<Any, Any>().apply {
setConsumerFactory(consumerFactory() as ConsumerFactory<in Any, in Any>?)
}
}
我究竟做错了什么?请注意,我正在使用Confluent Schema Registry并尝试从Avro反序列化。
我正在尝试测试的是我的消费者是否正常工作,如下所示:
open class SomeConsumer(private val someUseCase) {
@KafkaListener(topics = ["\${kafka.some-topic}"])
open fun processMessage(record: ConsumerRecord<String, SomeObject>) {
someUseCase.call(record)
}
}
我相信你缺少为测试设置代理网址。
有关如何在文档中获取此值的说明:
当嵌入式Kafka和嵌入式Zookeeper服务器由EmbeddedKafkaBroker启动时,名为spring.embedded.kafka.brokers的系统属性将设置为Kafka代理的地址,并且名为spring.embedded.zookeeper.connect的系统属性将设置为Zookeeper的地址。此属性提供了方便的常量(EmbeddedKafkaBroker.SPRING_EMBEDDED_KAFKA_BROKERS和EmbeddedKafkaBroker.SPRING_EMBEDDED_ZOOKEEPER_CONNECT)。
(它位于junit部分here的底部)
解决此问题的一种方法是在测试中将kafka.consumers.bootstrap-servers
设置为此值,例如
spring:
kafka:
consumer:
bootstrap-servers: ${spring.embedded.kafka.brokers}