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

@Cacheable annotation, using same value in a differents methods

我正在尝试使用 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();
}

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

  • 1st time : select all fields from DataBase
  • 2nd time : select all fields from Cache
  • 3rd time : select all fields from Cache

到现在还不错

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

  • 1st time : select specific field from DataBase
  • 2nd time : select specific field from Cache
  • 3rd time : select specific field from Cache

哪个又好

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

select all fields Data from Cache

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

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

默认为 SimpleKeyGenerator is used to generate the key value in cache. SimpleKeyGenerator uses the method parameters to generate the cache key. The key value will be wrapped with the SimpleKey 对象。

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

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

  • List<User> findAll()

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

    1. userId参数
    2. 键=new SimpleKey(userId)
    3. store 方法使用键
    4. 在缓存中的结果

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

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

  • List<User> findAll()

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

    1. userId参数
    2. 键=new SimpleKey(userId)
    3. 使用键从缓存中获取结果