Spring Integration和Kafka:如何根据消息头过滤消息

时间:2020-02-28 12:23:17

标签: apache-kafka spring-integration spring-kafka

我有一个基于此问题的问题:Filter messages before deserialization based on headers

我想使用Spring Integration DSL按kafka消费者记录标头进行过滤。

目前我有这个流程:

DestinationChild

如何在此流程中注册@Bean IntegrationFlow readTicketsFlow(KafkaProperties kafkaProperties, ObjectMapper jacksonObjectMapper, EventService<Ticket> service) { Map<String, Object> consumerProperties = kafkaProperties.buildConsumerProperties(); DefaultKafkaConsumerFactory<String, String> consumerFactory = new DefaultKafkaConsumerFactory<>(consumerProperties); return IntegrationFlows.from( Kafka.messageDrivenChannelAdapter( consumerFactory, TICKET_TOPIC)) .transform(fromJson(Ticket.class, new Jackson2JsonObjectMapper(jacksonObjectMapper))) .handle(service) .get(); }

1 个答案:

答案 0 :(得分:4)

您可以简单地向流程中添加一个.filter()元素。

.filter("!'bar'.equals(headers['foo'])")

将过滤掉(忽略)标题为foo等于bar的邮件。

请注意,Spring Kafka的RecordFilterStrategy具有与Spring Integration过滤器相反的含义

public interface RecordFilterStrategy<K, V> {

    /**
     * Return true if the record should be discarded.
     * @param consumerRecord the record.
     * @return true to discard.
     */
    boolean filter(ConsumerRecord<K, V> consumerRecord);

}

Spring Integration过滤器如果过滤器返回false,则丢弃消息。

编辑

或者您可以将RecordFilterStrategy添加到频道适配器。

return IntegrationFlows
        .from(Kafka.messageDrivenChannelAdapter(consumerFactory(), TEST_TOPIC1)
                .recordFilterStrategy(record -> {
                    Header header = record.headers().lastHeader("foo");
                    return header != null ? new String(header.value()).equals("bar") : false;
                })
                ...