http://www.ehcache.org/documentation/3.7/107.html
jsr107是java定义的缓存规范,各个缓存框架都写了适配器对接上其定义的规范。如同数据库DB规范
导入包
<dependency>
<groupId>javax.cache</groupId>
<artifactId>cache-api</artifactId>
<version>1.0.0</version>
</dependency>
javax.cache 本身是没有对缓存的实现。 其会自动去找类路径下实现了该规范的jar,然后使用其中的方法。
以下是示例代码,如我们类路径下有ehcache的包实现了jcache规范,Caching.getCachingProvider() 会检索到该包并使用。
package a.caixl.cache;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;
public class JSR107Demo {
public static void main(String[] args) {
CachingProvider provider = Caching.getCachingProvider();
CacheManager cacheManager = provider.getCacheManager();
MutableConfiguration<Long, String> configuration =
new MutableConfiguration<Long, String>()
.setTypes(Long.class, String.class)
.setStoreByValue(false)
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.ONE_MINUTE));
Cache<Long, String> cache = cacheManager.createCache("jCache", configuration);
cache.put(1L, "one");
String value = cache.get(1L);
System.out.println(value);
}
}