@Cacheable注解,在不同的方法中使用相同的值

Ibt*_*ama 4 caching ehcache spring-cache cacheapi

我正在尝试使用 Spring @Cacheable 注释。

 @Cacheable(value="users")          
public List<User> findAll() {
    System.out.println("Looking for All users : ");
    return userRepository.findAll();
}

@Override
@Cacheable(value="users")  
public User findOne(String userId) {
    System.out.println("Looking for user : "+ userId);
    return userRepository.findById(userId).get();
}
Run Code Online (Sandbox Code Playgroud)

当我执行第一个方法时,List<User>我得到:

  • 第一次:从数据库中选择所有字段
  • 第二次:从缓存中选择所有字段
  • 第三次:从缓存中选择所有字段

到目前为止这都很好。

当我执行第二种方法时,findOne(String userId)我得到的结果是:

  • 第一次:从数据库中选择特定字段
  • 第二次:从缓存中选择特定字段
  • 第三次:从缓存中选择特定字段

这又好了。

当我执行第一个方法时,List<User>我得到:

从缓存中选择所有字段数据

问题:这两种方法(和 )如何具有相同的缓存名称,但返回不同的结果。List<User>findOne(String userId)

Igo*_*gor 5

当您使用注释来注释您的方法时@Cacheable,Spring 将对其应用缓存行为。缓存名称用于将同一缓存区域中的缓存数据分组。但是为了将值存储在缓存区域中,Spring 将生成缓存键。

默认情况下,SimpleKeyGenerator用于在缓存中生成键值。SimpleKeyGenerator使用方法参数来生成缓存键。键值将用SimpleKey对象包装。

因此,在您的情况下,它将执行以下操作:

第一次调用- 缓存中没有数据

  • List<User> findAll()

    1. 无参数
    2. 关键=SimpleKey.EMPTY
    3. 使用键将方法结果存储在缓存中
  • User findOne(String userId)

    1. userId范围
    2. 关键=new SimpleKey(userId)
    3. 使用键将方法结果存储在缓存中

如上所示,虽然@Cacheable两种情况下的缓存名称相同,但用于存储方法结果的键不同。当您再次调用您的方法时:

第二次调用- 缓存中的数据

  • List<User> findAll()

    1. 无参数
    2. 关键=SimpleKey.EMPTY
    3. 使用key从缓存中获取结果
  • User findOne(String userId)

    1. userId范围
    2. 关键=new SimpleKey(userId)
    3. 使用key从缓存中获取结果