我正在使用 Spring Integration 应用程序,该应用程序应该迭代目录的内容,处理其中的文件,然后退出。
我已经将下面的 XML 设置为每秒轮询一次目录,但这并不是我想要的。如何更改此设置以读取目录中的所有文件,然后在消息完成流经系统后让我的程序退出?
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int-file="http://www.springframework.org/schema/integration/file"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/integration/xml http://www.springframework.org/schema/integration/xml/spring-integration-xml-2.1.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-2.1.xsd
http://www.springframework.org/schema/integration/file http://www.springframework.org/schema/integration/file/spring-integration-file-2.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd >
<int-file:inbound-channel-adapter
directory="inputDir"
channel="inputChannel">
<int:poller fixed-rate="1000"></int:poller>
</int-file:inbound-channel-adapter>
<!-- more components to read from inputChannel, write to output adapter -->
</beans>
最佳答案
有点老套,我过去曾使用过这种方法并且效果很好。
该方法是定义一个关闭
队列 channel ,从主线程等待消息到达此 channel ,一旦可用即可关闭应用程序上下文。
<int:channel id="shutdownChannel"><int:queue/></int:channel>
在你的主线程中 - :
PollableChannel pollableChannel = applicationContext.getBean("shutdownChannel",PollableChannel.class);
pollableChannel.receive();
applicationContext.close();
仅当消息进入关闭 channel 时,主代码才会经过 receive
调用。现在的问题是如何将消息发送到关闭 channel 。
您可以在文件消息的最终处理器中保留某些状态,例如自上次处理任何文件以来的时间,以下可能是一个稻草人:
public class FileContentProcessor {
private long lastProcessedTime = System.currentTimeMillis();
public void processContent(String content){
this.lastProcessedTime = System.currentTimeMillis();
System.out.println("Processed content: " + content);
}
public long msSinceLastProcessed(){
return System.currentTimeMillis() - this.lastProcessedTime;
}
}
根据此状态定义入站 channel 适配器:
<int:inbound-channel-adapter ref="fileProcessor" method="msSinceLastProcessed" channel="shutdownFilterChannel">
<int:poller fixed-rate="3000"/>
</int:inbound-channel-adapter>
<int:filter input-channel="shutdownFilterChannel" output-channel="shutdownChannel" expression="payload>20000"></int:filter>
在这里,我实质上是获取自上次处理以来的时间,将其传递给一个过滤器,该过滤器检查自上次处理时间以来是否已经超过 20 秒,并将该消息传递到关闭 channel 。
关于java - Spring 集成: iterate through contents of directory only once,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13607283/