Ehcache,一个开源的缓存机制,在一些小型的项目中可以有效的担任缓存的角色,分担数据库压力此外,ehcache在使用上也是极为简单, 下面是简单介绍一下ehcahce的本地使用的两种方式:
1,使用代码编写的方式使用ehcache:
准备一个可用的maven项目:并加入依赖;
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>
a:首先您得准备一些ehcache的配置文件:
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,是默认的缓存策略 -->
<!-- 如果你指定的缓存策略没有找到,那么就用这个默认的缓存策略 -->
<!-- external:缓存对象是否一直存在,如果设置为true的话,那么timeout就没有效果,缓存就会一直存在,一般默认就是false -->
<!-- maxElementsInMemory:内存中可以缓存多少个缓存条目 -->
<!-- overflowToDisk:如果内存不够的时候,是否溢出到磁盘 -->
<!-- diskPersistent:是否启用磁盘持久化的机制,在jvm崩溃的时候和重启之间 -->
<!-- timeToIdleSeconds:对象最大的闲置的时间,如果超出闲置的时间,可能就会过期 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大-->
<!-- timeToLiveSeconds:对象最多存活的时间 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是存活时间无穷大-->
<!-- memoryStoreEvictionPolicy:当缓存数量达到了最大的指定条目数的时候,需要采用一定的算法,从缓存中清除一批数据,LRU,最近最少使用算法,最近一段时间内,最少使用的那些数据,就被干掉了 -->
<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>
b.在编码中读取ehcache配置文件,并得到EhCacheCacheManager操作:
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());
}
运行结果:
如此,可以自己封装到单例中作为工具提供。
2.使用springboot注解方法:
准备工作:一个可以正常使用的springboot项目:也要添加上面的ehcache依赖和ehcache配置 。
a.读取ehcache配置 生成EhCacheCacheManager:
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中使用ehcache:
EhcahceServiceImpl.java:
@Service
public class EhcahceServiceImpl implements EhcahceService {
private Log log = LogFactory.getLog(EhcahceServiceImpl.class);
// @Resource
// private JedisCluster cluster;
@Resource
private Jedis cluster;
private static final String CACHE_STRATEGY = "local";
@CachePut(value=CACHE_STRATEGY,key="'key_'+#info.getProduct_id()")
@Override
public ProductInfo saveProductInfo(ProductInfo info) throws Exception {
return info;
}
//@CacheEvict(value="myCache", key="'get'+#userNo")
allEntries为true表示清除value中的全部缓存,默认为false
// @CacheEvict(value="myCache", allEntries=true)
@Cacheable(value=CACHE_STRATEGY,key="'key_'+#id")
@Override
public ProductInfo getProductInfoById(Long id) throws Exception {
return null;
}}
到此我们就可以简单的使用ehcache到我们的项目中了。
ehcache被更多的作为本地的缓存机制,但是在业务复杂频频的系统中,单靠ehcache貌似有些吃力,这时我们可以加上Redis,
让Redis做为分布式缓存,ehcache做本地的缓存,形成拥有2种缓存的系统。在一个请求被路由到某台服务上时,系统先去Redis中找,Reids中有
对应的缓存就返回,没有的话再从本地的Ehcache中找,找到则返回,找不到就从数据库中查询了,查询了之后我们可以保持在Redis
和本地的Ehcache中。