问题:springboot整合kafka,作为消费端,对端的kafka系统是在生产环境,在本地开发测试时配置了对端的生产环境的kafka地址。因为开发环境和对端生产环境是不通的,所以连接肯定是失败的,kafka的连接失败导致springboot项目启动时停机。
思路:
ConcurrentKafkaListenerContainerFactory
时配置setAutoStartup(false)
。方法2:使用kafka@KafkaListener
注解时配置`autoStartup = “false”。@KafkaListener
注解时配置id = "kafkaTest"
。创建MyApplicationReadyEventListener
在spingboot项目启动完成后再手动启动kafka消费端import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.kafka.config.KafkaListenerEndpointRegistry;
import org.springframework.kafka.listener.MessageListenerContainer;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class MyApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
@Autowired
private KafkaListenerEndpointRegistry registry;
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
MessageListenerContainer messageListenerContainer = registry
.getListenerContainer("kafkaTest");
if(Objects.nonNull(messageListenerContainer)) {
if(!messageListenerContainer.isRunning()) {
messageListenerContainer.start();
} else {
if(messageListenerContainer.isContainerPaused()) {
messageListenerContainer.resume();
}
}
}
}
}