Spring Boot Caching with Redis

Caching is a common technique used to improve application performance by reducing the need for repeated database calls. Here’s how caching helps:

  1. Reduced Database Load: By caching frequently accessed data, you can reduce the number of database queries, which can alleviate the load on the database server. This can lead to better overall performance, especially during periods of high traffic.
  2. Faster Response Times: Cached data can be served more quickly than fetching data from the database, especially if the database is located remotely or if complex queries are involved. This can result in faster response times for end-users, leading to a better user experience.
  3. Scalability: Caching can improve the scalability of your application by reducing the load on the database server. With fewer database queries, your application can handle more concurrent users without experiencing performance degradation.
  4. Improved Availability: In some cases, caching can help improve the availability of your application by reducing the dependency on the database. If the database becomes temporarily unavailable, cached data can still be served to users, providing a fallback option.
  5. Cost Savings: By reducing the load on the database server, caching can potentially lower infrastructure costs, as you may require fewer database resources to handle the same level of traffic.

In this article we are going to implement redis in Spring boot

Please add the maven dependancy for redis in your application for Redis

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

For enable of caching use annotation @EnableCaching in your application

In this article we made api level caching simillarly we can use it in method level

@GetMapping("/product/{id}")  
	@Cacheable(value = "product", key = "#id")
	public Product getProductById(@PathVariable long id) throws Exception {
		  return repository.findById(id).orElseThrow(() -> new Exception("Product Not found"));
		  
	}
	
	@PutMapping("/product/{id}")
	@CachePut(cacheNames = "product", key = "#id")
	public Product editProduct(@PathVariable long id, @RequestBody Product product) throws Exception {
		repository.findById(id).orElseThrow(() -> new Exception("Product Not found"));
		return repository.save(product);
	}
	
	
	@DeleteMapping("/product/{id}")
	@CacheEvict(cacheNames = "product", key = "#id", beforeInvocation = true)
	public String removeProductById(@PathVariable long id) throws Exception {
		Product product = repository.findById(id).orElseThrow(() -> new Exception("Product Not found"));
		repository.delete(product);
		return  "Deleted Successfully";
	}
please find the detailed example of all caching in github

Leave a Reply

Your email address will not be published.

Back To Top