缓存 JpaRepository 中的方法(Spring Data)

xia*_*oli 5 java spring spring-data-jpa spring-boot

工具:Spring-Boot:1.5.9.RELEASE Spring-Data-JPA:1.11.9.RELEASE

问题:目前我有一个从 JpaRepository 扩展的存储库。为了避免频繁的DB访问,我想在JpaRepository中缓存一些CRUD方法。我尝试了几种可以从 Google 先生那里找到的方法,但除了一种方法外,其他方法都不起作用。

已编辑 1. 此链接中提到的解决方案是可行的。但是,这里有一个不好的做法(对我来说是冗余的)。想象一下,如果我有 50 个存储库扩展 JpaRepository,这意味着我必须覆盖 50 个存储库中的 save 方法。

     public interface UserRepository extends CrudRepository<User, Long> {
        @Override
        @CacheEvict("user")
        <S extends User> S save(S entity);

        @Cacheable("user")
        User findByUsername(String username);
     }
Run Code Online (Sandbox Code Playgroud)

编辑 2. 扩展 JpaRepository 接口。我看到了一些可能在link2 上工作的东西。

在链接中,它提到了 3 种不同的缓存 JpaRepository 方法的方法。第一种方法与我在#1 中提到的方法相同。但是,我想要类似于 2nd/3rd 方法的东西,这样我就不需要不断重复覆盖所有存储库中的 CRUD 方法

下面是我编写的一些示例代码。

    @NoRepositoryBean        
    public interface BaseRepository<T, ID extends Serializable> extends 
    JpaRepository<T, ID> {

        @CacheEvict
        <S extends User> S save(S entity);

        @Cacheble
        T findOne(ID id);
    }

    @Repository
    @CacheConfig("user")
    public interface UserRepository extends BaseRepository<User, Integer> {
        // when I calling findOne/save method from UserRepository, it should 
        // caching the methods based on the CacheConfig name defined in the 
        // child class.
    }
Run Code Online (Sandbox Code Playgroud)

但是,当我遇到异常时,代码(上面的)似乎不起作用。我理解这个问题主要是因为没有为 BaseRepository 中的可缓存注释分配名称。但是我需要在从 JpaRepository 扩展的 BaseRepository 中缓存 CRUD 方法。

java.lang.IllegalStateException: 无法为 'Builder[public abstract java.util.List com.sdsap.app.repository.BaseRepository.findAll()] caches=[] | 解析缓存 键='' | 密钥生成器='' | 缓存管理器='' | cacheResolver='' | 条件='' | 除非='' | sync='false'' 使用解析器 'org.springframework.cache.interceptor.SimpleCacheResolver@30a9fd0'。每个缓存操作应至少提供一个缓存。

我已经问了谷歌先生几天了,但找不到任何合适的解决方案。我希望有人能在这里帮助我。对不起,如果我的问题不清楚或遗漏了什么,因为这是我第一次在这里发帖。谢谢!

Sha*_*pta 0

使用@CachedResult您想要缓存的方法。

在你的主类中使用@EnableCaching.

示例代码: Main

@SpringBootApplication
@EnableCaching
@RestController
public class SpringBootCacheApplication {

    @Autowired
    SomeBean someBean;

    @RequestMapping(value = "/cached/{key}")
    public int getCachedMethod(@PathVariable("key") String key) {
        System.out.println("Got key as " + key);
        return someBean.someCachedResult(key);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBootCacheApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

SomeBean类包含我希望缓存的方法

@Component
public class SomeBean {

    @CacheResult
    public int someCachedResult(String key) {
        System.out.println("Generating random number");
        int num = new Random().nextInt(200);
        return num;
    }

}
Run Code Online (Sandbox Code Playgroud)

在该someCachedResult方法中,我总是返回一些随机值。由于它被缓存,您只会在第一次时获得随机值。

这里SomeBean应该对应于你的CachingUserRepository班级。