Apache Camel处理InputStream中PGP加密文件解密时CamelContext挂起问题
解决Apache Camel处理PGP解密时InputStream导致的挂起问题
嘿,我瞅了下你的代码,问题其实挺明显的——你压根儿没把InputStream的消息实际发送到direct:is端点上!这就导致你的路由一直等着消息进来,latch.await()就一直卡着,自然看起来像挂起了。
先给你捋下代码里的坑:
- 你创建了第二个
DefaultFluentProducerTemplate但没指定任何目标端点,也没发送,这完全是多余的代码 - 第一个构建好的ProducerTemplate没调用
.send()方法!DefaultFluentProducerTemplate.on(context).withBody(inputStream).to("direct:is")这行只是构建了发送模板,但没真正触发消息发送,路由当然一直空等
给你修正后的代码,你可以直接用:
CamelContext context = new DefaultCamelContext(); CountDownLatch latch = new CountDownLatch(1); context.addRoutes(new RouteBuilder() { public void configure() { from("direct:is") .unmarshal().pgp(secretKeyFileName, keyUserId, keyPassword) .process(exchange -> { // 把解密后的内容写入输出流 InputStream decryptedStream = exchange.getIn().getBody(InputStream.class); IOUtils.copy(decryptedStream, outputStream); latch.countDown(); }); } }); // 关键!调用send()实际发送消息到路由 DefaultFluentProducerTemplate.on(context) .withBody(inputStream) .to("direct:is") .send(); context.start(); try { // 加个超时时间,避免无限挂起 latch.await(5, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException("解密流程被中断", e); } finally { context.stop(); // 记得关闭流资源,避免泄漏 inputStream.close(); outputStream.close(); }
另外再给你几个小提醒:
- 确保你的PGP密钥文件路径正确,
keyUserId和keyPassword和密钥完全匹配,不然解密失败也会导致流程卡住 - InputStream是一次性读取的,别重复使用同一个流实例
- 最好用
try-with-resources语法来管理流和CamelContext,进一步避免资源泄漏
内容的提问来源于stack exchange,提问作者Anna
相关产品推荐
相关产品推荐

