Ehcache缓存的使用
pom坐标
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>
ehcache.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<diskStore path="java.io.tmpdir/Tmp_EhCache" />
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="300"
timeToLiveSeconds="0"
memoryStoreEvictionPolicy="LRU" />
<cache
name="local"
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="300"
timeToLiveSeconds="0"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
测试读写
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
@org.junit.Test
public void testEhcache (){
CacheManager create = CacheManager.create(this.getClass().getResourceAsStream("/ehcache.xml"));
Cache cache = create.getCache("local");
cache.put(new Element("key1", "value1"));
Element element = cache.get("key1");
System.out.println(element.getObjectKey()+" : "+element.getObjectValue());
}
springboot集成Ehcache
EhcacheConfiguration.java
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@Configuration
@EnableCaching
public class EhcacheConfiguration {
@Bean
public EhCacheManagerFactoryBean cacheManagerFactoryBean(){
EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();
bean.setConfigLocation(new ClassPathResource("ehcache.xml"));
bean.setShared(true);
return bean;
}
@Bean
public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){
return new EhCacheCacheManager(bean.getObject());
}
}
使用
@Service
public class EhcahceServiceImpl implements EhcahceService {
private static final String CACHE_STRATEGY = "local";
@CachePut(value=CACHE_STRATEGY,key="#root.methodName+#info.getProduct_id()")
@Override
public ProductInfo saveProductInfo(ProductInfo info) throws Exception {
return info;
}
@Cacheable(value=CACHE_STRATEGY,key="#root.methodName+#id")
@Override
public ProductInfo getProductInfoById(Long id) throws Exception {
return null;
}}