我可以使用Spring Framework分离JDBC读写吗?

Eld*_*rry 0 java postgresql jdbc spring-data

我正在使用Spring Framework JDBC来处理PostgreSQL上的所有数据库作业.现在我想将我的读写分为主服务器和从服务器.我可以在不涉及Hibernate等其他框架的情况下实现这一目标吗?这是什么最好的做法?

Soe*_*ark 7

您可以通过处理多个数据源配置来实现.有几种方法可以做到这一点,但我更喜欢如下.

在context.xml中,分别设置主数据源和从数据源.

<bean id="masterDataSource" class="...">
    <property name = "driverClassName" value="value">
    ...
</bean>

<bean id="slaveDataSource" class="...">
    <property name = "driverClassName" value="...">
    ...
</bean>
Run Code Online (Sandbox Code Playgroud)

并设置重定向器,它将设备请求

<bean id="dataSourceRedirector" class="..">
    <constructor-arg name="readDataSource" ref="slaveDataSource"/>
    <constructor-arg name="writeDataSource" ref="masterDataSource"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

并将重定向器作为主数据源.请注意,我们正在使用LazyConnectionDataSourceProxy.

<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
    <constructor-arg name="targetDataSource" ref="dataSourceRedirector" />
</bean>
Run Code Online (Sandbox Code Playgroud)

并实现类重定向器,如:

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;
    }
} 
Run Code Online (Sandbox Code Playgroud)

然后@Transactional(readOnly = true)到你想让它查询奴隶的方法.