java - 我可以使用 Spring Framework 分离 JDBC 读取和写入吗?

标签 java postgresql jdbc spring-data

我正在使用 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/

相关文章:

java - SpringMvc Controller 类不工作

java - 是否可以在没有变量的情况下计算方法执行时间?

java - Android应用设备体积

database - 可以在 CTE 中订购 JOIN 操作吗? (PostgreSQL)

postgresql - 如何从数据库插入返回串行主键以用于另一个数据库插入

java - 使用 Spring 框架单例 bean 进行单元测试

java - 使用 Java 调用 PostgreSQL 存储过程返回 null

java - 什么时候必须关闭数据库连接? ( java )

java - SQL Server : Data more fractional digits in Java

java - CREATE TABLE 的 SQL 语法错误