我使用Spring Framework JDBC来处理我在PostgreSQL上的所有数据库作业。现在,我想将读写操作分离到主服务器和从服务器中。我可以在不涉及Hibernate等其他框架的情况下实现这一点吗?这方面的最佳实践是什么?
发布于 2016-01-18 11:18:37
您可以通过处理多个数据源配置来做到这一点。有几种方法可以做到这一点,但我更喜欢如下所示。
在context.xml中,分别设置主数据源和从数据源。
<bean id="masterDataSource" class="...">
<property name = "driverClassName" value="value">
...
</bean>
<bean id="slaveDataSource" class="...">
<property name = "driverClassName" value="...">
...
</bean>并设置将设备请求的重定向器
<bean id="dataSourceRedirector" class="..">
<constructor-arg name="readDataSource" ref="slaveDataSource"/>
<constructor-arg name="writeDataSource" ref="masterDataSource"/>
</bean>并将重定向器作为主数据源。注意,我们使用的是LazyConnectionDataSourceProxy。
<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<constructor-arg name="targetDataSource" ref="dataSourceRedirector" />
</bean>并实现类重定向器,如下所示:
public class DataSourceRedirector extends AbstractRoutingDataSource {
private final DataSource writeDataSource;
private final DataSource readDataSource;
public DataSourceRedirector(DataSource writeDataSource, DataSource readDataSource) {
this.writeDataSource = writeDataSource;
this.readDataSource = readDataSource;
}
@PostConstruct
public void init() {
Map<Object, Object> dataSourceMap = new HashMap<>();
dataSourceMap.put("write", writeDataSource);
dataSourceMap.put("read", readDataSource);
this.setTargetDataSources(dataSourceMap);
this.setDefaultTargetDataSource(writeDataSource);
}
@Override
protected Object determineCurrentLookupKey() {
String dataSourceType =
TransactionSynchronizationManager.isCurrentTransactionReadOnly() ? "read" : "write";
return dataSourceType;
}
} 然后@Transactional(readOnly = true)到你想让它在从服务器上查询的方法。
https://stackoverflow.com/questions/34846541
复制相似问题