Ehcache migration from net.sf.ehcache 2.10.9.2 to org.ehcache 3.10.8

1.6k views Asked by At

I am trying to upgrade Ehcache for my Project from net.sf.ehcache 2.10.9.2 to org.ehcache 3.10.8 version.

Any replacement for net.sf.ehcache.Element and CacheExceptionHandler.

Less documentation on Ehcache 3, Can anyone give some tips for upgrading Ehacahe to version 3.

as both of the Ehcache are different GroupId are there any proper Documentation for Migration

net.sf.ehcache 2.x maven Dependency is like Below

<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.9.2</version>
</dependency>

while org.echcache 3.x maven Dependency is like Below

<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.10.8</version>
</dependency>

configuration part is given in net.sf.echcache 2.x

CacheManager cm = CacheManager.getInstance();

Cache cache = cm.getCache("AccessTokenCache");

CacheConfiguration config = cache.getCacheConfiguration();

cache.put(new Element(TOKEN_CACHE_KEY, accessToken));

congif.setTimeToLiveSeconds(AccessTokenResponse.getExpire() - 120);

but as above code could could not find any similar compatible code for org.ehcache 3.x kindly let me how to do that

1

There are 1 answers

1
Suman On
  1. Add Ehcache dependency

     <dependency>
         <groupId>org.ehcache</groupId>
         <artifactId>ehcache</artifactId>
         <version>3.10.8</version>
     </dependency>
    
  2. Add Ehcache.xml in resource folder to configure cache details. Below is the snippet of Ehcache.xml

Ehccache.xml

<config>
    <cache alias="AccessTokenCache"> <key-type>java.lang.String</key-type>
        <value-type>org.springframework.http.HttpHeaders</value-type>
        <expiry>
            <ttl unit="seconds">3000</ttl>
        </expiry>
        <resources>
            <heap unit="entries">20</heap>
            <offheap unit="MB">1</offheap>
        </resources>
    </cache>
</config>
  1. Use @Cacheable in method level
@Cacheable(cacheNames = "AccessTokenCache",key = "#root.methodName")    
Token getToken();
  1. Add @EnableCaching in main class
@SpringBootApplication    
@EnableCaching   
public class SampleApplication {    

}