缓存不用于spring boot

时间:2016-11-09 05:47:17

标签: spring-boot ehcache spring-cache

在具有rest实现的Spring启动应用程序中(没有spring security的会话),我想避免多次调用用户表的数据库。

在扩展WebSecurityConfigurerAdapter的类中,我有

@Bean
public AuthenticationProvider authenticationProviderBean() throws Excen {
    DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
    authenticationProvider.setPasswordEncoder(passwordEncoder);
    authenticationProvider.setUserCache(userCache);
    authenticationProvider.setUserDetailsService(userDetailsServiceBean());

    return authenticationProvider;
}

@Configuration
@EnableCaching
public class CacheConfig {

    @Bean
    public EhCacheFactoryBean ehCacheFactoryBean(){
        EhCacheFactoryBean ehCacheFactory = new EhCacheFactoryBean();
        ehCacheFactory.setCacheManager(cacheManagerFactoryBean().getObject());
        return ehCacheFactory;
    }

    @Bean
    public CacheManager cacheManager(){
        return new EhCacheCacheManager(cacheManagerFactoryBean().getObject());
    }

    @Bean
    public EhCacheManagerFactoryBean cacheManagerFactoryBean() {
        EhCacheManagerFactoryBean cacheManager = new EhCacheManagerFactoryBean();
        return cacheManager;
    }


    @Bean
    public UserCache userCache() {
        EhCacheBasedUserCache userCache = new EhCacheBasedUserCache();
        userCache.setCache(ehCacheFactoryBean().getObject());
        return userCache;
    }
}

ehcache.xml(在java中可以做到吗?)

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true" monitoring="autodetect" dynamicConfig="true"> 
  <diskStore path="java.io.tmpdir"/> 
  <defaultCache 
     maxEntriesLocalHeap="10000" 
     eternal="false" 
     timeToIdleSeconds="60" 
     timeToLiveSeconds="300" 
     maxEntriesLocalDisk="10000000" 
     diskExpiryThreadIntervalSeconds="120" 
     memoryStoreEvictionPolicy="LRU"> 
     <persistence strategy="localTempSwap"/> 
  </defaultCache> 
</ehcache>

如何确定我的缓存已被使用?

实际上我看到在服务器上完成了查询

2 个答案:

答案 0 :(得分:0)

一种简单的方法是启用统计信息。如果我没记错的话,添加statistics="true"。因此,您将通过注册缓存管理器在JMX中看到缓存命中和未命中。

MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ManagementService.registerMBeans(cacheManager, mBeanServer, false, false, false, true);

在您的代码中,这意味着

@Bean
public CacheManager cacheManager(){
    net.sf.ehcache.CacheManager cacheManager = cacheManagerFactoryBean().getObject();

    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    ManagementService.registerMBeans(cacheManager, mBeanServer, false, false, false, true);

    return new EhCacheCacheManager(cacheManager);
}

net.sf.ehcache.Cache设置日志到DEBUG也会为您提供缓存创建,过期等信息。但是,你不会看到命中和错过。

答案 1 :(得分:0)

只需编写演示代码:

@Cacheable(value = "v")
public Object get(int id){
    System.out.println("get from db");
    return dao.findById(id);
}

如果缓存有效,则控制台中没有任何输出。