103.21. 避免多次读取同一文件(幂等使用者)

Camel 直接在组件内支持 Idempotent Consumer,以便它跳过已处理的文件。这个功能可以通过设置 idempotent=true 选项来启用。

from("file://inbox?idempotent=true").to("...");

Camel 使用绝对文件名作为幂等密钥来检测重复的文件。从 Camel 2.11 开始,您可以使用 idempotentKey 选项中的表达式自定义此密钥。例如,使用名称和文件大小作为密钥

<route>
  <from uri="file://inbox?idempotent=true&amp;idempotentKey=${file:name}-${file:size}"/>
  <to uri="bean:processInbox"/>
</route>

默认情况下,Camel 使用基于内存的存储来跟踪消耗的文件,它使用了最接近 1000 条目的最近使用缓存。您可以使用值中的 # 符号来 插入 这个存储您自己的实现,以指示它在 registry 中使用指定的 id 引用 Bean。

 <!-- define our store as a plain spring bean -->
 <bean id="myStore" class="com.mycompany.MyIdempotentStore"/>

<route>
  <from uri="file://inbox?idempotent=true&amp;idempotentRepository=#myStore"/>
  <to uri="bean:processInbox"/>
</route>

如果因为之前已消耗了文件,Camel 会记录 DEBUG 级别的日志:

DEBUG FileConsumer is idempotent and the file has been consumed before. Will skip this file: target\idempotent\report.txt