首页 > 解决方案 > 当消费者宕机时,Kafka 消息会丢失

问题描述

您好,我正在使用 spring cloud stream 编写一个 kafka 消费者生产者。在我的消费者内部,我将数据保存到数据库中,如果数据库出现故障,我将手动退出应用程序。重新启动应用程序后,如果数据库仍然处于关闭状态,则应用程序再次停止。现在,如果我第三次重新启动应用程序,在中间间隔(两次失败)中收到的消息丢失,kafka 消费者会获取最新消息,它也会跳过我退出代码的消息。

入站和出站通道绑定器接口

public interface EventChannel {

String inputEvent = "inputChannel";
String outputEvent = "outputChannel";

@Input(inputChannel)
SubscribableChannel consumeEvent();

@Output(outputEvent)
SubscribableChannel produceEvent();
}

服务等级 -

1) 生产者服务

@Service
@EnableBinding(EventChannel.class)

public class EventProducerService{

private final EventChannel eventChannel;

@Autowired  
public EventConsumerService(EventChannel eventChannel){
this.eventChannel = eventChannel;
}

public void postEvent(EventDTO event) {
    MessageChannel messageChannel = eventChannel.produceEvent();
    messageChannel.send(MessageBuilder
            .withPayload(event)
            .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON)
            .setHeader("partitionKey",event.getId().toString())
            .build());     
    }
}

2) 消费者服务

@Component
@EnableBinding(EventChannel.class)
public class EventConsumerService{ 

private final ApplicationContext applicationContext;
private final EventChannel eventChannel;

@Autowired  
public EventConsumerService(ApplicationContext applicationContext,EventChannel eventChannel){
this.applicationContext = applicationContext;
this.eventChannel = eventChannel;
}

@StreamListener(EventChannel.inputEvent)
public void saveUpdateCassandra(EventDTO event){
  Event newEvent = new Event(event);
  try{
     eventRepository.save(newEvent)
    } catch(Exceptione e){
     e.printStackTrace();
     SpringApplication.exit(applicationContext,()-> 0); 
  }
}

应用程序属性文件

#Spring Cloud Streams Configuration
##Broker
spring.cloud.stream.kafka.binder.brokers=localhost:9092
##EventIngestion 
spring.cloud.stream.bindings.outputChannel.destination=Event
spring.cloud.stream.bindings.outputChannel.producer.partitionKeyExpression=headers.partitionKey
spring.cloud.stream.bindings.inputChannel.destination=Event
spring.cloud.stream.bindings.inputChannel.group=event-consumer-1
spring.cloud.stream.kafka.bindings.inputChannel.consumer.startOffset=earliest

两个应用程序都是独立运行的,所以如果我的数据库出现故障,消费者会停止,在连续失败时消息会丢失

标签: spring-bootapache-kafkakafka-consumer-apispring-cloud-stream

解决方案


首先,我不确定您对 的期望是什么SpringApplication.exit(applicationContext,()-> 0);,但您实际上是在关闭整个应用程序,其中可能运行的所有东西。其次,您的消息丢失是由于 Kafka binder 完全不知道发生了异常并且必须将消息放回主题。事实上,从活页夹的角度来看,由于您的代码,每条消息总是被成功处理。所以。. .

try/catch从您的 StreamListener 方法中删除并让异常传播,从而让 binder 知道存在错误。


推荐阅读