实际上我有一个Spring Boot应用程序,我使用kafka嵌入式而不使用spring-kafka但是使用了汇合库。
我配置了自定义拓扑,当我启动junit时,流仍然在监听,并且Spring引导服务器不会结束。
我尝试使用@DirtiesContext,但问题仍然存在。
开始使用junit
@RunWith(SpringRunner.class)
@SpringBootTest
当消费者处于循环中时,我在控制台中看到此消息:
[生产者 的clientId = application1-3c4587c8-23f0-4c8b-8ef0-75bc1e0f966c-StreamThread -1-生产者] 无法建立与节点-1的连接。经纪人可能不会 可用。
提示?
谢谢
答案 0 :(得分:0)
似乎发生错误是因为代理未运行。但KafkaStreams正在运行。
为了解决这个问题,我认为你需要阻止KafkaStreams在测试时运行。
@SpringBootTest注释提供属性类。您可以指定将注册为bean的类
您可以通过指定classes属性来阻止注册KafkaStreams相关bean。
例如,您可以按如下方式进行测试。在这种情况下,不会发生上述问题,因为没有注册KafkaStreams相关的bean。
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ServiceImpl.class, CommonConfig.class})
public class SomeClassTest {
@Autowired
private ServiceImpl articleServiceImpl;
// do test
}
使用@SpringBootTest时,最好只注册要测试的bean。
如果您不熟悉这种方法,请尝试模拟管理KafkaStreams对象的bean
例如,我创建了以下bean来启动和结束KafkaStreams对象。
@Component
public class ManageableStream implements DisposableBean, InitializingBean {
private final KafkaStreams kafkaStreams;
public ManageableStream() {
StreamsConfig config = buildStreamConfig();
StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> inputStream = builder.stream("source.topic");
inputStream.to("destination.topic");
Topology topology = builder.build();
kafkaStreams = new KafkaStreams(topology, config);
}
@Override
public void destroy() throws Exception {
kafkaStreams.close();
}
@Override
public void afterPropertiesSet() throws Exception {
kafkaStreams.start();
}
private StreamsConfig buildStreamConfig() {
Map<String, Object> properties = new HashMap<>();
properties.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
properties.put(StreamsConfig.APPLICATION_ID_CONFIG, "test-stream-application");
properties.put(StreamsConfig.PROCESSING_GUARANTEE_CONFIG, AT_LEAST_ONCE);
properties.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
properties.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.StringSerde.class);
return new StreamsConfig(properties);
}
}
测试时,模拟管理KafkaStreams对象的bean。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@MockBean
private ManageableStream manageableStream;
@Test
public void contextLoads() {
}
}
然后KafkaStreams将无法启动,因此上述问题不会发生。
如果您想测试KafkaStreams的拓扑,请参阅下面的链接
https://kafka.apache.org/11/documentation/streams/developer-guide/testing.html
我希望我的回答很有帮助