Tuesday, December 5, 2017

Caching

CACHE
  • GUAVA CACHE


CacheBuilder.newBuilder()
.maximumSize(100)
.expireAfterAccess(30, TimeUnit.MINUTES).build(new CacheLoader(),personid)

  • EHCACHE
  • LRU
  • SPRING CACHE

Question 1: What is Ecache?

Ehcache is an open source, standards-based cache that 
boosts performance 
offloads your database,
*    and simplifies scalability.
It's the most widely-used Java-based cache because it's robust, proven, full-featured, and integrates with other popular libraries and frameworks.

What is cachestore ?

CacheStore is a key-value hybrid storage system between memory cache and disk. It is high performance, horizontally scalable, and high availability. It was developed to support real time auction and high performance ad serving systems.

Maven dependencies
    net.sf.ehcache
    ehcache
    2.10.1



//Create a cache manager
                  CacheManager cm = CacheManager.getInstance();

//Create a cache called "cacheStore"
                  //cm.addCache("cacheStore");

//Get a cache called "cacheStore"
                  Cache cache = cm.getCache("cacheStore");

//Add few elements in to cache
                  UserDetails details = new UserDetails("001","First Name","Last Name");
                  cache.put(new Element("1", details));
                  cache.put(new Element("2", "Two"));
                  cache.put(new Element("3", "Three"));

                  //Get the element from cache
                  Element ele = cache.get("1");
                  UserDetails u = (UserDetails)ele.getObjectValue();
                  System.out.println(u.getUserId());

                  //Whether key is in the cache?
                  System.out.println(cache.isKeyInCache("1"));
                  System.out.println(cache.isKeyInCache("5"));

                  //Call shutdown to close the cache manager
                  cm.shutdown();





updateCheck="true" monitoring="autodetect" dynamicConfig="true">

        
        
        
        
        

        
        
                     maxEntriesLocalHeap="10000"
                     maxEntriesLocalDisk="1000"
                     eternal="false"
                    diskSpoolBufferSizeMB="20"
                    timeToIdleSeconds="300"
                    timeToLiveSeconds="600"
                    memoryStoreEvictionPolicy="LFU"
                    transactionalMode="off">
                       
        


S.No


1
defaultCache




2
maxElementsInMemory
The attribute tells the Ehcache that how many caches would be stored in the memory. If the total caches reached the limit, then the caches will be pushed to the disk if the configurations set as overflowToDisk=true. If this attribute set as false, old caches will be evicted and new caches will be replace the old one.



3
eternal
If this attribute is set as true, then other attributes timeToIdleSecondsand timeToLiveSeconds need not be configured. If you configure these attributes, then the configure values will not be considered. The default value of 0 will be taken for both the attributes. Note that, the configuration eternal=true implies that caching configuration should not consider the timeToIdleSeconds and timeToLiveSeconds. It means that the caches will not be expired for ever in the store. It has to be cleared manually by the server administrator by restarting the server. Be careful on using this attribute



4
overflowToDisk
This attribute sets whether cache elements can overflow to disk when the memory store has reached the maxElementsInMemory limit. If the attribute set to false, cache elements will not overflow to disk when store has reached the maxElementsInMemory limit.



5
timeToIdleSeconds
This attribute sets the idle time before it expires. For example, if you set this attribute as 10, the caches that are not accessed for 10 seconds will be automatically expired. The default value for this attribute is 0. If the value is 0, this attribute will not be considered for the expiration. timeToIdleSeconds is valid only when eternal attribute value is false



6
timeToLiveSeconds
This attribute sets the total expiry time for the cache. It is the time between creating time and expiration time. The default value for this attribute is 0. If the value is 0, this attribute will not be considered for the expiration. timeToLiveSeconds is valid only when eternal attribute value is false.



7
maxElementsOnDisk




8
maxEntriesLocalDisk vs maxElementsOnDisk




9
Exceptions




10

http://javabeat.net/ehcache/





1.     JDK java.util.concurrent.ConcurrentMap based caches
2.     EhCache
3.     Gemfire Cache
4.     Guava Caches
5.    JSR 107 complaint caches



CACHING
1.     Read Only: This caching strategy should be used for persistent objects that will always read but never updated. It’s good for reading and caching application configuration and other static data that are never updated. This is the simplest strategy with best performance because there is no overload to check if the object is updated in database or not.
2.     Read Write: It’s good for persistent objects that can be updated by the hibernate application. However if the data is updated either through backend or other applications, then there is no way hibernate will know about it and data might be stale. So while using this strategy, make sure you are using Hibernate API for updating the data.
3.     Nonrestricted Read Write: If the application only occasionally needs to update data and strict transaction isolation is not required, a nonstrict-read-write cache might be appropriate.
4.     Transactional: The transactional cache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache can only be used in a JTA environment and you must specify hibernate.transaction.manager_lookup_class.

Hibernate.cfg.xml
Some important points about hibernate second level cache configurations are:
1.     hibernate.cache.region.factory_class is used to define the Factory class for Second level caching, I am using org.hibernate.cache.ehcache.EhCacheRegionFactory for this. If you want the factory class to be singleton, you should use org.hibernate.cache.ehcache.SingletonEhCacheRegionFactoryclass.
If you are using Hibernate 3, corresponding classes will be net.sf.ehcache.hibernate.EhCacheRegionFactory and net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory.
2.     hibernate.cache.use_second_level_cache is used to enable the second level cache.
3.     hibernate.cache.use_query_cache is used to enable the query cache, without it HQL queries results will not be cached.
4.     net.sf.ehcache.configurationResourceName is used to define the EHCache configuration file location, it’s an optional parameter and if it’s not present EHCache will try to locate ehcache.xml file in the application classpath.








































What is Spring Cache?
@Cacheable

@Cacheable annotation is one of the most important and common annotation for caching the requests. If you annotate a method with @Cacheable, if multiple requests are received by the application, then this annotation will not execute the method multiple times, instead it will send the result from the cached storage.

Here is an example:

@Cacheable(value="users", condition="#name.length < 32", unless="#result.hardback")
            public UserDetails findById(String id) {
                        slowResponsee();
                        return new UserDetails(id, "Name"+id);
            }

@CachePut

@CachePut annotation helps for updating the cache with the latest execution without stopping the method execution. The only difference between @Cacheable and @CachePut is that first one is only once executed for the combination of similar key and updated the cache storage and later is executed every time and updates the cache storage.

It is not recommended to use both the annotation for the same method which will result in an unexpected results. It is highly recommended to use either @Cacheable or @CachePut for a method.

The list of attributes defined in this annotation is similar to the @Cacheable.

@CacheEvict

@CacheEvict annotation is used for removing a single cache or clearing the entire cache from the cache storage. This annotation supports suitable parameters to execute the condition to clear the matching set of cached from the store. If you set the allEntries=true , then the entire cache will be cleared.

@Caching

@Caching annotation used for grouping multiple annotations of the same type together when one annotation is not sufficient for the specifying the suitable condition. For example, you can put mutiple @CacheEvict ot @CachePut annotation inside @Caching to narrow down your conditions as you need.







No comments:

Post a Comment