我使用Spring Kafka 1.1.2-RELEASE和Spring Boot 1.5.0 RC,我已经配置了一个自定义值序列化器/解串器类,扩展了org.springframework.kafka.support.serializer.JsonSerializer
/ org.springframework.kafka.support.serializer.JsonDeserializer
。这些类确实使用了Jackson ObjectMapper,它可以通过构造函数提供。
在某种程度上可以从我的Spring上下文中注入ObjectMapper吗?我已经配置了一个ObjectMapper,我想在serialiser / deserialiser中重用它。
答案 0 :(得分:7)
您可以将JsonSerializer
和JsonDeserializer
配置为@Bean
。
向他们注入所需的ObjectMapper
。并在DefaultKafkaProducerFactory
和DefaultKafkaConsumerFactory
bean定义中使用这些bean:
@Bean
public ProducerFactory<Integer, String> producerFactory() {
DefaultKafkaProducerFactory<Integer, String> producerFactory =
new DefaultKafkaProducerFactory<>(producerConfigs());
producerFactory.setValueSerializer(jsonSerializer());
return producerFactory;
}
答案 1 :(得分:1)
@Component
public class ObjectMapperProducerFactoryCustomizer implements DefaultKafkaProducerFactoryCustomizer {
private final ObjectMapper objectMapper;
public ObjectMapperProducerFactoryCustomizer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
@Override
public void customize(DefaultKafkaProducerFactory<?, ?> producerFactory) {
if (Objects.nonNull(producerFactory)) {
producerFactory.setValueSerializer(new JsonSerializer<>(objectMapper));
}
}
}
答案 2 :(得分:0)
对于反应式非阻塞 kafka 客户端,配置如下:
@Configuration
@EnableConfigurationProperties(KafkaProperties.class)
public class KafkaConfig {
@Bean
public ReactiveKafkaProducerTemplate<String, Object> kafkaProducerTemplate(KafkaProperties p,
ObjectMapper objectMapper) {
return new ReactiveKafkaProducerTemplate<>(
SenderOptions.<String, Object>create(p.buildProducerProperties())
.withValueSerializer(new JsonSerializer<>(objectMapper)));
}
}
以上暗示您正在使用 io.projectreactor.kafka
dep,
dependencies {
compile "io.projectreactor.kafka:reactor-kafka"
}