首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我可以使用Spring Framework分离JDBC读写吗?

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

Stack Overflow用户
提问于 2016-01-18 10:47:05
回答 1查看 708关注 0票数 0

我使用Spring Framework JDBC来处理我在PostgreSQL上的所有数据库作业。现在,我想将读写操作分离到主服务器和从服务器中。我可以在不涉及Hibernate等其他框架的情况下实现这一点吗?这方面的最佳实践是什么?

EN

回答 1

Stack Overflow用户

发布于 2016-01-18 11:18:37

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

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

代码语言:javascript
复制
<bean id="masterDataSource" class="...">
    <property name = "driverClassName" value="value">
    ...
</bean>

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

并设置将设备请求的重定向器

代码语言:javascript
复制
<bean id="dataSourceRedirector" class="..">
    <constructor-arg name="readDataSource" ref="slaveDataSource"/>
    <constructor-arg name="writeDataSource" ref="masterDataSource"/>
</bean>

并将重定向器作为主数据源。注意,我们使用的是LazyConnectionDataSourceProxy

代码语言:javascript
复制
<bean id="dataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
    <constructor-arg name="targetDataSource" ref="dataSourceRedirector" />
</bean>

并实现类重定向器,如下所示:

代码语言:javascript
复制
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)到你想让它在从服务器上查询的方法。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34846541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档