如何将JsonDeserializer
添加到我的Kafka用户。我现在收到一个Json字符串,并希望将其转换为数据类对象。
这是我的消费者:
ConsumerConfig:
@EnableKafka
@Configuration
class KafkaConsumerConfig {
@Value("\${kafka.host:localhost}")
private val host: String? = null
@Value("\${kafka.port:9092}")
private val port: Int = 0
@Bean
fun userConsumerConfigs(): ConsumerFactory<String, String> {
val props = HashMap<String, Any>()
props[ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG] = "$host:$port"
props[ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
props[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = StringDeserializer::class.java
props[ConsumerConfig.GROUP_ID_CONFIG] = "helloworld"
val mapper = ObjectMapper()
return DefaultKafkaConsumerFactory(props, StringDeserializer(), StringDeserializer())
//return props
}
@Bean
fun kafkaListenerContainerFactory():
KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String,
String>> {
val factory = ConcurrentKafkaListenerContainerFactory<String, String>()
factory.consumerFactory = userConsumerConfigs()
return factory
}
@Bean
fun kafkaConsumer(): Consumerz {
return Consumerz()
}
companion object {
const val TOPIC = "test"
}
}
消费者:
class Consumerz {
@KafkaListener(topics = ["usertest"])
fun receive(message: String) {
LOGGER.info("Received payload= $message")
}
companion object {
private val LOGGER = LoggerFactory.getLogger(Consumerz::class.java)
}
}
我目前仅使用StringDeserializer
。在这种情况下,我该如何实现JsonDeserializer
。
当前输出为:Received payload= { "firstName": "Jack", "lastName" : "Adam" }
谢谢。
@这是一个 Spring 项目。
答案 0 :(得分:0)
您可以按以下方式直接使用org.springframework.kafka.support.serializer.JsonDeserializer.class
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
因此,使用者配置为:
private ConsumerFactory<String, MyDomainModel> myMessageFactory() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, SERVERS);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "KAPP");
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
return new DefaultKafkaConsumerFactory<>(props, new StringDeserializer(), new JsonDeserializer<>(MyDomainModel.class));
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, MyDomainModel> myMessageListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, MyDomainModel> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(myMessageFactory());
return factory;
}