81,094
社区成员
发帖
与我相关
我的任务
分享
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactory")
public class JpaDbConfig {
@Value("${druid.type}")
private Class<? extends DataSource> dataSourceType;
@Bean(name = "writeDataSource")
@ConfigurationProperties(prefix = "druid.winpos.master")
public DataSource winposMasterDataSource() {
return DataSourceBuilder.create().type(dataSourceType).build();
}
@Bean(name = "readDataSource")
@ConfigurationProperties(prefix = "druid.winpos.slave")
public DataSource winposSlaveDataSource1() {
return DataSourceBuilder.create().type(dataSourceType).build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("dataSource") DataSource dataSource){
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setDatabase(Database.MYSQL);
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(false);
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan("mw.jpa");
factory.setDataSource(dataSource);
Map<String, Object> jpaProperties = new HashMap<String, Object>();
jpaProperties.put("hibernate.ejb.interceptor",new MyInterceptor());
jpaProperties.put("hibernate.cache.use.query_cache",false);
jpaProperties.put("hibernate.cache.use_second_level_cache",false);
jpaProperties.put("javax.persistence.cache.storeMode", CacheStoreMode.BYPASS);
jpaProperties.put("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS);
factory.setJpaPropertyMap(jpaProperties);
factory.setSharedCacheMode(SharedCacheMode.DISABLE_SELECTIVE);
factory.afterPropertiesSet();
return factory;
}
@Bean
public ReplicationRoutingDataSource dataSource(@Qualifier("writeDataSource") DataSource writeDataSource, @Qualifier("readDataSource") DataSource readDataSource){
ReplicationRoutingDataSource routingDataSource=new ReplicationRoutingDataSource();
Map<Object, Object> dataSourceMap = new HashMap<Object, Object>();
dataSourceMap.put("write", writeDataSource);
dataSourceMap.put("read", readDataSource);
routingDataSource.setTargetDataSources(dataSourceMap);
routingDataSource.setDefaultTargetDataSource(writeDataSource);
return routingDataSource;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
DynamicDataSourceTransactionManager transactionManager = new DynamicDataSourceTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
// transactionManager.setDataSource(dataSource());
return transactionManager;
}
}
public class ReplicationRoutingDataSource extends AbstractRoutingDataSource {
private Logger log = LoggerFactory.getLogger(ReplicationRoutingDataSource.class);
@Override
protected Object determineCurrentLookupKey() {
// String dataSourceType = TransactionSynchronizationManager.isCurrentTransactionReadOnly() ? "read" : "write";
log.info("current dataSourceType : {}", DynamicDataSourceHolder.getDataSource().name());
return DynamicDataSourceHolder.getDataSource().name().toLowerCase();
}
}
public class DynamicDataSourceTransactionManager extends JpaTransactionManager
{
/**
* 只读事务到读库,读写事务到写库
* @param transaction
* @param definition
*/
@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
//设置数据源
boolean readOnly = definition.isReadOnly();
if(readOnly) {
logger.info("doBegin"+DynamicDataSourceGlobal.READ.name());
DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.READ);
} else {
DynamicDataSourceHolder.putDataSource(DynamicDataSourceGlobal.WRITE);
logger.info("doBegin"+DynamicDataSourceGlobal.WRITE.name());
}
super.doBegin(transaction, definition);
}
/**
* 清理本地线程的数据源
* @param transaction
*/
@Override
protected void doCleanupAfterCompletion(Object transaction) {
super.doCleanupAfterCompletion(transaction);
DynamicDataSourceHolder.clearDataSource();
}
}
@GetMapping("test")
public void saveWrite() throws Exception {
User newUserFromRead = userOuterService.findByIdRead(1);
User newUser = new User();
newUser.setName("New User");
userOuterService.save(newUser);
log.info("User saved : {}", newUser);
// User newUserFromRead = userOuterService.findByIdRead(1);
//// assertThat(newUserFromRead).as("New user is saved to write db. So read db must not have the user.").isNull();
//
// User newUserFromWrite = userOuterService.findByIdWrite(1);
// assertThat(newUserFromWrite).as("New user is saved to write db. So write db must have the user.").isNotNull().isEqualTo(newUser);
}