问题:springboot整合kafka,作为消费端,对端的kafka系统是在生产环境,在本地开发测试时配置了对端的生产环境的kafka地址。因为开发环境和对端生产环境是不通的,所以连接肯定是失败的,kafka的连接失败导致springboot项目启动时停机。
思路:
- 将kafka消费端配置自启动关闭。方法1:创建
ConcurrentKafkaListenerContainerFactory
时配置setAutoStartup(false)
。方法2:使用kafka@KafkaListener
注解时配置`autoStartup = “false”。
这样kakfa的消费端不会自己启动,也就不会影响springboot项目的启动。 - springboot项目启动完成后,再手动启动kafka消费端。使用kafka
@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> {@Autowiredprivate KafkaListenerEndpointRegistry registry;@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {MessageListenerContainer messageListenerContainer = registry.getListenerContainer("kafkaTest");if(Objects.nonNull(messageListenerContainer)) {if(!messageListenerContainer.isRunning()) {messageListenerContainer.start();} else {if(messageListenerContainer.isContainerPaused()) {messageListenerContainer.resume();}}}}
}