181.16. 使用基于 JPA 的 Idempotent 仓库
来自 EIP 模式的 Idempotent Consumer 用于过滤掉重复的消息。提供了基于 JPA 的幂等存储库。
使用基于 JPA 的幂等存储库:
流程
-
在 persistence.xml 文件中设置
persistence-unit: -
设置
org.springframework.orm.jpaTemplate,由org.apache.camel.processor.idempotent.jpaMessageIdRepository: - 配置错误格式化宏: snippet: java.lang.IndexOutOfBoundsException: Index: 20, Size: 20
-
配置幂等存储库:
org.apache.camel.processor.idempotent.jpa.JpaMessageIdRepository: - 在 Spring XML 文件创建 JPA 幂等存储库:
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route id="JpaMessageIdRepositoryTest">
<from uri="direct:start" />
<idempotentConsumer messageIdRepositoryRef="jpaStore">
<header>messageId</header>
<to uri="mock:result" />
</idempotentConsumer>
</route>
</camelContext>当在 IDE 中运行此 Camel 组件测试时
如果您在 IDE 中直接运行此组件 的测试,而不是通过 Maven,您可以看到类似如下的异常:
org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is
<openjpa-2.2.1-r422266:1396819 nonfatal user error> org.apache.openjpa.persistence.ArgumentException: This configuration disallows runtime optimization,
but the following listed types were not enhanced at build time or at class load time with a javaagent: "org.apache.camel.examples.SendEmail".
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:427)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:127)
at org.apache.camel.processor.jpa.JpaRouteTest.cleanupRepository(JpaRouteTest.java:96)
at org.apache.camel.processor.jpa.JpaRouteTest.createCamelContext(JpaRouteTest.java:67)
at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:238)
at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:208)这里的问题在于,源已通过 IDE 编译或重新编译,而不是通过 Maven 编译,这将 在构建时增强字节代码。为了克服这一问题,您需要启用 OpenJPA 的动态字节代码增强。例如,假设 Camel 中使用的当前 OpenJPA 版本为 2.2.1,若要在 IDE 中运行测试,您需要将以下参数传递给 JVM:
-javaagent:<path_to_your_local_m2_cache>/org/apache/openjpa/openjpa/2.2.1/openjpa-2.2.1.jar