版本 4

    要求:

    • JDK 版本与Sun Java 6 或者更高版本兼容。
    • 一个Java集成开发环境。
    • 确保你已经下载了 Infinispan, 并且添加了 Infinispan的所有 jar包到项目的 classpath下.
      • 如果在项目中你使用了 Maven , 你可以在你的 pom.xml 文件中添加对Infinispan的依赖。关于如何添加依赖的更多细节请点击 链接

    注意: 下面的例子使用的是Infinispan 4.1.x.  如果你是用的是 Infinispan 4.0.x请将类EmbeddedCacheManager 替换成CacheManager。

    步骤 1: 创建 cache manager
    EmbeddedCacheManager manager = new DefaultCacheManager();
    


     

    如果你要创建支持集群的缓存,使用:

    EmbeddedCacheManager manager = new DefaultCacheManager(
                    GlobalConfiguration.getClusteredDefault() );
    


     

    或者, 你想要创建自定义的 GlobalConfiguration实例并将其传入构造方法:

    GlobalConfiguration myGlobalConfig = new GlobalConfiguration();
    // 配置对应的myGlobalConfig 
    EmbeddedCacheManager manager = new DefaultCacheManager(myGlobalConfig);
    


    步骤 2: 创建一个cache

    获取默认的缓存实例:

    Cache cache = manager.getCache();


     

    为了获取自定义的缓存实例, 你需要在manager上对其进行注册:

    Configuration config = new Configuration();
    // 配置你的config bean 
    manager.defineConfiguration("myCustomCache", config);
    Cache customCache = manager.getCache("myCustomCache");
    
    
    
    
    步骤 3: 使用 cache

     

    cache.put("key", "value");
    assert cache.size() == 1;
    assert cache.containsKey("key");
    Object v = cache.remove("key");
    assert v.equals("value");
    assert cache.isEmpty();
    
    
    
    
    
    
    
    
    // 记住Cache 继承了ConcurrentMap!
    
    
    
    
    
    
    
    cache.put("key", "value");
    
    
    
    cache.putIfAbsent("key", "newValue");
    
    
    
    assert "value".equals(cache.get("key"));
    
    
    
    
    
    
    
    cache.clear();
    
    
    
    assert cache.isEmpty();
    
    
    
    
    
    
    
    
    
    
    步骤 4: 设置数据项的过期


    默认情况下数据项是永不过期的,但是你能够通过设置一个基本的键值和生命周期来重写该属性。

     

    cache.put("key", "value", 60, TimeUnit.SECONDS);
    assert cache.containsKey("key");
    Thread.sleep(60000);
    assert ! cache.containsKey("key");