如何部分地更新Spring缓存(仅一个字段)?(当对象突变时) [英] How to update spring cache partiallly(one field only)?(when object mutates)

查看:63
本文介绍了如何部分地更新Spring缓存(仅一个字段)?(当对象突变时)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下,我有一种方法可以为所有实体更新一个字段.

Let's imagine that I have a method which can updates one field for all entities.

public void makeAllCarsRed(){...}

我知道Spring提供了3个注释来管理缓存:

I know that Spring offers 3 annotation to manage cache:

  1. @Cacheable -尝试在缓存中查找值.如果找不到-执行方法并添加到缓存中;
  2. @CachEvict -只需根据条件从缓存中删除对象;
  3. @CachPut -将新值放入缓存
  1. @Cacheable - tries to find value in cache. If cannot find - execute method and adds to cache;
  2. @CachEvict - just remove objects from cache by criteria;
  3. @CachPut - put new value to cache

我看不到针对我的情况应用这些注释的方法.

I don't see a way to apply these annotations for my situation.

我认为要使所有哈希失效都太昂贵了

I think that it is too expensive to invalidate all cach

推荐答案

Spring会缓存整个实体,而不是单个字段.因此,您不能从缓存中逐出一个字段.

Spring caches a whole entity, not a single field. So you cannot evict a field from the cache.

如果您想从缓存中逐出实体,那么您也将有一个问题,但这可以解决:

If you would want to evict the entities from the cache, you would also have aproblem, but that can be solved :

在方法之外,它是不可见的,哪些实体已更新,所以您不能使用这些注释中的任何一个.

Outside your method it is not visible, which entites are updated, so you cannot use any of these annotations.

您可以做的是将CacheManager注入拥有方法makeAllCarsRed()的类中,然后手动更新所有已更新实体的缓存:

What you can do, is get the CacheManager injected into the class that owns the method makeAllCarsRed() and than update the cache manually for all entites that are updated :

在您的配置中

@Bean
public CacheManager cacheManager() {
    return new ConcurrentMapCacheManager("cacheName");
}

具有makeAllCarsRed()的类:

class that has makeAllCarsRed() :

public class MakeAllCarsRedService{
@Autowired CacheManager cm;
...
public void makeAllCarsRed(){
Cache cache = cm.getCache("cacheName");
//remove from cache
cache.evict(key)
//or, if neddec add to cache
put(key, entity);
...
}
}

这篇关于如何部分地更新Spring缓存(仅一个字段)?(当对象突变时)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆