2014-12-02 62 views
2

我找的例子有註解的類,完全XML免費的這樣:JDBC Spring集成與註解

<int-jdbc:inbound-channel-adapter query="select * from item where status=2" 
channel="target" data-source="dataSource" 
update="update item set status=10 where id in (:id)" /> 

OR

<int-jdbc:inbound-channel-adapter query="..." 
    channel="target" data-source="dataSource" update="..."> 
<int:poller fixed-rate="1000"> 
    <int:transactional/> 
</int:poller> 
</int-jdbc:inbound-channel-adapter> 

也許存在一個更好的解決方案,如輸入消息網關通過使用CRON語句查詢數據庫來創建入口點。 克朗編程查詢 - >第一通道

回答

3

Java的&註解配置變種:

@Bean 
public PollerMetadata poller(PlatformTransactionManager transactionManager) { 
    PeriodicTrigger trigger = new PeriodicTrigger(1000); 
    trigger.setFixedRate(true); 

    MatchAlwaysTransactionAttributeSource attributeSource = new MatchAlwaysTransactionAttributeSource(); 
    attributeSource.setTransactionAttribute(new DefaultTransactionAttribute()); 
    TransactionInterceptor interceptor = new TransactionInterceptor(transactionManager, attributeSource); 

    PollerMetadata poller = new PollerMetadata(); 
    poller.setTrigger(trigger); 
    poller.setAdviceChain(Collections.singletonList(interceptor)); 
    return poller; 
} 

@Bean 
@InboundChannelAdapter(value = "target", poller = @Poller("poller")) 
public MessageSource<?> counterMessageSource(DataSource dataSource) { 
    JdbcPollingChannelAdapter adapter = 
      new JdbcPollingChannelAdapter(dataSource, "select * from item where status = 2"); 
    adapter.setUpdateSql("update item set status = 10 where id in (:id)"); 
    return adapter; 
} 

權,本次交易構成長相醜陋,但尚未提供TX AdvicePollerMetadata的簡單方法。

你可以考慮對此事使用Spring Integration Java DSL

@Bean 
public MessageSource<?> jdbcAdapter(DataSource dataSource) { 
    JdbcPollingChannelAdapter adapter = 
      new JdbcPollingChannelAdapter(dataSource, "select * from item where status = 2"); 
    adapter.setUpdateSql("update item set status = 10 where id in (:id)"); 
    return adapter; 
} 

@Bean 
public IntegrationFlow jdbcFlow(MessageSource<?> jdbcAdapter) { 
    return IntegrationFlows 
      .from(jdbcAdapter, e -> 
        e.poller(p -> p.fixedRate(1000).transactional(transactionManager()))) 
      .channel(c -> c.direct("target")) 
      .get(); 
} 

隨意,以提高對DSL項目GH-問題,爲JDBC適配器提供了DSL。

+0

它的工作原理!非常感謝。在這一刻,我想了解poller.setAdviceChain(Collections.singletonList(interceptor))的含義。我收到一個錯誤,因爲它期待着一個不同的類型: PollerMetadata類型中的setAdviceChain(List )方法不適用於參數(List ) – crm86 2014-12-02 15:04:02

+0

試試這個'poller.setAdviceChain(Collections。 singletonList攔截器));' - 方法的預期泛型。 – 2014-12-02 15:07:10

+0

@Artem Bilan:如何獲得您在第二個片段中提到的'transactionManager'?謝謝。 – 2018-03-10 01:16:47