Last active
May 28, 2022 01:15
-
-
Save rcvaram/0c006e33755b4fcfbf50dbf796a1927f to your computer and use it in GitHub Desktop.
This describes the reader writer database configurations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Configuration | |
| @EntityScan | |
| public class DatabaseConfig { | |
| @Bean | |
| @ConfigurationProperties(prefix = "db.master") | |
| public DataSource readWriteConfiguration() { | |
| return DataSourceBuilder.create().build(); | |
| } | |
| @Bean | |
| @ConfigurationProperties(prefix = "db.slave") | |
| public DataSource readOnlyConfiguration() { | |
| return DataSourceBuilder.create().build(); | |
| } | |
| @Bean | |
| @Primary | |
| public DataSource routingDataSource() { | |
| return new TransactionRoutingDataSource(loggingProxy("read_write", readWriteConfiguration()), | |
| loggingProxy("read_only", readOnlyConfiguration())); | |
| } | |
| private DataSource loggingProxy(String name, DataSource dataSource) { | |
| SLF4JQueryLoggingListener loggingListener = new SLF4JQueryLoggingListener(); | |
| loggingListener.setLogLevel(SLF4JLogLevel.DEBUG); | |
| loggingListener.setLogger(name); | |
| loggingListener.setWriteConnectionId(false); | |
| return ProxyDataSourceBuilder.create(dataSource).name(name).listener(loggingListener).build(); | |
| } | |
| @Bean | |
| public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) { | |
| return builder.dataSource(routingDataSource()).packages("org.rcvaram.demo.entity").build(); | |
| } | |
| @Bean | |
| @Primary | |
| public PlatformTransactionManager transactionManager(@Qualifier("jpaTxManager") PlatformTransactionManager wrapped) { | |
| return new ReplicaAwareTransactionManager(wrapped); | |
| } | |
| @Bean(name = "jpaTxManager") | |
| public PlatformTransactionManager jpaTransactionManager(EntityManagerFactory emf) { | |
| return new JpaTransactionManager(emf); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment