【发布时间】:2018-10-27 16:41:27
【问题描述】:
我的 Spring Boot 应用程序有 许多 类型为 Map<String, List<Car>> 的复杂对象,我喜欢将它们缓存在某处。
我不想在程序中为此使用静态变量,就好像应用程序将在负载平衡器后面运行一样,每个实例可能会从其自己的内存缓存中获得不同的结果,并且不会占用一个应用程序中的更改另一个效果。
所以我在查看 Redis & its Jedis client,但似乎我们只能缓存 <String, String> 类型的地图中的项目,但不能缓存更复杂的项目。
我还检查了Spring's @Cacheable annotation 选项,但似乎这个复杂对象没有被缓存。请参阅下面的代码示例。
我想知道缓存这些复杂项目的正确方法应该是什么。
这是来自@Cacheable 尝试的代码:
public class ComplexObject implements Serializable {... getters & setters ...}
在服务类中:
@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
}
在属性文件中:(无论是simple还是redis都没有缓存item):
spring.cache.type=simple
#spring.cache.type=redis
#spring.redis.host=localhost
#spring.redis.port=6379
在应用程序类中:
@SpringBootApplication
@EnableCaching
public class MyApplication {....
【问题讨论】:
-
你不能只存储
List<Car>,为什么要存储密钥? -
但这个复杂的对象似乎没有被缓存显示不起作用的代码,以及缓存的配置。
-
@riorio 你找到问题了吗?我在缓存复杂的地图对象时遇到了同样的问题
-
这里有同样的问题:我使用 CrudRepository 从 redis 保存和加载实体。我有一个带有 Map
> 的实体(@RedisHash),列表项存储为单字节值,而不是字符串本身。在 Redisson 中,我认为这个用例有一种特殊类型,但在 spring data redis 中我还没有找到任何相关信息。请帮忙
标签: java spring-boot caching redis