Loading
0

Ehcache,Caffeine缓存

Ehcache 官网:https://www.ehcache.org/

Caffeine Github: https://github.com/ben-manes/caffeine

Maven依赖:

<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.10.1</version>
    <exclusions>
        <exclusion>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.istack</groupId>
            <artifactId>istack-commons-runtime</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.sun.xml.fastinfoset</groupId>
            <artifactId>FastInfoset</artifactId>
        </exclusion>
    </exclusions>
</dependency>

编译时发现经常报依赖找不到,干脆把上面那几项排除了,简单试了下,发现基本功能没啥影响。

Ehcache 3 API 示例:

 CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
          .withCache("preConfigured",
               CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                              ResourcePoolsBuilder.heap(100))
               .build())
          .build(true);

      Cache<Long, String> preConfigured
          = cacheManager.getCache("preConfigured", Long.class, String.class);

      Cache<Long, String> myCache = cacheManager.createCache("myCache",
          CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
                                        ResourcePoolsBuilder.heap(100)).build());

      myCache.put(1L, "da one!");
      String value = myCache.get(1L);

      cacheManager.close();
try(CacheManager cacheManager = newCacheManagerBuilder() 
  .withCache("preConfigured", newCacheConfigurationBuilder(Long.class, String.class, heap(10))) 
  .build(true)) { 

  // Same code as before [...]
}
URL myUrl = getClass().getResource("/my-config.xml"); 
Configuration xmlConfig = new XmlConfiguration(myUrl); 
CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig); 
CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
    CacheManagerBuilder.newCacheManagerBuilder() 
        .with(ClusteringServiceConfigurationBuilder.cluster(URI.create("terracotta://localhost/my-application")) 
            .autoCreateOnReconnect(c -> c)); 
PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); 

cacheManager.close(); 

参考:

最后编辑于:2022/9/16作者: joycode

评论已关闭