Home > database >  How to configure Kafka type mapping using spring kafka?
How to configure Kafka type mapping using spring kafka?

Time:09-17

I've looked at the documentation and found this:

spring.kafka.producer.properties.spring.json.type.mapping=cat:com.mycat.Cat,hat:com.myhat.Hat

My producer properties:

spring.kafka.producer.bootstrap-server=localhost:9092
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.springframework.kafka.support.serializer.JsonSerializer 
spring.kafka.producer.properties.spring.json.type.mapping=com.producerservice.dto.UserDTO:UserDTO

The maven install run successfully.

The consumer properties:

spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.springframework.kafka.support.serializer.JsonDeserializer
spring.kafka.consumer.properties.spring.json.type.mapping=com.consumerservice.dto.UserDTO:UserDTO
spring.kafka.consumer.properties.spring.json.trusted.packages=*

This one maven install failed:

Caused by: java.lang.IllegalArgumentException: Failed to load: UserDTO for com.consumerservice.dto.UserDTO
    at org.springframework.kafka.support.serializer.JsonSerializer.createMappings(JsonSerializer.java:188) ~[spring-kafka-2.8.8.jar:2.8.8]
    at org.springframework.kafka.support.serializer.JsonDeserializer.createMappings(JsonDeserializer.java:438) ~[spring-kafka-2.8.8.jar:2.8.8]
    at org.springframework.kafka.support.serializer.JsonDeserializer.configure(JsonDeserializer.java:418) ~[spring-kafka-2.8.8.jar:2.8.8]
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:716) ~[kafka-clients-3.1.1.jar:na]

Can't figure it out.

CodePudding user response:

According to the doc, on a consumer side a token still should go first (before a full classname):

consumerProps.put(JsonDeSerializer.TYPE_MAPPINGS, "cat:com.yourcat.Cat, hat:com.yourhat.hat");

So: spring.kafka.consumer.properties.spring.json.type.mapping=UserDTO:com.consumerservice.dto.UserDTO

  • Related