Using Two Data Sources in Spring Boot

I use Spring Boot 1.3.3 in my project using one database, now I want to use two databases with the same schema but different strong> connections .

I want to use the same repositories, entities, and find a way to tell spring which data source I want to use depending on the situation.

+6
source share
1 answer

If anyone has this problem, I found a solution:

First, your application.properties should look like this:

 datasource: primary: url: jdbc:mysql://localhost:3306/primary_db username: your_username password: your_password driver-class-name: com.mysql.jdbc.Driver secondary: url: jdbc:mysql://localhost:3306/secondary_db username: your_username password: your_password driver-class-name: com.mysql.jdbc.Driver 

After that, you need to create an enumeration with your databases:

 public enum Database { PRIMARY, SECONDARY } 

Then you create ThreadLocal:

 public class DatabaseThreadContext { private static final ThreadLocal<Database> current = new ThreadLocal<>(); public static void setCurrentDatabase(Database database) { current.set(database); } public static Object getCurrentDatabase() { return current.get(); } } 

Here comes the magic, you should use AbstractRoutingDataSource , which was implemented in Spring 2 in 2007:

 public class RoutingDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DatabaseThreadContext.getCurrentDatabase(); } } 

Finally, enter the configuration in the Spring Boot App:

 @Configuration public class DatabaseRouter { @Bean @ConfigurationProperties(prefix="datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @ConfigurationProperties(prefix="datasource.secondary") public DataSource secondaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public DataSource dataSource() { Map<Object, Object> targetDatasources = new HashMap<Object, Object>(){{ put(Database.SECONDARY, secondaryDataSource()); put(Database.PRIMARY, primaryDataSource()); }}; RoutingDataSource routingDataSource = new RoutingDataSource(); routingDataSource.setDefaultTargetDataSource(primaryDataSource()); routingDataSource.setTargetDataSources(targetDatasources); routingDataSource.afterPropertiesSet(); return routingDataSource; } } 

In each query, if you want to change your databases, you simply use this function: DatabaseThreadContext.setCurrentDatabase(Database.PRIMARY); .

In addition, you can have more than two databases at the same time.

+5
source

Source: https://habr.com/ru/post/1012380/


All Articles