You can introduce caching to your Java application quite easily with Ehcache, either using its new, powerful API or using the javax.cache API as defined in the JSR-107 specification.
pom.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.what21.demo
ehcache
0.0.1-SNAPSHOT
jar
ehcache
http://maven.apache.org
UTF-8
org.ehcache
ehcache
3.6.1
javax.cache
cache-api
1.1.0
junit
junit
3.8.1
test
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
1.8
Java代码:package com.what21.demo.ehcache;
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 App {
/**
* @param args
*/
public static void main(String[] args) {
// CacheManager是Ehcache框架的核心类和入口,负责管理一个或多个Cache对象
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("preConfigured", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build())
.build(true);
// 获取preConfigured缓存
Cache preConfigured = cacheManager.getCache("preConfigured", Long.class, String.class);
System.out.println(preConfigured);
// 创建myCache缓存
Cache myCache = cacheManager.createCache("myCache", CacheConfigurationBuilder
.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)).build());
// 缓存内容
myCache.put(1L, "www.what21.com,ehcache测试");
String value = myCache.get(1L);
System.out.println("value = " + value);
// 关闭CacheManager
cacheManager.close();
}
}