Skip to content
Advertisement

Spring Boot + Infinispan embedded – how to prevent ClassCastException when the object to be cached has been modified?

I have a web application with Spring Boot 2.5.5 and embedded Infinispan 12.1.7.

I have a Controller with an endpoint to get a Person object by ID:

JavaScript

The following is the PersonService implementation with the use of the @Cacheable annotation on the getPerson method :

JavaScript

And here is the Person class:

JavaScript

I configured infinispan to use a filesystem-based cache store:

JavaScript

I request the endpoint to get the person with id ‘1’: http://localhost:8090/assets-webapp/person/1
PersonService.getPerson(String) is called the first time and the result is cached.
I request again the endpoint to get the person with id ‘1’, and I retrieve the result in the cache.

I update the Person object by removing the extra field with getter/setter, and I add a extra2 field:

JavaScript

I request again the endpoint to get the person with id ‘1’, but a ClassCastException is thrown:

JavaScript

I rollback the Person object modifications by removing the extra2 field and adding the extra field.
I request again the endpoint to get the person with id ‘1’, but a ClassCastException is always thrown

The marshaller used by infinispan is JavaSerializationMarshaller.

I guess java serialization does not allow to unmarchall the cached data if the class has been recompiled.

But I would like to know how to avoid this, and especially to be able to manage updates of the class (adding/removing fields) without having an exception when accessing the cached data.

Does anyone have a solution?

Advertisement

Answer

I finally created my own Marshaller that serialize/deserialize in JSON, inspired by the following class: GenericJackson2JsonRedisSerializer.java

JavaScript

The Serializer/Deserializer for SimpleKey object:

JavaScript

And I configured infinispan like the following:

JavaScript
Advertisement