Spring启动缓存结果

时间:2017-07-26 12:02:31

标签: spring-boot

我的Controller中有几个只读资源。我想在内存中缓存它们,我不清楚如何在Spring Boot中执行它。 我做了什么:

  • 使用@EnableCaching
  • 注释主要应用程序
  • 使用@Cacheable
  • 注释资源
@Cacheable
@RequestMapping(value = "/api/graph", method=RequestMethod.GET, produces = { "application/json"})
public @ResponseBody Iterable<Map<String, String>> graph() {
    return Repository.graph();
}

我错过了什么? 由于它是一个只读资源,我想我不会@CachePut我是对的吗?

我已经在maven中添加了spring-boot-starter-cache广告依赖

1 个答案:

答案 0 :(得分:0)

以下是启用缓存的步骤。例如,我为此使用Google GuavaCacheManager。

  1. 添加依赖关系,并通过使用Application类上的注释启用缓存。

    <dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>18.0</version>
    </dependency>
    
    @SpringBootApplication
    @EnableCaching
    public class Application extends SpringBootServletInitializer {
    }
    
  2. 在您的Application类中将GuavaCacheManager公开为bean。

    @Bean
    public CacheManager cacheManager() {
    GuavaCacheManager cacheManager = new GuavaCacheManager();
    // Cache expires every day
    cacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterAccess(1, 
    TimeUnit.DAYS).expireAfterWrite(1, TimeUnit.DAYS)); 
    cacheManager.setCacheNames(Arrays.asList("findUser"));
    return cacheManager;
    }
    
  3. 将方法标记为可缓存,因此所有对该方法的调用都首先尝试在Cache中查找条目(如果找不到),然后实际调用该方法

    @Override
    @Cacheable("findUser")
    public User findUser(String username) {
    // biz logic to find the user and return the object
    return user;
    }