对于最新的稳定版本,请使用 Spring for Apache Kafka 3.2.1Spring中文文档

对于最新的稳定版本,请使用 Spring for Apache Kafka 3.2.1Spring中文文档

手动分配所有分区

假设您希望始终从所有分区读取所有记录(例如,当使用压缩主题加载分布式缓存时),手动分配分区而不是使用 Kafka 的组管理会很有用。 当有许多分区时,这样做可能会很笨拙,因为您必须列出分区。 如果分区数随时间变化,这也是一个问题,因为每次分区计数更改时都必须重新编译应用程序。Spring中文文档

下面是如何在应用程序启动时使用 SpEL 表达式的强大功能动态创建分区列表的示例:Spring中文文档

@KafkaListener(topicPartitions = @TopicPartition(topic = "compacted",
            partitions = "#{@finder.partitions('compacted')}"),
            partitionOffsets = @PartitionOffset(partition = "*", initialOffset = "0")))
public void listen(@Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key, String payload) {
    ...
}

@Bean
public PartitionFinder finder(ConsumerFactory<String, String> consumerFactory) {
    return new PartitionFinder(consumerFactory);
}

public static class PartitionFinder {

    private final ConsumerFactory<String, String> consumerFactory;

    public PartitionFinder(ConsumerFactory<String, String> consumerFactory) {
        this.consumerFactory = consumerFactory;
    }

    public String[] partitions(String topic) {
        try (Consumer<String, String> consumer = consumerFactory.createConsumer()) {
            return consumer.partitionsFor(topic).stream()
                .map(pi -> "" + pi.partition())
                .toArray(String[]::new);
        }
    }

}

将此功能结合使用将在每次启动应用程序时加载所有记录。 还应将容器设置为,以防止容器为使用者组提交偏移量。 从版本 3.1 开始,当使用手动主题分配且没有使用者时,容器将自动强制执行 to 。 但是,从版本 2.5.5 开始,如上所示,您可以将初始偏移量应用于所有分区;有关详细信息,请参阅显式分区分配ConsumerConfig.AUTO_OFFSET_RESET_CONFIG=earliestAckModeMANUALnullAckModeMANUALgroup.idSpring中文文档

Kafka 与其他事务管理器的事务示例

以下 Spring Boot 应用程序是链接数据库和 Kafka 事务的示例。 侦听器容器启动 Kafka 事务,注解启动 DB 事务。 首先提交数据库事务;如果 Kafka 事务提交失败,则将重新传送记录,因此数据库更新应该是幂等的。@TransactionalSpring中文文档

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public ApplicationRunner runner(KafkaTemplate<String, String> template) {
        return args -> template.executeInTransaction(t -> t.send("topic1", "test"));
    }

    @Bean
    public DataSourceTransactionManager dstm(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Component
    public static class Listener {

        private final JdbcTemplate jdbcTemplate;

        private final KafkaTemplate<String, String> kafkaTemplate;

        public Listener(JdbcTemplate jdbcTemplate, KafkaTemplate<String, String> kafkaTemplate) {
            this.jdbcTemplate = jdbcTemplate;
            this.kafkaTemplate = kafkaTemplate;
        }

        @KafkaListener(id = "group1", topics = "topic1")
        @Transactional("dstm")
        public void listen1(String in) {
            this.kafkaTemplate.send("topic2", in.toUpperCase());
            this.jdbcTemplate.execute("insert into mytable (data) values ('" + in + "')");
        }

        @KafkaListener(id = "group2", topics = "topic2")
        public void listen2(String in) {
            System.out.println(in);
        }

    }

    @Bean
    public NewTopic topic1() {
        return TopicBuilder.name("topic1").build();
    }

    @Bean
    public NewTopic topic2() {
        return TopicBuilder.name("topic2").build();
    }

}
spring.datasource.url=jdbc:mysql://localhost/integration?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.consumer.properties.isolation.level=read_committed

spring.kafka.producer.transaction-id-prefix=tx-

#logging.level.org.springframework.transaction=trace
#logging.level.org.springframework.kafka.transaction=debug
#logging.level.org.springframework.jdbc=debug
create table mytable (data varchar(20));

对于仅限生产者的事务,事务同步的工作原理是:Spring中文文档

@Transactional("dstm")
public void someMethod(String in) {
    this.kafkaTemplate.send("topic2", in.toUpperCase());
    this.jdbcTemplate.execute("insert into mytable (data) values ('" + in + "')");
}

将把其事务与数据库事务同步,提交/回滚发生在数据库之后。KafkaTemplateSpring中文文档

如果您希望首先提交 Kafka 事务,并且仅在 Kafka 事务成功时才提交 DB 事务,请使用嵌套方法:@TransactionalSpring中文文档

@Transactional("dstm")
public void someMethod(String in) {
    this.jdbcTemplate.execute("insert into mytable (data) values ('" + in + "')");
    sendToKafka(in);
}

@Transactional("kafkaTransactionManager")
public void sendToKafka(String in) {
    this.kafkaTemplate.send("topic2", in.toUpperCase());
}

自定义 JsonSerializer 和 JsonDeserializer

序列化程序和反序列化程序支持使用属性进行多种 cusomization,有关详细信息,请参阅 JSON。 代码(而不是 Spring)实例化这些对象,除非将它们直接注入使用者和生产者工厂。 如果您希望使用属性配置(反)序列化程序,但希望使用自定义,只需创建一个子类并将自定义映射器传递到构造函数中。例如:kafka-clientsObjectMappersuperSpring中文文档

public class CustomJsonSerializer extends JsonSerializer<Object> {

    public CustomJsonSerializer() {
        super(customizedObjectMapper());
    }

    private static ObjectMapper customizedObjectMapper() {
        ObjectMapper mapper = JacksonUtils.enhancedObjectMapper();
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }

}