Springboot Cache

 

An application without cache is typically slow. Even great code will crawl when handling heavy traffic without cache. Caching can be a fast and relatively cheap way to increase performance.

Caching is a performance boost strategy you must implement into your application. Caching is nothing more than a hash table.

For Redis, all Redis data resides in-memory, in contrast to databases that store data on disk or SSDs. By eliminating the need to access disks, in-memory data stores such as Redis avoid seek time delays and can access data in microseconds. Redis features versatile data structures, high availability, geospatial, Lua scripting, transactions, on-disk persistence, and cluster support making it simpler to build real-time internet-scale apps.

I am going to show you how to implement caching into your Spring Boot application.

1. Include the following dependencies in your pom file.

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

In your application.properties file, set Redis configurations. Also set spring.cache.type=redis.

2. Create a configuration class

@Configuration
@EnableCaching
public class CachingConfig{
	
	
    @Bean("customKeyGenerator")
    public KeyGenerator keyGenerator() {
        return new CustomKeyGenerator();
    }
	
private class CustomKeyGenerator implements KeyGenerator {
		  
	    public Object generate(Object target, Method method, Object... params) {
	    	StringBuilder strParams = new StringBuilder(target.getClass().getSimpleName());
	    	strParams.append("_");
			strParams.append(method.getName());
	    	for(Object param: params) {
				strParams.append("_");
				strParams.append(param);
			}
	    	System.out.println("key="+strParams.toString());
	        return strParams.toString();
	    }
}

}

3. Use @Cacheable to retrieve data

@Cacheable(value="users", key = "#id")
public User getById(Long id) {
	// retrieve User from db
	...
	return user;
}

4. Use @CachePut to update cached data

@CachePut(value="users", key = "#user.id")
public User update(User user) {
        ....
	return user;
}

5. Use @CacheEvict to delete cached data

@CacheEvict(value="users", key = "#id")
public Boolean delete(Long id) {
	....
	return true;
}



Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *