Skip to main content

Spring Data Redis with RedisTemplate and CrudRepository

In this article, we will see how to use Spring Data Redis to communicate (using RedisTemplate and CrudRepository) with a Redis instance or cluster.

1) Run Redis in a Docker Container

To run Redis in a Docker container, you can follow these steps:

1) Make sure you have Docker installed on your machine. You can download and install Docker from the official Docker website.

2) Open a terminal or command prompt and run the following command to pull the Redis Docker image from Docker Hub:

docker pull redis

3) Once the Redis image is pulled, you can start a Redis container using the following command:

docker run --name my-redis-container -d -p 6379:6379 redis

4) To verify that the Redis container is running, you can use the following command:

docker ps

CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                    NAMES
c6987af34bba   redis     "docker-entrypoint.s…"   29 seconds ago   Up 28 seconds   0.0.0.0:6379->6379/tcp   my-redis-container

5) Run the following command to start a new redis-cli session and connect to the Redis container:

docker exec -it c6987af34bba redis-cli

2) Set up a Spring Boot project

Create a new Spring Boot project or use an existing one. You can set up a new project using Spring Initializr or your preferred IDE.

2.1) Dependencies

In your project's pom.xml, add the following dependencies:


2.2) Properties

In your application.properties or application.yml file, configure the Redis connection properties.

2.3) Redis configuration

Create a new RedisConfig.java class to configure Redis. This configuration sets up a "Redis connection factory" and a "Redis template bean", which allows you to interact with Redis.

2.4) Using the RedisTemplate

In this, the RedisTemplateService injects the RedisTemplate bean and provides methods to set and get values from Redis.

2.4.1) Create a REST Controller

Create a "RedisController" class and annotate it with @RestController. This class will handle the HTTP requests and define the API endpoints.

2.5) Using repositories

2.5.1) Create a Redis entity

Define a Java class that represents your Redis entity. This class should have the necessary annotations to specify the Redis key and any additional properties.

The User class is annotated with @RedisHash("users") to indicate that it maps to the "users" Redis hash.


2.5.2) Create a repository interface

The UserRepository interface provides basic CRUD operations (create, read, update, delete) for the User entity. You can also define additional custom query methods if needed.

2.5.2) Perform Redis operations

The UserServiceImpl class injects the UserRepository and uses it to save and retrieve User entities.

2.5.3) Create a REST Controller

Create a "UserController" class and annotate it with @RestController. This class will handle the HTTP requests and define the API endpoints.

2.6) Run the application

Run the Spring Boot application using your preferred method (e.g., IDE, Maven).

2.7) Test

You can now test your API using a tool like cURL, Postman, or /swagger-ui. For example, you can use swagger-ui to make requests from the browser:

Swagger UI

Source Code

Comments

Popular posts from this blog

Deploying Spring Boot microservices on Kubernetes Cluster

This article guides you through the deployment of two Spring Boot microservices, namely "order-service" and "inventory-service," on Kubernetes using "MiniKube" . We will establish communication between them, with "order-service" making calls to an endpoint in "inventory-service." Additionally, we will configure "order-service" to be accessible from the local machine's browser . 1) Create Spring Boot microservices The Spring Boot microservices, "order-service" and "inventory-service," have been developed and can be found in this GitHub repository. If you are interested in learning more about creating Spring Boot REST microservices, please refer to this or this (Reactive) link. 2) Build Docker Images The Docker images for both "order-service" and "inventory-service" have already been generated and deployed on DockerHub, as shown below. codeburps/order-service cod...

Circuit Breaker Pattern with Resilience4J in a Spring Boot Application

Read Also: Spring Cloud Circuit Breaker + Resilience4j Resilience4j is a lightweight fault tolerance library that draws inspiration from Netflix Hystrix but is specifically crafted for functional programming. The library offers higher-order functions, known as decorators , designed to augment any functional interface, lambda expression, or method reference with features such as Circuit Breaker, Rate Limiter, Retry, or Bulkhead . These functionalities can be seamlessly integrated within a project, class, or even applied to a single method. It's possible to layer multiple decorators on any functional interface, lambda expression, or method reference, allowing for versatile and customizable fault tolerance. While numerous annotation-based implementations exist online, this article focuses solely on the reactive approach using router predicates and router functions . How Circuit Breaker Pattern works? In general, a circuit breaker functions as an automatic electrical s...

Declarative REST Client in Spring Boot (Spring 6 HTTP Interface)

Feign , an early declarative REST client, was initially part of the Spring Cloud Netflix stack and later rebranded as Spring Cloud OpenFeign . Before its introduction, crafting HTTP calls using RestTemplate involved repetitive code for each service interaction. With Feign, developers could simply define an interface with method contracts mirroring the service's endpoints. Behind the scenes, proxy magic generated a fully functional HTTP client, eliminating the need for boilerplate code . HTTP Interface (Spring Framework 6) The recent release of Spring Framework 6 integrated this declarative REST client as a native part of the core web framework in the form of the HTTP Interface . All the necessary components reside in the spring-web module, which is a transitive dependency for either the spring-boot-starter-web or spring-boot-starter-webflux modules. Currently, the WebFlux dependency is essential due to the HttpServiceProxyFactory , responsible for client gener...