Spring Boot - Spring Data Redis
Lets learn to integrate Spring Data Redis into a Spring Boot application.
First, you need a Redis server. You can start a redis server as Docker container:
1 | docker run -d --rm -p 6379:6379 --name redis-demo redis |
Maven Dependency
You need to include spring-boot-starter-data-redis
dependency in your spring boot’s pom.xml file in order to use Spring Data Redis.
1 | <dependency> |
Configuration
Here is an example of Redis Configuration. The configuration below sets up a redis connection to localhost:6379 and RedisTemplate.
1 |
|
We need to provide @EnableRedisRepositories
annotation to tell Spring boot to use Reids Repositories.
LettuceConnectionFactory is a connection factory that creates Lettuce-based connections. Here we configure by providing hostname and port number. In reality, it should be configured using environmetnal configuration.
RedisTemplate is used for Redis data access.
Another approach is to configure the Redis connection in application.yml. Spring will automatically configure RedisConnectionFactory and RedisTemplate for you.
1 | spring.redis.host=localhost |
Entity
A very simple object that annotated with @RedisHash. The identity should have @Id annotation.
1 | import lombok.Data; |
Repository
Redis Repository class are interfaces that extends CrudRepository interface.
1 | import org.springframework.data.repository.CrudRepository; |
Controller
Controller class that tests the repository
1 |
|
Execute POST http request to save a customer to redis data store.
1 | curl -X POST -H 'Content-Type: application/json' localhost:8080/customers/save -d '{"name": "James"}' |
go to localhost:8080/customers/all
to view all the customers in the redis data store.
source code for this post