Spring Boot with Database and Redis

Shashikanth Nalla
Javarevisited
Published in
1 min readFeb 17, 2021

--

Spring boot logo and database logo

This article explains using the spring boot application with multiple data sources.

I am using Spring Boot 2.3.0.RELEASE and database as Postgres, pre-requisites are Postgres database and Redis running already.

Lets get started by adding below dependencies to your pom.xml file

Annotate the spring boot application class using these annotations.

RedisKeyValueAdapter.EnableKeyspaceEvents.ON_STARTUP listens to the expiry events of redis entries.

Configure your data sources in application.yml

Create a data source bean using @Primary annotation for Postgres to tell spring it's the primary data source, this step helps if spring runs into exceptions while creating an entity manager bean.

Let’s create entity POJO’s for Postgres and Redis

@Id for redis entity should be from org.springframework.data.annotation.Id instead of javax.persistence.Id

Let's boot the app and access health check http://localhost:8080/health. you can write JPA repository classes and perform operations with both Postgres and Redis.

You can access the complete code repo here https://github.com/shashikanth69/multiple-data-source-spring-boot.git

Happy Coding !!

--

--