Spring 可缓​​存错误,尝试通过 ID 密钥缓存用户并以相同方式逐出它

Spring cacheable error, trying to cache a user by ID key and evict it the same way

我正在尝试使用 spring 的 @Cacheable 进行缓存。我也在使用 spring mongodb。我不断收到以下错误:

java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) CacheableOperation[public abstract test.models.User test.repositories.UserRepository.findById(java.lang.String)] caches=[userById] | key='#id' | keyGenerator='' | cacheManager='' | cacheResolver='' | condition='' | unless=''

这是我正在使用的代码。看来无论我用“#id”还是"id"似乎都不行。要么我得到 IllegalArgumentException,要么它抱怨 id 可能不是 public,但我想在我的用户模型中将 "id" 保持为私有。

public interface UserRepository extends MongoRepository<User, String> {

    @Override
    @CacheEvict(value="byId", key="#entity.id")
    <S extends User> S save(S entity);

    @Cacheable(value="byId", key="#id")
    User findById(String id);

    public User findByUsername(String username);

}

有人可以指出我做错了什么吗?本质上,我想在redis中缓存用户下的所有"users",但以用户"id"为键缓存它。然后,我还想在保存用户时基于相同的 id 进行驱逐。

仅供参考,异常与代码不匹配(缓存的名称不同)。

findById 上的 key 属性没用。缓存抽象将默认使用方法参数来计算键。由于您只有一个参数,因此它将使用所述参数。您可以按如下方式重写该方法并获得完全相同的结果:

@Cacheable(value="byId")
User findById(String id);

我无法对其他问题发表评论。如果缓存抽象抱怨某些东西是私有的,它一定是在缓存逐出上,而不是在这个方法上。因此,发布与描述一致的异常会有所帮助。