Using Redis As A Database

Rasalingam Ragul
3 min readFeb 12, 2023

--

As a Java developer, if we talk about data layer, we can’t develop an insightful application without the use of CRUD Operations. We might have developed CRUD operations multiple times using a relational database such as My SQL, SQL Server, Oracle etc. However, this time I’m going to use a NoSQL Database which is different than a relational database. Here, I will use the Redis database to implement CRUD operations using Spring Boot. Hence, this article for the discussion is ‘Spring Boot Redis CRUD Example’.

What is Redis?

Redis is an open source(BSD licensed) in-memory remote data structure store(database) that offers high performance, replication, and a unique data model. The full form of Redis is Remote Directory Server. Moreover, we can use it in multiple forms.

What is Redis Database?

Redis is a NoSQL DB of type Key-Value stores. In fact, Redis Database is an in-memory database that persists on disk. It means when we use Redis Database, we occupy a memory on the disk to use as a Database. The data model is key-value, but many several kind of values are supported such as Strings, Lists, Sets, Sorted Sets, Hashes, Streams, HyperLogLogs, Bitmaps etc.

What are the benefits of Redis?

1) In-memory data store
2) Flexible data structures : like Strings, Lists, Sets, Sorted Sets, Hashes, Bitmaps, HyperLoglogs
3) Simplicity and ease-of-use
4) High availability and scalability
5) Easy for Replication and persistence
6) High Extensibility

Let’s dive in to our sample project for that we need to create simple Spring Boot project using Spring Initializr .

1. Add Dependencies

If you are using Maven

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

Gradle

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'redis.clients:jedis:4.3.1'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

2. Redis Configuration

@Configuration
@EnableRedisRepositories
public class RedisConfig {

@Bean
public JedisConnectionFactory connectionFactory(){
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName("localhost");
configuration.setPort(6379);
return new JedisConnectionFactory(configuration);
}

@Bean
@Primary
public RedisTemplate<String, Object> redisTemplate(){
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new JdkSerializationRedisSerializer());
template.setHashValueSerializer(new JdkSerializationRedisSerializer());
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();

return template;
}
}

3. Entity

@Data
@AllArgsConstructor
@NoArgsConstructor
@RedisHash("student")
public class Student implements Serializable {
@Id
private int id;
private String name;
private int age;
private int grade;
}

4. Repository

@Repository
public class StudentRepository {
public static final String HASH_KEY = "student";
private final RedisTemplate template;

public StudentRepository(RedisTemplate template) {
this.template = template;
}

public Student save(Student student){
template.opsForHash().put(HASH_KEY, student.getId(),student);
return student;
}

public List<Student> findAll(){
return template.opsForHash().values(HASH_KEY);
}

public Student findById(int id){
return (Student) template.opsForHash().get(HASH_KEY, id);
}

public String delete(int id){
template.opsForHash().delete(HASH_KEY, id);
return "Student removed!!";
}
}

5. Service

@Service
public class StudentService {

private final StudentRepository studentRepository;

public StudentService(StudentRepository studentRepository) {
this.studentRepository = studentRepository;
}

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

public List<Student> getStudents(){
return studentRepository.findAll();
}

public Student getStudentById(int id){
return studentRepository.findById(id);
}

public String removeStudent(int id){
return studentRepository.delete(id);
}
}

6. Controller

@RestController
@RequestMapping("api/v1/student/")
public class StudentController {

private final StudentService service;

public StudentController(StudentService service) {
this.service = service;
}

@PostMapping
public Student addStudent(@RequestBody Student student){
return service.saveStudent(student);
}

@GetMapping
public List<Student> getStudents(){
return service.getStudents();
}

@GetMapping("{id}")
public Student getStudentById(@PathVariable int id){
return service.getStudentById(id);
}

@DeleteMapping("{id}")
public String removeStudent(@PathVariable int id){
return service.removeStudent(id);
}

}

Conclusion

After going through all the theoretical & example part of ‘Spring Boot Redis CRUD Example’, finally, You should be able to implement Redis DB in a Spring Boot Application. I hope you might be convinced by the article Spring Boot Redis CRUD Example.

You can found full project on my GitHub.

--

--

Rasalingam Ragul
Rasalingam Ragul

Written by Rasalingam Ragul

Software Engineering Undergraduate

No responses yet