在事务测试中不回滚Spring Kafka Listener中保存的实体

时间:2019-01-01 12:31:12

标签: spring spring-data spring-jdbc transactional spring-kafka

我有一个@KafkaListener,它使用Spring Data JDBC Repository保存了一个新实体。保存的实体不会在带有@Transactional

的测试中回滚
@Service
public class KafkaConsumer {

    private final EntityRepository entityRepository;

    private CountDownLatch countDownLatch;

    public KafkaConsumer(EntityRepository entityRepository) {
        this.entityRepository = entityRepository;
    }

    @KafkaListener(topics = "topic", groupId = "group-id")
    public void consume(String id) {
        Entity entity = new Entity();
        entity.setId(id);
        entity.setNew(true);

        entityRepository.save(entity);

        if (countDownLatch != null) countDownLatch.countDown();
    }

    public void setCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }
}

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class SpringKafkaDataJdbcMysqlTransactionalTestApplicationTests {

    @ClassRule
    public static EmbeddedKafkaRule embeddedKafkaRule = new EmbeddedKafkaRule(1, true, 1, "topic");

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private KafkaConsumer kafkaConsumer;

    @Autowired
    private EntityRepository entityRepository;

    @BeforeClass
    public static void setup() {
        System.setProperty("spring.kafka.bootstrap-servers", embeddedKafkaRule.getEmbeddedKafka().getBrokersAsString());
    }

    @Test
    public void test() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);

        kafkaConsumer.setCountDownLatch(countDownLatch);

        String id = UUID.randomUUID().toString();

        kafkaTemplate.send("topic", id);

        assertThat(countDownLatch.await(5, TimeUnit.SECONDS)).isTrue();

        assertThat(entityRepository.findById(id)).isNotEmpty();
    }

}

我正在使用MySQL数据库运行此程序,并且希望保存的实体能够回滚。看起来由存储库启动的事务未加入测试中由事务启动的事务,因为它是单独线程中的事务。

如何加入交易并回滚实体?另外,这是测试此行为的好方法吗?

我在这里复制了此内容:https://github.com/yraydhitya/spring-kafka-data-jdbc-mysql-transactional-test

0 个答案:

没有答案