spring数据归档最佳实践

1yjd4xko  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(425)

假设我有实体 Rule 以及 RuleArchive . 每次有人改变 Rule 是将以前的状态保持到 RuleArchiveTable . 我想到了这个解决方案:

class CustomRuleRepositoryImpl implements CustomRuleRepository {
    private final RuleRepository ruleRepository;
    private final RuleArchiveRepository ruleArchiveRepository;

    @Override
    public Rule saveAndFlushWithArchiveRecordCreated(Rule rule) {
        ofNullable(rule.getId())
            .flatMap(ruleRepository::findById)
            .ifPresent(this::createNewArchiveRecord);
        return ruleRepository.saveAndFlush(rule);
    }

    private void createNewArchiveRecord(Rule oldRule) {
        ruleArchiveRepository.saveAndFlush(
            RuleArchive.builder()
                // building the entity from 'oldRule' fields
                .build()
        );
    }
}

我担心的是并发性。虽然系统不是高负载类型,但可能有一些注意事项。例如,当我用 ruleRepository 可能已经有人改变了。因此,存档版本和保存规则的值将不一致。
对这种方法有什么想法吗?有更好的选择吗?我想我可以 repeatable read 隔离(我们使用postgresql),因此可以保证在整个事务期间获取的记录是相同的。

ghhaqwfi

ghhaqwfi1#

这将防止脏读:

@Transactional(isolation = Isolation.READ_COMMITTED)

这里有更多https://www.baeldung.com/spring-transactional-propagation-isolation
需要注意的重要一点是,虽然隔离级别防止脏读,但它们不会阻止争用条件—因此,您仍然需要使用synchronized(有趣的是,如果只有这个方法在执行保存操作,那么synchronized可以解决这两个问题)

相关问题