您当前的位置: 首页 > 

_waylau

暂无认证

  • 1浏览

    0关注

    275博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Ehcache 2升级到Ehcache 3的改动点

_waylau 发布时间:2022-03-03 19:29:19 ,浏览量:1

本文总结了Ehcache 2升级到Ehcache 3的改动点。

Ehcache 2升级到Ehcache 3的改动点 1. 包名更改

Ehcache 2包名如下:

import net.sf.ehcache.Cache;

Ehcache 3包名如下:

import org.ehcache.Cache;
2. 配置文件

Ehcache 2配置文件如下:



    

    
        
    


Ehcache 3配置文件如下:


    
        java.lang.Long
        java.lang.String
        200
    


Ehcache 2 初始化配置方式如下:


```java
try (InputStream fis = this.getClass().getResourceAsStream("/config/ehcache.xml")) {
    manager = new CacheManager(fis);
}

Ehcache 3初始化配置方式如下:

final URL myUrl = getClass().getResource("/configs/ ehcache.xml ");

XmlConfiguration xmlConfig = new XmlConfiguration(myUrl);

CacheManager myCacheManager = CacheManagerBuilder.newCacheManager(xmlConfig);
3. CacheManager类

Ehcache 2的CacheManager有addCacheIfAbsent方法。

public Cache getCacheAddIfAbsent(String cacheName) {

    Cache cache = manager.getCache(cacheName);

    if (cache == null) {
        synchronized (EhcacheManager.class) {
            manager.addCacheIfAbsent(cacheName);
            cache = manager.getCache(cacheName);
        }
    }

    return cache;

}

Ehcache 3的CacheManager没有addCacheIfAbsent方法,需自己实现。

private CacheManager manager;

public Cache getCacheAddIfAbsent(String cacheName) {

    Cache cache = manager.getCache(cacheName, String.class, Object.class);

    if (cache == null) {
        try {
            cache = manager.createCache(cacheName, configurationBuilder);
        } catch (IllegalArgumentException e) {
            //cache already exists
            LOGGER.info("cache {} already exists", cacheName);
            cache = manager.getCache(cacheName, String.class, Object.class);
        }
    }

    return cache;

}
4. 没有了Element的概念

Ehcache 3已经没有了net.sf.ehcache.Element的概念。

Ehcache 2从缓存获取值的方式如下:

Cache cache = ……;

Element element = cache.get("key1");

Serializable value = element.getValue();

Ehcache 3从缓存获取值的方式如下:

Cache myCache = ……;

String value = myCache.get("key1");

Ehcache 3没有了Element这个中间对象,用法上更加简洁。

参考引用
  • 原本同步至:https://waylau.com/differences-between-ehcache-2-and-ehcache-3/
  • 该版本在高并发下bug:https://github.com/ehcache/ehcache3/issues/2787
关注
打赏
1651845987
查看更多评论
立即登录/注册

微信扫码登录

0.0412s