You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成Spring Pulsar,如何配置自定义ObjectMapper适配Kotlin JSON?

可以强制Spring Pulsar使用自定义ObjectMapper,以下是具体实现方案

完全不需要担心底层Pulsar库的shaded版本问题,Spring Pulsar提供了明确的扩展点来替换默认的JSON序列化逻辑,直接覆盖即可适配Kotlin的JSON特性。

核心实现步骤

1. 定义适配Kotlin的自定义ObjectMapper

创建一个Spring Bean,配置好Kotlin专属的Jackson模块及序列化规则:

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.registerKotlinModule

@Configuration
class PulsarJsonConfig {

    @Bean
    fun kotlinObjectMapper(): ObjectMapper {
        return ObjectMapper()
            .registerKotlinModule() // 关键:启用Kotlin模块,支持data class、可空类型等
            // 按需添加Kotlin适配配置
            .configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL)
            .enable(com.fasterxml.jackson.module.kotlin.KotlinFeature.NullToEmptyCollection)
    }
}

2. 替换Spring Pulsar默认的JSON消息转换器

Spring Pulsar默认使用PulsarJsonMessageConverter处理JSON消息,我们可以自定义该转换器并注入上面的ObjectMapper,Spring会自动替换默认实现:

import org.springframework.context.annotation.Bean
import org.springframework.pulsar.converter.PulsarJsonMessageConverter

@Configuration
class PulsarConverterConfig {

    @Bean
    fun pulsarJsonMessageConverter(objectMapper: ObjectMapper): PulsarJsonMessageConverter {
        return PulsarJsonMessageConverter(objectMapper)
    }
}

3. 生产者与消费者的自动适配

完成上述配置后,使用@PulsarProducer和@PulsarListener时会自动使用自定义的ObjectMapper,无需额外指定:

// 生产者示例
import org.springframework.pulsar.annotation.PulsarProducer
import org.springframework.stereotype.Component

@Component
class KotlinJsonProducer {

    @PulsarProducer(topic = "kotlin-json-topic")
    fun sendUserMessage(user: UserData) {
        // UserData为Kotlin data class
    }
}

// 消费者示例
import org.springframework.pulsar.annotation.PulsarListener
import org.springframework.stereotype.Component

@Component
class KotlinJsonConsumer {

    @PulsarListener(topics = "kotlin-json-topic")
    fun handleUserMessage(user: UserData) {
        // 直接接收反序列化后的Kotlin对象
    }
}

关于Shaded版本的说明

Spring Pulsar确实会shade底层Pulsar客户端库,但这与我们的自定义配置完全隔离:

  • 我们替换的是Spring层面的PulsarJsonMessageConverter,它是Spring Pulsar的上层组件,依赖的ObjectMapper由Spring容器管理
  • 底层shaded库的内部ObjectMapper不会影响我们的业务消息序列化流程,两者完全独立

内容的提问来源于stack exchange,提问作者Gootik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 05:06:05