CodeX
Published in

CodeX

Spring Boot & Redis

In this article, we will talk about Redis and how to connect to it via a Spring Boot application.

What is Redis?

Millions of developers use Redis as an open-source in-memory data store, database, cache, streaming engine, and message broker. Redis is frequently referred to as a data structure server. In other words, it means that Redis offers basic commands that can be used as a server-client approach by TCP sockets to access and modify data structures. As a result, many processes can share access to the same data structures and change them when required.

There are different known use cases for Redis, and you can find some of them here with a simple description:

Real-time datastore

Having a huge amount of data that needs to be stored and processed in real-time is becoming an everyday challenge for businesses. In general, a real-time database is a data store created to gather, process, and/or enrich an incoming sequence of data points, just like data streams, in real-time, usually right away after the data is created. Using Redis, you can create a data infrastructure for real-time applications that require low latency and high throughput.

Caching and session storage

Another common issue for applications that rely on a high-latency system is the need to cache and deliver data quickly. Redis is the best option for caching database queries, complicated calculations, API requests, and session states because of its speed.

Streaming and messaging

Streaming the data around the organization and making it available for different components in the system has always been challenging. Redis’s stream data type enables messaging, event sources, notifications, and high-speed data ingestion.

The use cases for Redis are more than the examples that we have mentioned, but in this article, we are focused on the real-time data store use case, and the following example using Spring Boot will show how to use it.

Getting Start

In this simple example, you will learn how to establish a connection to a Redis server and perform some fundamental tasks, such as inputting data and reading it from Redis. Installing Redis is pretty straightforward you can find the installation guide here.

Redis-related libraries are part of the Spring Data Package, which makes it easy to use data access technologies, relational and non-relational databases, map-reduce frameworks, and cloud-based data services. You have two approaches to dealing with related dependencies. You can use the spring-boot-starter-data-redis which will have all the necessary dependencies prepared.

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

The other alternative is to use spring-data-redis and then you will have the flexibility to choose the underlying connector driver implementation.

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

Now you can select the preferred connector driver as a different dependency, as follows: Currently, two options are available for the underlying library used by Spring Data Redis.

Jedis is a Java client for Redis designed for performance and ease of use, which is also used in spring-boot-starter-data-redis. It helps you create a connection pool and use it to communicate with Redis.

<dependency>     
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>

Lettuce is a scalable, thread-safe Redis client for synchronous, asynchronous, and reactive usage.

<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>

Currently, not all connectors support all Redis features. When invoking a method on the Connection API that is unsupported by the underlying library, an UnsupportedOperationException is thrown. The following overview explains features that are supported by the individual Redis connectors:

By default, using the Spring Boot starter will add the Jedis dependencies as well. Connecting to the Redis store through the IoC container is one of the initial tasks when utilizing Redis and Spring. This needed to be accomplished using a Java connector, regardless of the library you have.

The RedisConnection and RedisConnectionFactory interfaces from org.springframework.data.redis.connection package can be used to retrieve active connections to Redis.

RedisConnection, which manages communication with the Redis back end, offers the fundamental building block for Redis communication, and automatically converts the underlying connecting library exceptions to Spring’s reliable DAO exception hierarchy.

In order to create RedisConnection you can use the RedisConnectionFactory. The RedisConnectionFactory can be used most simply by configuring the proper connection through the IoC container and injecting it into the target class.

If you have a simple standalone instance of Redis running, you can use RedisStandaloneConfiguration to prepare the JedisConnectionFactory by simply passing the IP address or hostname of the server and the port number in the constructor.

@Configuration
public class RedisConfiguration {

@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration("192.168.0.80", 6379);
return new JedisConnectionFactory(redisConfiguration);
}

}

RedisTemplate and its container package, org.springframework.data.redis.core, are used by the majority of users. It is a high-level abstraction for Redis interactions and handles serialization and connection management.

@Configuration
public class RedisConfiguration {

@Bean
public JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration redisConfiguration = new RedisStandaloneConfiguration("192.168.0.80", 6379);
return new JedisConnectionFactory(redisConfiguration);
}

@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
return template;
}

}

Having the JedisConnectionFactory and RedisTemplate set up and ready, you can start to work with data in Redis. But there is even a simple way to work with Redis if you are familiar with repositories. Utilizing Repositories lets you seamlessly read and manipulate domain objects in Redis Hashes.

Just like the following example, you can simply implement domain entities Using Spring Data Redis.

@RedisHash("Student")
public class Student implements Serializable {
private String id;
private String name;
private Integer age;
}

Now that we have a component responsible for storage and retrieval, we can create our repository by extending CrudRepository interface.

public interface StudentRepository extends CrudRepository<Student, String> {
}

CrudRepository will provide basic CRUD operations to work with like the following examples:

  • save(Student student);
  • findById(String id);
  • count();
  • delete(Student student);

It is time to create your service class, inject the repository and start working with Redis just like the following sample code:

@Service
public class StudentService {

@Autowired
StudentRepository studentRepository;

public Student addStudent(Student student){
return studentRepository.save(student);
}

public List<Student> getStudents(){
List<Student> list = new ArrayList<Student>();
studentRepository.findAll().forEach( i -> {
list.add(i);
});
return list;
}

}

Using the model object you can simply insert records to Hash and read them as expected.

Of course, there are a lot of details involved in the process of reading and retrieving data from Redis but this example can give you a basic understanding of how the whole libraries work.

I hope this article helped you, and please support me by applauding 👏 for the story. If you don’t know how it works, it's just like this:

Or buy me a coffee here!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store