Wednesday, March 16, 2022

Spring Boot + Redis Example in Java

Hello guys, if you are wondering how to use Redis with Spring Boot in Java then you have come to the right place. Earlier, I have shared the Spring Boot + React example, Spring Boot + Angular example, and Spring Boot + MyBatis examples In this tutorial, we will review the basics of how to use Redis with Spring Boot. We will build an application that demonstrates how to perform CRUD operations Redis through a web interface. So before going into in detailed project example, let's move with the what is spring Redis. As Java developers, we need to talk about the data layer, as we can't develop an insightful application without the use of CRUD operations. 

You might have developed the CRUD web applications using databases such as MYSQL, SQL Server, Oracle, etc. This time, though, we'll utilize a NoSQL database, which isn't the same as a relational database.

Before moving to Spring boot and Redis's example, let's talk about what is Redis?

What is Redis?

Redis is an in-memory remote data structure store (database) that is open source (BSD licensed) and offers great performance, replication, and a unique data model. Redis stands for Remote Directory Server in its entire form. We can also use it in a variety of ways. 

Strings, hashes, lists, sets, sorted sets with range searches, bitmaps, geographic indexes, and streams are all available in Redis. We'll be able to use the common patterns of Spring Data (templates, etc.), while also having the traditional simplicity of all Spring Data projects.

If you want to learn more about Redis, you can also check out these best Redis courses to start with. This list contains the best online courses to learn Redis from Udemy and other websites. 

So let's start our Redis example project with Spring boot. 




The Redis Configuration

We need to declare the Spring Boot Redis dependencies in the pom.xml file before starting to code.

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

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.3.0</version>
<type>jar</type>
</dependency>

Instead of having separated dependencies above, we can use the spring boot starter for Redis and it will eliminate the need for separate spring-data and jedis dependencies. 

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

Note : You can install the latest maven dependencies and use them there. No need to stick with the above versions of the dependencies. This Redis framework supports for both the XML and Java configurations. In this tutorial, we only focus on Java based configurations




The Java Configuration

This java based configuration is quite simple. We can define a connectionFactory in order to define the JedisClient. Then we will define the RedisTemplate using the jedisConnectionFactory. This will be used to querying data with the custom repository.

@Bean
JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}

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


The Custom Connection Properties

As you can see in the above example, the server port number, address are missing. To include those properties, we can modify the JedisConnectionFactory method as below. 
@Bean
JedisConnectionFactory jedisConnectionFactoryMethod() {
JedisConnectionFactory myJedisConFactory
= new JedisConnectionFactory();
myJedisConFactory.setHostName("localhost");
myJedisConFactory.setPort(8000);
return myJedisConFactory;
}


The Student Entity

In here, we can define the Student Entity as below. It is used to map with the database.

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;

@RedisHash("Student")
public class Student implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

private String name;

private String grade;

private String contactNo;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGrade() {
return grade;
}

public void setGrade(String grade) {
this.grade = grade;
}

public String getContactNo() {
return contactNo;
}

public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}

@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", grade='" + grade + '\'' +
", contactNo='" + contactNo + '\'' +
'}';
}
}

The Student Data Repository

Now we can create the student data repository layer as below. 
package com.student.crudapp.Repository;

import com.student.crudapp.Model.Student;
import org.springframework.data.repository.CrudRepository;

public interface StudentRepository extends CrudRepository<Student, String> {

}
So through this, we were able to get the complete set of persistence methods that perform CRUD functionality.


Data Access using StudentRepository

1. How to retrive a existing student by the id is shown below.

Student studentExisiting = studentRepository.findById(1).get();

2. Save a new student to Database.
Student student = new Student(1, "Jhon Doe", 3, 01112345345);
studentRepository.save(student);

3. Update an existing student.
Student studentExisiting = studentRepository.findById(1).get();
studentExisiting.setName("Alex Hales");
studentRepository.save(student);

4. Delete an existing student.
studentRepository.deleteById(student.getId()); 

5. Find all the students. 
As we save some student data in the above, we can use this multiple times
 to insert many students.

Student student1 = new Student(1, "Jhon Doe", 3, 01112345345);
Student student2 = new Student(2, "Alex Hales", 3, 0111232235);
studentRepository.save(student1);
studentRepository.save(student2);

To find all the student details which is saved, we can use the findAll() 
in built method as below.
List<Student> allStudents = new ArrayList<>();
studentRepository.findAll().forEach(students::add);

So this is how we can deal with the Spring boot and Redis. 
Spring Boot + Redis Example in Java

Summary

Spring is the most popular full-stack Java/JEE application framework. It uses dependency injection, AOP, and portable service abstractions to provide a lightweight container and a non-invasive programming style. 
              
For horizontal scalability and speed, NoSQL storage systems offer an alternative to traditional RDBMS. Key-value stores are one of the largest (and oldest) members of the NoSQL family in terms of implementation.

That's all about how to use Redis with Spring Boot Application in Java. So in this tutorial, we go through some basics of what is redis and also we discussed an example related to spring boot and redis. Hope you understand what we have discussed so far and hope to see you in the next tutorial. Until then, bye.

Other Spring Framework articles you may like to explore 


    Thanks for reading this article so far. If you find this Spring Boot and Redis example tutorial useful, please share them with your friends and colleagues. If you have any questions or feedback, then please drop a note.


    No comments:

    Post a Comment