Cache And It's Implementation !!!!

Cache And It's Implementation !!!!

·

6 min read

Let us explore the building blocks of Cache and other caching types, as well as multiple strategies for implementing temporary data storage in your application.

The contents of the Article include:

  1. What is Caching?

  2. Why should we use Cache?

  3. Different types of Cache

  4. Examples of Cache.

  5. Applying Cache in Java Spring using Annotations.

What is Caching?

The definition of caching can be said to be storage for temporary data in RAM. It lies between the Application and the persistence database. It stores the recently used data which reduces hitting the database multiple times. We can also say, caching is used to store data for future reference.

Why should we use Cache?

  • The primary reason for using cache is to make data access faster and less expensive.

  • When the highly requested resource is requested multiple times, it is often beneficial for the developer to cache resources so that it can give responses quickly.

  • Using cache in an application enhances the performance of the application.

  • Data access from memory is always faster in comparison to fetching data from the database.

  • Also, it reduces both monetary costs and opportunity costs.

  • Caching helps for better resources that you already have.

Different types of Cache

There are mainly 4 types of Caching.

  1. CDN - Content Delivery Network Caching

  2. Database Caching

  3. In-Memory Caching

  4. Web server Caching

CDN - Content Delivery Network Caching

  • CDN is known as the most popular cache because it improves the delivery of the content by replicating commonly requested files (such as HTML Pages, stylesheets, JavaScript, images, videos, etc.) across a globally distributed set of caching servers.

  • It delivers a local copy of the content from a nearby cache edge (a cache server that is closer to the end-user), or a Point of Presence (PoP).

Database Caching

  • Database caching is a mechanism that generates web pages on-demand (dynamically) by fetching the data from the database.

  • It is used in a multi-tier environment that involved clients, a web application server, and a database.

  • It improves scalability and performance by distributing a query workload. It is mainly used in ORM frameworks.

In-Memory Caching

  • An in-memory cache is a data storage layer that sits between applications and databases to deliver responses with high speeds by storing data from earlier requests or copying directly from databases.

  • In-memory Cache provides query functionality on top of caching.

Web-Server Cache

  • Web server caching is a mechanism that stores data for reuse, such as a copy of a web page served by a web server.

  • It is cached or stored the first time a user visits the page and when the next time a user requests the same page, the content will be delivered from the cache, which helps keep the origin server from getting overloaded.

Examples of Cache

  1. Redis Cache

  2. Hazelcast Cache

  3. Memcached Cache

  4. Oracle Coherence Cache

  5. Infinispan Cache

  6. Ehcache Cache

  7. Apache Ignite Cache

  8. GridGain Cache

  9. GemFire Cache

Apply cache in Java Spring using Annotations:

Step 1: If we want to enable any caching mechanism in a Spring Boot application, we need to add cache dependency in the pom.xml file. It enables caching and configuring a CacheManager into the application.

<dependency>  
     <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-cache</artifactId>  
</dependency>

Step 2: In the Spring main java file, add the @EnableCaching annotation

@SpringBootApplication  
@EnableCaching   
public class SpringBootCachingDemo {  
public static void main(String[] args)   {  
    SpringApplication.run(SpringBootCachingApplication.class, args);  
    }  
}

Step 3: Then add the @CacheConfig class-level annotation to tell the Spring where to store the cache for the class.

When we annotate a class with this annotation, it provides default settings for any cache operation defined in that class and we need not declare things multiple times.

  •       @CacheConfig(cacheNames={"employee"})   
          public class UserService {  
              //Code   
          }
    

Step 4: Adding the @Caching annotation

This annotation is used when we need the annotations @CachePut or @CacheEvict at the same time on the same method. Otherwise, it is used when we want to use multiple annotations of the same type.

But Java does not allow multiple annotations of the same type to be declared for a given method. To avoid this problem, we use @Caching annotation.

@Caching(evict = {@CacheEvict("phone_number"), @CacheEvict(value="directory", key="#student.id") })  
public String getAddress(Student student)   
{  
    // code  
}

@CacheEvict:

  • It is a method-level annotation. It is used when we want to remove unused data from the cache. It requires one or multiple caches that are affected by the action.

  • We can also specify a condition for it.

  • If we want wide cache eviction, the @CacheEvict annotation provides a parameter called allEntries. It evicts all entries rather than one entry based on the key.

  • Also, note that @CacheEvict annotation is that it can be used with void methods because the method acts as a trigger.

  • It avoids return values. On the other hand, the annotation @Cacheable requires a return value that adds/updates data in the cache.

@CacheEvict(allEntries=true) - Evict the whole cache:
@CacheEvict(key="#student.stud_name") - Evict an entry by key:

Example:

@CacheEvict(value="student_data", allEntries=true) //removing all entries from the cache  
public String getNames(Student student){  
    // code  
}

@CachePut:

  • It is a method-level annotation.

  • It is used when we want to update the cache without interfering with the method execution. It means the method will always execute, and its result will be placed into the cache. It supports the attributes of @Cacheable annotation.

  • Remember @Cacheable and @CachePut are not the same because they have different behavior.

  • The difference between @Cacheable and @CachePut annotations is that the @Cacheable annotation skips the method execution while the @CachePut annotation runs the method and put the result into the cache.

      @CachePut(cacheNames="employee", key="#id") //updating cache  
      public Employee updateEmp(ID id, EmployeeData data) {  
            // code  
      }
    

    Step 5: Using method-level @Cacheable annotation. It defines a cache for a method's return value.

  • The @Cacheable annotation contains more options. For example, we can provide a cache name by using the value or cacheNames attribute.

  • We can also specify the key attribute of the annotation that uniquely identifies each entry in the cache.

  • If we do not specify the key, Spring uses the default mechanism to create the key.

      Example 1:
    
      @Cacheable(value="cacheStudentInfo", key="#id")  
      public List studentInfo() {  
          // code   
          return studentDetails;  
      }
    
      Example 2:
    
      @Cacheable(value="student", condition="#name.length<20")  
      public Student findStudent(String name)  {  
          //some code  
      }
    

Here comes the end of basics of Cache, I have covered the basics concepts to know before working on Cache.

Thank you for reading the article. Please like, share and comment. it will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!!!