Redis with Spring Boot
Introduction
In this post we are going discuss Redis, Redis is a Key-value based NoSQL database which can be used for multiple purposes. It is open source and it is an InMemory data structure store. Because Redis supports all the basic data structures like list, set, map, and sorted set.
Using Redis we can develop a different kinds of applications like chat applications, session storage applications, gaming dashboards etc.
If you want to learn Redis then first understand about different data structures which Redis supports apart from that the commands using which we can store and get data from Redis.
Some Important Commands
Redis supports String, Set, Sorted Set, List, and HashMap as key — values. Below are some basic commands to get an understanding of different data structures.
String
SET foo bar (foo is key, bar is value)
GET foo
bar
HashMap
HMSET student name: "shubham" age: 25
HGETALL student
List
LPUSH product car
LPUSH product bike
LRANGE product 0 10
Set
SADD product car
SADD product bike
SMEMBERS product
Apart from that Redis has lot of other features also like HyperLogLog, and Transactions.
Use Cases of Redis
- Redis can be used as a Key-value based NoSQL database.
- Redis can be used as a cache provider.
- Redis can be used as a publisher and subscriber, which is used in event processing.
- Redis can be used as a session store.
- Redis can be used in chat applications.
Setup Redis on MacOS
So if you get some interest after reading this and now you want to do some hands-on practice on Redis then set up the Redis server in your system.
- Install homebrew in your system if not there.
- The Run below commands sequentially
brew install redis
After succesfull installation
brew services start redis
After starting redis if you want to try above commands
redis-cli
To test whether redis server is working
PING
If yu get PONG then its connected
If you want to monitor which all commands are getting executed on redis
redis-monitor
Setup Redis on Windows
There is no direct software to install, just download the git hub project and run the batch file from the bin folder.
So after this, if you want to use Redis from some other system then you need a client which will interact with the Redis server.
Now in this part, we will see how we can use Redis with spring boot and use it as a NoSQL DB.
Setup
The first step is to create a sample Spring boot project from spring initializer and add spring-boot-starter-data-redis dependency.
Now after importing the project into your favourite IDE, create packages and classes.
The first class will be for configuration, We have two drivers for Redis one is Jedis, another is lettuce(It is lazily initialised, and performance wise also it is better.)
Apart from the driver, we need a template for doing operations on the Redis server, the similar way we have RestTemplate for doing rest operations.
package com.redisexample.redisdemo.config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
//@EnableRedisRepositories
public class AppConfig {
//There are two ways of creating driver, one is jedis another is lettuce,
//lettuce is bit lazy in intialization so it creates beans lazily
//It is using default host and port
@Bean
RedisConnectionFactory jedisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new JdkSerializationRedisSerializer());
template.setValueSerializer(new JdkSerializationRedisSerializer());
template.setEnableTransactionSupport(true);
template.afterPropertiesSet();
return template;
}
//For setting host and port
// @Bean
// JedisConnectionFactory jedisConnectionFactory() {
// JedisConnectionFactory jedisConFactory
// = new JedisConnectionFactory();
// jedisConFactory.setHostName("localhost");
// jedisConFactory.setPort(6379);
// return jedisConFactory;
// }
}
The above class will make our application ready to connect with Redis server, Now it's simple we can use basic entity, repository, service and controller classes for doing CRUD operation on Redis.
Create an Entity class
@RedisHash("student") // this is a set so we can use set command to see data via redis cli
public class Student {
public enum Gender {
MALE, FEMALE
}
private Long id;
private String name;
private int age;
private String city;
//getters and setters
}
Create a Repository interface
@Repository
public interface StudnetRepo extends CrudRepository<Student, Long> {
}
Now create a service class and then a controller for creating APIs.
package com.redisexample.redisdemo.controller;
import com.redisexample.redisdemo.model.Student;
import com.redisexample.redisdemo.repo.StudnetRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudnetRepo studnetRepo;
@PostMapping
public void saveStudent(@RequestBody Student student){
studnetRepo.save(student);
}
@GetMapping
public Iterable<Student> getStudent(){
return studnetRepo.findAll();
}
}
We can test the above endpoints via Postman, and we can monitor the commands via Redis CLI (monitor command).
So this is a simple example of using Redis as a DB with a spring boot application.
In the next post, we will see how to use Redis as a cache Provider.
Thanks for reading!!