【问题标题】:Master-slave configuration on spring boot, @Transactional(readOnly = true) not working as expectedspring boot 上的主从配置,@Transactional(readOnly = true) 没有按预期工作
【发布时间】:2022-12-08 00:57:42
【问题描述】:

所以我有一个主从数据源设置如下:

@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.myservice.notificationservice.repositories.happyoffer",
        entityManagerFactoryRef = "happyofferEntityManagerFactory",
        transactionManagerRef= "happyofferTransactionManager"
)
public class HappyofferDataSourceConfig {

    @Value("${spring.entity.scan.packages}")
    private String packageToScan;

    @Bean
    @Primary
    @ConfigurationProperties("spring.happyoffer.datasource.master")
    public DataSourceProperties happyOfferMasterDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean
    @ConfigurationProperties("spring.happyoffer.datasource.master.configuration")
    public DataSource masterDataSource() {
        return happyOfferMasterDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
    }

    @Bean
    @ConfigurationProperties("spring.happyoffer.datasource.slave")
    public DataSourceProperties happyOfferSlaveDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "slaveDataSource")
    @ConfigurationProperties("spring.happyoffer.datasource.slave.configuration")
    public DataSource slaveDataSource() {
        return happyOfferSlaveDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
    }

    @Bean
    @Primary
    public DataSource routingDataSource() {

        Map<Object, Object> targetDataSources = new LinkedHashMap<>();
        RoutingDataSourceConfiguration routingDataSourceConfiguration = new RoutingDataSourceConfiguration();
        DataSource master = this.masterDataSource();
        targetDataSources.put(DataSourceTypes.MASTER, master);
        DataSource slave = this.slaveDataSource();
        targetDataSources.put(DataSourceTypes.SLAVE, slave);
        routingDataSourceConfiguration.setTargetDataSources(targetDataSources);
        routingDataSourceConfiguration.setDefaultTargetDataSource(master);
        return routingDataSourceConfiguration;
    }

    @Bean
    public DataSource dataSource() {
        return new LazyConnectionDataSourceProxy(routingDataSource());
    }

    @Bean(name = "happyofferEntityManagerFactory")
    @Primary
    public LocalContainerEntityManagerFactoryBean happyofferEntityManagerFactory(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(routingDataSource())
                .packages(new String[]{packageToScan})
                .build();
    }


    @Bean
    @Primary
    public PlatformTransactionManager happyofferTransactionManager(final @Qualifier("happyofferEntityManagerFactory") LocalContainerEntityManagerFactoryBean happyofferEntityManagerFactory) {
        return new JpaTransactionManager(happyofferEntityManagerFactory.getObject());
    }

    @Primary
    @Bean(name = "readerJdbcTemplate")
    public NamedParameterJdbcTemplate getReaderJdbcTemplate() {
        return new NamedParameterJdbcTemplate(slaveDataSource());
    }

    @Bean(name = "writerJdbcTemplate")
    public NamedParameterJdbcTemplate getWriterJdbcTemplate() {
        return new NamedParameterJdbcTemplate(masterDataSource());
    }
}

路由配置定义为:

public class RoutingDataSourceConfiguration extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        boolean isReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();
        if(isReadOnly) {
            return DataSourceTypes.SLAVE;
        } else {
            return DataSourceTypes.MASTER;
        }
    }
}

我还有一个存储库类定义为:

@Repository
@Transactional(readOnly = true)
public interface DeviceInfoRepository extends JpaRepository<DeviceInfo,Integer> {

    List<DeviceInfo> findAllByUserIdIn(List<Integer> userIds);
}

我只是在这样的服务中调用上述函数:

@Service
@Slf4j
public class NotificationShooterServiceImpl implements NotificationShooterService {

    @Autowired
    DeviceInfoRepository deviceInfoRepository;

    @Override
    public NotificationShooterResponse shoot(List<Integer> userIds) throws Exception {
       

        List<DeviceInfo> deviceInfoList = deviceInfoRepository.findAllByUserIdIn(userIds);
        log.info("Size : " + deviceInfoList.size());
        ..........
        ..........
        ..........
        NotificationShooterResponse notificationShooterResponse = new NotificationShooterResponse();
        notificationShooterResponse.setCountOfUniqueUserIds(deviceInfoList.size());

        return notificationShooterResponse;
    }

现在,正如我添加的@Transactional(readOnly = true),我希望查询将被路由到 SLAVE 数据库。但是,我每次都看到它变成了 MASTER。 我对此进行了调试,发现此事务的 readOnly 属性未设置为 true,即 在上面显示的文件RoutingDataSourceConfiguration中, boolean isReadOnly = TransactionSynchronizationManager.isCurrentTransactionReadOnly();false

【问题讨论】:

    标签: java spring spring-transactions master-slave


    【解决方案1】:

    简而言之,这个问题的解决方案是将 hibernate.connection.provider_disables_autocommit=true 添加到 application.properties,如果使用 Hikari,还可以设置 setAutoCommit(false)

    More details can be found here

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 2017-10-27
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多