32.14. 使用 JPA-Based Idempotent 仓库
EIP 模式中的 Idempotent Consumer 用于过滤掉重复的消息。提供了基于 JPA 的幂等存储库。
使用基于 JPA 的幂等存储库。
流程
-
在 persistence.xml 文件中设置
persistence-unit。 -
设置
org.springframework.orm.jpa.JpaTemplate,供org.apache.camel.processor.idempotent.jpa.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 idempotentRepository="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.junit5.CamelTestSupport.doSetUp(CamelTestSupport.java:238)
at org.apache.camel.test.junit5.CamelTestSupport.setUp(CamelTestSupport.java:208)
这里的问题是源已通过 IDE 编译或重新编译,而不是通过 Maven 进行编译 ,这会在构建时增强字节代码。要克服这一点,您需要启用 Open Liberty 的动态字节代码增强。例如,假设 Camel 中使用的当前 Open the 版本为 2.2.1,要在 IDE 中运行测试,您需要将以下参数传递给 JVM:
-javaagent:<path_to_your_local_m2_cache>/org/apache/openjpa/openjpa/2.2.1/openjpa-2.2.1.jar