【问题标题】:How to cache a complex object such as Map<String, List<Car>> in a Spring Boot app如何在 Spring Boot 应用程序中缓存 Map<String, List<Car>> 等复杂对象
【发布时间】:2018-10-27 16:41:27
【问题描述】:

我的 Spring Boot 应用程序有 许多 类型为 Map&lt;String, List&lt;Car&gt;&gt; 的复杂对象,我喜欢将它们缓存在某处。

我不想在程序中为此使用静态变量,就好像应用程序将在负载平衡器后面运行一样,每个实例可能会从其自己的内存缓存中获得不同的结果,并且不会占用一个应用程序中的更改另一个效果。

所以我在查看 Redis & its Jedis client,但似乎我们只能缓存 &lt;String, String&gt; 类型的地图中的项目,但不能缓存更复杂的项目。

我还检查了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&lt;Car&gt;,为什么要存储密钥?
  • 但这个复杂的对象似乎没有被缓存显示不起作用的代码,以及缓存的配置。
  • @riorio 你找到问题了吗?我在缓存复杂的地图对象时遇到了同样的问题
  • 这里有同样的问题:我使用 CrudRepository 从 redis 保存和加载实体。我有一个带有 Map> 的实体(@RedisHash),列表项存储为单字节值,而不是字符串本身。在 Redisson 中,我认为这个用例有一种特殊类型,但在 spring data redis 中我还没有找到任何相关信息。请帮忙

标签: java spring-boot caching redis


【解决方案1】:

其中一种可能的解决方案是使用 Redis 哈希。它的键将是您的复杂对象的名称。其属性的键将是地图的键。而List&lt;Car&gt; 可以用 JSON 序列化。

如果您经常需要对所有此映射进行迭代,则可以改为将所有 Map&lt;String, List&lt;Car&gt;&gt; 序列化为 JSON 并存储为单个键。但是更新这个对象需要很长时间。

【讨论】:

  • 是的,当我在Class上使用RedisHash时,List可以用spring数据redis进行序列化和保存。但是一个 Map> 不能用 redis 正确保存,只存储一个字节而不是正确的对象。
  • @Holger 我没有看到问题。你能看这里github.com/Imaskar/springcache 吗?我存储Map&lt;String, List&lt;Car&gt;&gt; 就好了。
  • 但您无法将其作为 RedisHash 保存在 redis 中;)
猜你喜欢
  • 2012-06-22
  • 2020-07-14
  • 2019-10-01
  • 2020-01-26
  • 2012-11-29
  • 1970-01-01
  • 2021-12-27
  • 2013-01-15
  • 1970-01-01
相关资源
最近更新 更多