我正在使用 Spring Framework JDBC 来处理我在 PostgreSQL 上的所有数据库作业。现在我想将我的读写分离到主服务器和从服务器中。我可以在不涉及 Hibernate 等其他框架的情况下实现这一目标吗?这方面的最佳做法是什么?
最佳答案
您可以通过处理多个数据源配置来做到这一点。 有几种方法可以做到这一点,但我更喜欢下面的方法。
在你的context.xml中,分别设置master和slave数据源。
<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)
到你想让它在从站上查询的方法。
关于java - 我可以使用 Spring Framework 分离 JDBC 读取和写入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34846541/