EHCacheImpl.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.utils.cache;

  21. import java.io.OutputStream;
  22. import java.io.Serializable;
  23. import java.time.Duration;
  24. import java.util.ArrayList;
  25. import java.util.HashSet;
  26. import java.util.List;
  27. import java.util.Set;

  28. import org.ehcache.Cache;
  29. import org.ehcache.CacheManager;
  30. import org.ehcache.config.CacheConfiguration;
  31. import org.ehcache.config.builders.CacheConfigurationBuilder;
  32. import org.ehcache.config.builders.CacheManagerBuilder;
  33. import org.ehcache.config.builders.ExpiryPolicyBuilder;
  34. import org.ehcache.config.builders.ResourcePoolsBuilder;
  35. import org.ehcache.config.units.EntryUnit;
  36. import org.ehcache.core.internal.statistics.DefaultStatisticsService;
  37. import org.ehcache.core.spi.service.StatisticsService;
  38. import org.ehcache.core.statistics.CacheStatistics;
  39. import org.openspcoop2.utils.UtilsException;

  40. /**
  41.  * EHCacheImpl
  42.  *
  43.  * @author Poli Andrea (apoli@link.it)
  44.  * @author $Author$
  45.  * @version $Rev$, $Date$
  46.  */
  47. public class EHCacheImpl extends AbstractCacheImpl {

  48.     private static CacheManager cacheManager;
  49.     private static StatisticsService statisticsService;
  50.     private static synchronized void initCacheManager() {
  51.         if(cacheManager==null) {
  52.             statisticsService = new DefaultStatisticsService();
  53.             cacheManager = CacheManagerBuilder.newCacheManagerBuilder().using(statisticsService).build();
  54.             cacheManager.init();
  55.         }
  56.     }

  57.     private Cache<String, Serializable> cache = null;
  58.     private int maxSize = -1;
  59.     private int maxLifeTime = -1; // secondi
  60.    

  61.     public EHCacheImpl(String name) throws UtilsException{
  62.         this(name, org.openspcoop2.utils.cache.Cache.DEFAULT_DISABLE_SYNCRONIZED_GET);
  63.     }
  64.     @Deprecated
  65.     private EHCacheImpl(String name, boolean disableSyncronizedGet) throws UtilsException{
  66.         super(CacheType.EH, name);
  67.         if(cacheManager==null) {
  68.             initCacheManager();
  69.         }
  70.     }
  71.    
  72.    
  73.     //  *** Inizializzazione ***
  74.    
  75.     @Override
  76.     public int getCacheSize() {
  77.         return this.maxSize;
  78.     }
  79.     @Override
  80.     public void setCacheSize(int cacheSize) {
  81.         this.maxSize = cacheSize;
  82.     }
  83.    
  84.     @Override
  85.     public CacheAlgorithm getCacheAlgoritm() {
  86.         return CacheAlgorithm.LRU;
  87.     }
  88.     @Override
  89.     public void setCacheAlgoritm(CacheAlgorithm cacheAlgoritm) {
  90.         // unsupported
  91.     }
  92.    
  93.     @Override
  94.     public long getItemIdleTime() throws UtilsException{
  95.         return -1;
  96.     }
  97.     @Override
  98.     public void setItemIdleTime(long itemIdleTimeCache) throws UtilsException{
  99.         // unsupported
  100.     }

  101.     @Override
  102.     public long getItemLifeTime() throws UtilsException{
  103.         return this.maxLifeTime;
  104.     }
  105.     @Override
  106.     public void setItemLifeTime(long itemLifeTimeCache) throws UtilsException{
  107.         this.maxLifeTime = (int) itemLifeTimeCache;
  108.     }
  109.    
  110.     @Override
  111.     public void build() throws UtilsException{
  112.         if ( this.maxSize <= 0 && this.maxLifeTime > 0 )
  113.             throw new UtilsException( "Cannot use maxLifeTime without maxSize" );
  114.        
  115.         ResourcePoolsBuilder rpb = ResourcePoolsBuilder.newResourcePoolsBuilder();
  116.         if(this.maxSize>0) {
  117.             rpb = rpb.heap(this.maxSize, EntryUnit.ENTRIES);
  118.         }
  119.        
  120.         CacheConfigurationBuilder<String,Serializable> ccb = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, Serializable.class, rpb);
  121.         if(this.maxLifeTime>0) {
  122.             ccb = ccb.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(this.maxLifeTime)));
  123.         }
  124.        
  125.         CacheConfiguration<String, Serializable> cacheConfiguration = ccb.build();
  126.         this.cache = cacheManager.createCache(this.cacheName, cacheConfiguration);
  127.     }
  128.    
  129.    
  130.    
  131.    
  132.    
  133.     //  *** Gestione ***
  134.    
  135.     @Override
  136.     public void clear() throws UtilsException{
  137.         this.cache.clear();
  138.     }
  139.    
  140.     @Override
  141.     public Object get(String key){
  142.         return this.cache.get(key);
  143.     }
  144.    
  145.     @Override
  146.     public void remove(String key) throws UtilsException{
  147.         try{
  148.             this.cache.remove(key);
  149.         }catch(Exception e){
  150.             throw new UtilsException(e.getMessage(),e);
  151.         }  
  152.     }
  153.    
  154.     @Override
  155.     public void put(String key,org.openspcoop2.utils.cache.CacheResponse value) throws UtilsException{
  156.         try{
  157.             this.cache.put(key, value);
  158.         }catch(Exception e){
  159.             throw new UtilsException(e.getMessage(),e);
  160.         }
  161.     }
  162.     @Override
  163.     public void put(String key,Serializable value) throws UtilsException{
  164.         try{
  165.             this.cache.put(key, value);
  166.         }catch(Exception e){
  167.             throw new UtilsException(e.getMessage(),e);
  168.         }
  169.     }
  170.    
  171.     @Override
  172.     public int getItemCount()  throws UtilsException {
  173.         CacheStatistics ehCacheStat = statisticsService.getCacheStatistics(this.cacheName);
  174.         return (int) ehCacheStat.getTierStatistics().get("OnHeap").getMappings();//nb element in heap tier
  175.     }
  176.    
  177.     @Override
  178.     public List<String> keys() throws UtilsException {
  179.         try{
  180.             Set<String> set = new HashSet<>();
  181.             this.cache.forEach(entry -> set.add(entry.getKey()));
  182.             List<String> keys = new ArrayList<>();
  183.             keys.addAll(set);
  184.             return keys;
  185.         }catch(Exception e){
  186.             throw new UtilsException(e.getMessage(),e);
  187.         }
  188.     }
  189.    
  190.    
  191.    

  192.    
  193.    
  194.     //  *** Info ***
  195.    
  196.     @Override
  197.     public void printStats(OutputStream out, String separator) throws UtilsException{
  198.        
  199.         try{
  200.            
  201.             StringBuilder bf = new StringBuilder();
  202.             bf.append(this._printStats(separator, true));
  203.            
  204.             CacheStatistics ehCacheStat = statisticsService.getCacheStatistics(this.cacheName);
  205.            
  206.             bf.append("PutCount:");
  207.             bf.append(ehCacheStat.getCachePuts());
  208.             bf.append(" ");
  209.            
  210.             bf.append(separator);
  211.            
  212.             bf.append("HitCount(Aux):");
  213.             bf.append(ehCacheStat.getCacheHits());
  214.             bf.append(" ");
  215.            
  216.             bf.append(separator);
  217.            
  218.             bf.append("Evictions:");
  219.             bf.append(ehCacheStat.getCacheEvictions());
  220.             bf.append(" ");
  221.            
  222.             bf.append(separator);
  223.            
  224.             bf.append("MissCount(Expired):");
  225.             bf.append(ehCacheStat.getCacheExpirations());
  226.             bf.append(" ");
  227.            
  228.             bf.append(separator);
  229.            
  230.             bf.append("MissCount(NotFound):");
  231.             bf.append(ehCacheStat.getCacheMisses());
  232.             bf.append(" ");
  233.            
  234.             out.write(bf.toString().getBytes());
  235.            
  236.         }catch(Exception e){
  237.             throw new UtilsException(e.getMessage(),e);
  238.         }
  239.     }
  240.    
  241.     /*
  242.      * Non funziona!
  243.     @Override
  244.     protected long getByteCount() {
  245.         CacheStatistics ehCacheStat = statisticsService.getCacheStatistics(this.cacheName);
  246.         return ehCacheStat.getTierStatistics().get("OnHeap").getAllocatedByteSize();
  247.     }
  248.     */
  249. }