0
我正在使用Spring Framework JDBC处理PostgreSQL上的所有数据库作业。现在我想将我的读写分离成主服务器和从服务器。我能否在不涉及Hibernate等其他框架的情况下实现这一目标?这最好的做法是什么?我可以使用Spring Framework分开JDBC读写操作吗?
我正在使用Spring Framework JDBC处理PostgreSQL上的所有数据库作业。现在我想将我的读写分离成主服务器和从服务器。我能否在不涉及Hibernate等其他框架的情况下实现这一目标?这最好的做法是什么?我可以使用Spring Framework分开JDBC读写操作吗?
您可以通过处理多个数据源配置来实现这一点。 有几种方法可以做到这一点,但我更喜欢如下。
在您的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)
你想让它查询奴隶的方法。
这是完全可行的。您只需要定义两个不同的* Datsources *并根据* JdbcTemplates *。 [这个链接](http://stackoverflow.com/questions/30362546/how-to-use-2-or-more-databases-with-spring)正在做这样的事情。 – jah