Reputation: 3
It seems that spring AMQP has built-in MessageConverter
support for Jackson with the Jackson2JsonMessageConverter
class, but is there an equivalent for the kotlinx serialization lib, or would it be necessary to write a custom message converter for it?
Trying to deserialize a JSON AMQP message without providing a MessageConverter Bean will cause an exception
Upvotes: 0
Views: 476
Reputation: 682
I faced this issue myself while working with Spring boot and Kotlin as well. I ended up creating my own converter like Artem said in his response.
An implementation of that would be like:
class KotlinConverter : MessageConverter {
override fun toMessage(model: Any, messageProperties: MessageProperties): Message {
val serializer = Json.serializersModule.serializer(model.javaClass)
val message = Json.encodeToString(serializer, model)
return Message(
message.toByteArray(),
messageProperties
)
}
override fun fromMessage(message: Message): Any {
return Json.decodeFromString(message.body.toString())
}
}
encodeToString needed more context to encode a model with Any type so I had to get the serializer from the model's class type.
I haven't tested the fromMessage part since I don't receive any messages from Rabbit but toMessage works fine.
And then set Rabbit's message converter like:
rabbitTemplate.messageConverter = KotlinConverter()
Upvotes: 1
Reputation: 121382
Yes, you have to write your own org.springframework.amqp.support.converter.MessageConverter
implementation for Kotlin Serialization.
It looks like we can borrow ideas from the org.springframework.messaging.converter.KotlinSerializationJsonMessageConverter
.
However you also can use a org.springframework.amqp.support.converter.MessagingMessageConverter
with a delegate to the mentioned KotlinSerializationJsonMessageConverter
.
See AbstractRabbitListenerContainerFactory.setMessageConverter(MessageConverter messageConverter)
.
Upvotes: 1