My linux world » Java – Cache

Java - Cache


Contents

Dependencies

If you use maven, add this to your pom.xml :

<dependencies>
(...)
  <dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>${ehcache.version}</version>
  </dependency>
  <dependency>
    <groupId>javax.cache</groupId>
    <artifactId>cache-api</artifactId>
    <version>${cacheapi.version}</version>
  </dependency>
(...)
</dependencies>

Cache

Initialize cache

// initialize cache manager :
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build();
cacheManager.init();
 
// create default cache configuration : 
long expiry = 20;
CacheConfiguration<Long, String> cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
				ResourcePoolsBuilder.heap(100))
				.withExpiry(Expirations.timeToLiveExpiration(Duration.of(expiry, TimeUnit.SECONDS))) 
				.build();
 
// create cache :
cacheManager.createCache("mycache", cacheConfiguration);

Get cache

Cache cache = cacheManager.getCache("mycache", Long.class, String.class);

Close all cache

cacheManager.close();

Cache entry

Create cache entry

// get cache:
Cache cache = cacheManager.getCache("mycache", Long.class, String.class);
 
// put value :
cache.put(2L,"value");

Read cache entry

// get cache:
Cache cache = cacheManager.getCache("mycache", Long.class, String.class);
 
// retrieve value :
String value = cache.get(2L);

Update cache entry

// get cache:
Cache cache = cacheManager.getCache("mycache", Long.class, String.class);
 
// replace value :
cache.replace(2L,"new value");

Delete cache entry

// get cache:
Cache cache = cacheManager.getCache("mycache", Long.class, String.class);
 
// delete key :
cache.remove(2L);

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub