** With Redis, your Spring Boot app can become faster and handle more traffic without breaking a sweat. This blog will show you how to set it up step-by-step.**
Cache
Cache is a temporary storage, it will represent the data in key value format, by using cache memory we can reduce the number of DB calls so the performance of the application is increased because the database calls are always costly.
Why cache ?
- Cache is a temporary storage mechanism designed to store frequently accessed data for quick retrieval.
- Data in the Cache is represented in a key-value format, allowing efficient lookups and updates.
- By leveraging cached data, the application can significantly reduce the number of database queries, thereby improving efficiency.
- Database calls are resource-intensive and time-consuming, often becoming expensive operations in terms of performance.
- Using Cache Memory enables faster access to data, which helps to enhance the overall performance and responsiveness of the application.
Redis
Redis is an open-source, in-memory data store that is super fast and used for multiple purposes like caching, storing data, and managing messages. It keeps data in memory (RAM) instead of disks, making it much quicker to retrieve. Developers use Redis to speed up applications and handle real-time tasks like messaging and streaming.
The spring-boot-starter-redis is a Spring Boot starter that simplifies integrating Redis into Spring applications. It includes all the necessary dependencies to connect, configure, and operate with Redis.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Spring Boot provides the spring-boot-starter-redis starter to easily communicate with the Redis server. It offers various components to interact with Redis efficiently
- JedisConnectionFactory: Manages and establish the connection between the Spring Boot application and the Redis server.
- RedisTemplate: It provides methods to perform operations like saving, retrieving, and deleting data in Redis.
- StringRedisTemplate: A specialized version of RedisTemplate that simplifies operations for String-based keys and values.
- OpsForValue: Supports operations on simple key-value pairs in Redis.
- OpsForHash: It is providing methods to peform operations based on Hash Data structure.
- OpsForList: Provides methods to interact with Redis Lists.
- OpsForSet: Facilitates operations on Redis Sets.
Spring Boot with Redis Integration
Spring Boot provides seamless integration with Redis, an in-memory data store, through the spring-boot-starter-redis starter. It simplifies configuration and enables developers to use Redis for caching, messaging, and data persistence.
Prerequisites for Running the Spring Boot Redis Integration Project
- Redis Server (Local or Cloud-based)
- Java Development Kit (JDK 17 or above)
- Maven (Build tool)
- IDE (e.g., IntelliJ IDEA, Eclipse, or Spring Tool Suite)
- Postman (Optional, for testing REST APIs)
- Git (To clone the repository)
- Updated application.properties with Redis server details
- Project Build using Maven
Steps to Integrate Redis with Spring Boot
- Add Maven Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
- Configure Redis Connection Add the Redis server configuration to application.properties or application.yml:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password= # Optional if Redis has no password
- create the configuration class for configure the JedisConnectionFactory or RedisTemplate.
package com.ayshriv.redis_server.config;
import com.ayshriv.redis_server.binding.Country;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class RedisConfig {
@Bean
public JedisConnectionFactory jedisConnectionFactory()
{
JedisConnectionFactory jedisConnectionFactory=new JedisConnectionFactory();
// redis server properties we write here if we are in same machine than there is no need to write properties
// jedisConnectionFactory.setHostName("localhost");
// jedisConnectionFactory.setPort(6379);
return jedisConnectionFactory;
}
@Bean
public RedisTemplate<String, Country> redisTemplate()
{
RedisTemplate<String, Country> redisTemplate=new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
}
- Here we create the country class to bind the data.
package com.ayshriv.redis_server.binding;
import lombok.Data;
import java.io.Serializable;
public class Country implements Serializable {
private Integer sno;
private String name;
private String countryCode;
public Integer getSno() {
return sno;
}
public void setSno(Integer sno) {
this.sno = sno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
}
- Create the RestController to create the endpoints.
package com.ayshriv.redis_server.rest;
import com.ayshriv.redis_server.binding.Country;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.Map;
@RestController
public class CountryRestController {
private HashOperations<String, Integer, Country> objectHashOperations =null;
public CountryRestController(RedisTemplate<String, Country> rt)
{
this.objectHashOperations = rt.opsForHash();
}
@PostMapping("/country")
public String addCountry(@RequestBody Country country)
{
objectHashOperations.put("COUNTRIES",country.getSno(), country);
return "Country added successfully";
}
@GetMapping("/countries")
public Collection<Country> getCountries()
{
Map<Integer, Country> countries = objectHashOperations.entries("COUNTRIES");
Collection<Country> values = countries.values();
return values;
}
@GetMapping("/country/{sno}")
public Country getCountry(@PathVariable("sno") Integer sno)
{
return objectHashOperations.get("COUNTRIES", sno);
}
@DeleteMapping("/country/{sno}")
public String deleteCountry(@PathVariable("sno") Integer sno)
{
objectHashOperations.delete("COUNTRIES",sno);
return "Country deleted successfully";
}
@PutMapping("/country")
public String updateCountry(@RequestBody Country country) {
objectHashOperations.put("COUNTRIES", country.getSno(), country);
return "Country updated successfully";
}
}
Run Your Spring Boot Application
Ensure your Spring Boot application with Redis is up and running on the default port 6379.
Redis should also be running on your local machine or server.
Postman Collection:
You will perform the following operations to test the endpoints:
- Add a country (POST)
- Get all countries (GET)
- Get a specific country by ID (GET)
- Update a country (PUT)
- Delete a country by ID (DELETE)
If Redis is configured correctly, these operations will persist data in Redis. You can also connect to Redis using a Redis client like redis-cli to verify the data:
HGETALL COUNTRIES
Distributed Caching
is a caching technique where the cache data is stored on a centralized cache server (e.g., Redis), which can be accessed by multiple microservices simultaneously. Instead of each microservice maintaining its own local cache, all microservices share a single, consistent cache.
Benefits of Redis Integration
- High Performance: Redis is extremely fast as it stores data in-memory.
- Easy Integration: Spring Boot's auto-configuration makes Redis integration simple.
- Supports Various Data Structures: Strings, Hashes, Lists, Sets, and more.
- Caching: Effective caching provider to speed up applications.
- Scalability: Redis works well in distributed systems for high scalability.
Conclusion
By using Redis as a centralized cache server shared across multiple microservices, you enable Distributed Caching. It enhances the system's performance, ensures consistency, and reduces latency, making it ideal for modern microservice-based architectures.
Complete Code Example on GitHub
For a fully working Spring Boot and Redis example, check out my GitHub repository here:
Top comments (0)