如何获得Kafka消费者对生产者的确认或回电

时间:2017-10-16 16:39:51

标签: apache-kafka kafka-consumer-api kafka-producer-api spring-kafka

我有一个Kafka生产者向Kafka消费者发送消息的Springboot项目的例子。

这就是我的Kafka Producer配置的样子:

@Configuration
public class KafkaProducerConfig {

@Value("${my.kafka.bootstrap-servers}")
private String bootstrapServer;

@Bean
public ProducerFactory<String, Customer> producerFactory() {
    Map<String, Object> configProps = new HashMap<>();
    configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
    configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
    configProps.put(ProducerConfig.ACKS_CONFIG, "all");
    return new DefaultKafkaProducerFactory<>(configProps);
}

@Bean
public KafkaTemplate<String, Customer> kafkaTemplate() {
    return new KafkaTemplate<>(producerFactory());
}
}

以下是Kafka制作人的服务类:

@Service
public class KafkaProducer {
@Autowired
private KafkaTemplate<String, Customer> kafkaTemplate;

@Value("${my.kafka.topic}")
String kafkaTopic = "my-test";

public void send(Customer customer) {
    System.out.println("sending customer data=" + customer);
    kafkaTemplate.send(kafkaTopic, customer);
}
}

我的KafkaConsumer配置类如下所示:

@EnableKafka
@Configuration
public class KafkaConsumerConfig {

@Value("${my.kafka.bootstrap-servers}")
private String bootstrapServer;

@Value("${my.kafka.consumer.group-id}")
private String groupId;

@Bean
public ConsumerFactory<String, Customer> consumerFactory() {
    Map<String, Object> props = new HashMap<>();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServer);
    props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);

    return new DefaultKafkaConsumerFactory<>(props,
                                      new StringDeserializer(), 
                                      new JsonDeserializer<>(Customer.class));
}

@Bean
public ConcurrentKafkaListenerContainerFactory<String, Customer> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, Customer> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setConsumerFactory(consumerFactory());
    return factory;
}

}

以下是我的Kafka Consumer课程:

@Service
public class KafkaConsumer {

@KafkaListener(topics="${my.kafka.topic}")
public void processMessage(Customer customer) {
    System.out.println("received customer details = " + customer);
}
}

我想向生产者发回一个确认消息,其中可能包含客户名称的消息。但我无法弄清楚如何实现这一目标。有没有一种方法可以在消费者端提取发件人数据,这样我就可以向生产者发送消息了?

1 个答案:

答案 0 :(得分:0)

实现此目的的一种方法是在生产者应听取的另一个主题上发布确认消息。该消息可以包含您想要的数据以及相关关系数据