Ehcache简介
一、简介
Ehcache是一种开源的、基于标准的缓存,它可以提高性能、减轻数据库负载并简化可扩展性。它是一种广泛使用的基于Java的开源缓存,具有内存和磁盘存储、监听器、缓存加载程序(loaders)、RESTful和SOAP API以及其他非常有用的特性。
二、安装
下载ehcache-3.4.0.jar
和slf4j-api-1.7.7.jar
或使用Maven配置依赖:
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.4.0</version>
</dependency>
三、Hello World
1、程序化配置
//定义别名为preConfigured的Cache
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class,
String.class, ResourcePoolsBuilder.heap(10)))
.build();
//初始化cacheManager,或者在上面使用build(true)
cacheManager.init();
//获取preConfigured缓存
Cache<Long, String> preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class);
//创建一个新的Cache
Cache<Long, String> myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10)));
//缓存数据
myCache.put(1L, "da one!");
//从缓存中获取数据
String value = myCache.get(1L);
System.out.println(value);
//删除Cache的引用
cacheManager.removeCache("preConfigured");
//释放资源
cacheManager.close();
2、XML配置
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns='http://www.ehcache.org/v3'
xsi:schemaLocation="http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core.xsd">
<!-- cache的别名为 foo -->
<cache alias="foo">
<!-- 键和值的类型,如果未指定则为Object -->
<key-type>java.lang.String</key-type>
<value-type>java.lang.String</value-type>
<resources>
<!-- 在堆上可以容纳2000个条目 -->
<heap unit="entries">2000</heap>
<!-- 500MB的堆外内存 -->
<offheap unit="MB">500</offheap>
</resources>
</cache>
<!-- 模板 -->
<cache-template name="myDefaults">
<key-type>java.lang.Long</key-type>
<value-type>java.lang.String</value-type>
<heap unit="entries">200</heap>
</cache-template>
<!-- 使用了myDefaults模板的Cache -->
<cache alias="bar" uses-template="myDefaults">
<key-type>java.lang.Number</key-type>
</cache>
<cache alias="simpleCache" uses-template="myDefaults" />
</config>
使用XML时CacheManager的创建方法如下:
URL myUrl = App.class.getResource("/my-config.xml");
XmlConfiguration xmlConfig = new XmlConfiguration(myUrl);
CacheManager cacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
四、样例
创建一个简单的方法来计算所提供数字的平方值,在每次调用时,该方法将调用calculateSquareOfNumber(int number)
方法并将信息消息打印到控制台。
通过使用缓存,实现数字平方值只计算一次,并且每个具有相同输入值的其他调用都从缓存返回结果。
以下代码部分省略:
import org.ehcache.Cache;
import org.ehcache.CacheManager;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.CacheManagerBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
public class CacheHelper {
private CacheManager cacheManager;
private Cache<Integer, Integer> squareNumberCache;
private final String CACHEKEY = "squaredNumber";
public CacheHelper() {
//创建并初始化cacheManager
cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
CacheConfigurationBuilder<Integer, Integer> configBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, Integer.class, ResourcePoolsBuilder.heap(10));
squareNumberCache = cacheManager.createCache(CACHEKEY, configBuilder);
}
public Cache<Integer, Integer> getSquareNumberCache(){
//获取缓存
return squareNumberCache;
}
}
public class SquaredCalculator {
private CacheHelper cacheHelper;
public SquaredCalculator() {
cacheHelper = new CacheHelper();
}
public int getSquareValueOfNumber(int input){
Cache<Integer, Integer> squareNumberCache = cacheHelper.getSquareNumberCache();
if(squareNumberCache.containsKey(input)){
return squareNumberCache.get(input);
}
System.out.println(String.format("Calculating square value of %s and caching result.", input));
int squaredValue = (int) Math.pow(input, 2);
squareNumberCache.put(input, squaredValue);
return squaredValue;
}
public boolean hasCachedSquareValue(int input){
return cacheHelper.getSquareNumberCache().containsKey(input);
}
}
测试类:
SquaredCalculator calculator = new SquaredCalculator();
for(int i = 2; i < 6; i++){
assertFalse(calculator.hasCachedSquareValue(i));
System.out.println(String.format("Square value of %s is: %s", i, calculator.getSquareValueOfNumber(i)));
}
System.out.println();
for(int i = 2; i < 6; i++){
assertTrue(calculator.hasCachedSquareValue(i));
System.out.println(String.format("Square value of %s is: %s", i, calculator.getSquareValueOfNumber(i)));
}
输出:
Calculating square value of 2 and caching result.
Square value of 2 is: 4
Calculating square value of 3 and caching result.
Square value of 3 is: 9
Calculating square value of 4 and caching result.
Square value of 4 is: 16
Calculating square value of 5 and caching result.
Square value of 5 is: 25
Square value of 2 is: 4
Square value of 3 is: 9
Square value of 4 is: 16
Square value of 5 is: 25