182.16. 使用基于 JPA 的 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 idempotent 存储库:
<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 编译 ,这会在构建时增强字节代码。要克服这一问题,您需要启用 Open JPA 的动态字节代码增强。例如,假设 Camel 中使用的当前 Opengfortran 版本为 2.2.1,以便在 IDE 中运行测试,您需要将以下参数传递给 JVM:
-javaagent:<path_to_your_local_m2_cache>/org/apache/openjpa/openjpa/2.2.1/openjpa-2.2.1.jar