问题
My spring boot app has many complex objects of type Map<String, List<Car>>
that I like to cache somewhere.
I don't want to use a static variable within the program for that, as if the application will run behind a load balancer, each instance might get different results from its own memory cache, and changes in one application will not take effect in the other.
So I was looking at Redis & its Jedis client, but it seems like we can only cache items in a map with the type of <String, String>
but not more complex items.
I also checked Spring's @Cacheable annotation option, but it seems like this complex object is not cached. See code sample below.
I'm wondering what should be the right approach to cache such complex items.
This is the code from the @Cacheable
attempt:
public class ComplexObject implements Serializable {... getters & setters ...}
In the service class:
@Cacheable(value = "customerCars", key = "#customerName")
public ComplexObject buildCoblexObject(String customerName, CarsRepository carRepository) {
...
System.out.printlin("here") // printed every time method is called with the same customerName
}
In the properties file: (both simple or redis are not caching the item):
spring.cache.type=simple
#spring.cache.type=redis
#spring.redis.host=localhost
#spring.redis.port=6379
In the application class:
@SpringBootApplication
@EnableCaching
public class MyApplication {....
回答1:
One of the possible solutions would be to use a Redis hash. Its key would be a name of your complex object. Keys of its properties would be keys of the map. And List<Car>
can be serialized with JSON.
If you often need to do iterations across all this map, you can instead serialize all Map<String, List<Car>>
to JSON and store as a single key. But updates to this object would take significant time.
来源:https://stackoverflow.com/questions/50390996/how-to-cache-a-complex-object-such-as-mapstring-listcar-in-a-spring-boot-ap