SourcePollingChannelAdapter with Transaction

时间:2013-10-17 09:40:22

标签: spring spring-integration spring-transactions

我想在实现轮询时使用SourcePollingChannelAdapter和事务传播REQUIRED,以便在发生错误时回滚所有操作。 setTransactionSynchronizationFactory方法未被注释... 非常感谢你的帮助!

在XML中,我可以这样做:

<int:poller fixed-rate="5000">
  <int:transactional transaction-manager="transactionManager" propagation="REQUIRED" />
</int:poller>

我想使用SourcePollingChannelAdapter和PeriodicTrigger以编程方式使用这样的事务,但我不知道如何。

我有这个:

SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
adapter.setSource(source);
adapter.setTrigger(new PeriodicTrigger(5, TimeUnit.SECONDS));
adapter.setOutputChannel(channel);
adapter.setBeanFactory(ctx);
adapter.start();

调用bean源时,删除数据库中的元素,创建消息并在outputchannel中发送;但是,如果我在ouputchannel之后的流程中有错误,我希望数据库恢复并且元素返回......实际上是一个传统的简单事务。我不明白这是怎么回事。

ouputchannel是:

<int:channel id="channel" >
    <int:queue />
</int:channel>
<int-http:outbound-gateway request-channel="channel"
    url="http://localhost:8081/icopitole-ws/baseactive" http-method="GET"
    reply-channel="reresponseVersionChannel" expected-response-type="java.lang.String"  />

当URL没有响应时,抛出异常但没有执行Rollback,尽管我已经像你说的那样添加了一个DefaultTransactionSynchronizationFactory和TransactionInterceptor :(

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你需要使用这个:DefaultTransactionSynchronizationFactory

以下是如何配置它的快照:

SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
    ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor =
            new ExpressionEvaluatingTransactionSynchronizationProcessor();
    syncProcessor.setBeanFactory(mock(BeanFactory.class));
    PollableChannel queueChannel = new QueueChannel();
    syncProcessor.setBeforeCommitExpression(new SpelExpressionParser().parseExpression("#bix"));
    syncProcessor.setBeforeCommitChannel(queueChannel);
    syncProcessor.setAfterCommitChannel(queueChannel);
    syncProcessor.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#baz"));

    DefaultTransactionSynchronizationFactory syncFactory =
            new DefaultTransactionSynchronizationFactory(syncProcessor);

    adapter.setTransactionSynchronizationFactory(syncFactory);

事务边界包含在SourcePollingChannelAdapter#adviceChain中,因此它应该像这样配置:

    TransactionInterceptor txAdvice = 
    new TransactionInterceptor(transactionManager, 
         new MatchAlwaysTransactionAttributeSource(new DefaultTransactionAttribute()));
    adapter.setAdviceChain(Collections.singletonList(txAdvice));

所以,现在每个'民意调查'都将包含在交易中,而你的syncFactory会执行这些操作。