使用 BeanIO 和 Apache Camel 解组 InputStream
Unmarshal InputStream using BeanIO and Apache Camel
我有一个接收文件并将其发送到 Camel 路由的服务。在那条路线上,我想使用 BeanIO 解组该文件,但它无法识别 InputStream 类型的输入。
@RestController
@RequestMapping(value = "/file")
public class FileController {
@Autowired
private CamelContext camelContext;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
ProducerTemplate template = camelContext.createProducerTemplate();
template.sendBody("direct:routeTest", new ByteArrayInputStream(multipartFile.getBytes()));
}
}
@Component
public class SampleRouter extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:routeTest")
.log("${body}")
.to("dataformat:beanio:unmarshal?mapping=mapping.xml&streamName=testFile")
.process(msg -> msg.getIn()
.getBody(List.class)
.forEach(o -> {...}))
.end();
}
}
我已经测试了使用 File 组件读取文件并将结果发送到 BeanIO 组件的路由。在那种情况下它有效。
如何在 Apache Camel 上将 BeanIO 与 InputStream 类型的输入一起使用?是否有任何组件可以将我的 InputStream 转换为与 BeanIO 组件兼容的东西?
正如 mgyongyosi 所说,当 .log("${body}")
读取流时,位置会转到它的末尾。为了解决这个问题,我们可以在读取后重置 InputStream 的位置:
from("direct:routeTest")
.log("${body}")
.process(exchange -> ((InputStream) exchange.getIn().getBody()).reset())
.to("dataformat:beanio:unmarshal?mapping=mapping.xml&streamName=testFile")
或删除行 .log("${body}")
.
其他解决方案可以是将 .streamCaching()
添加到路线中。然后你可以多次读取同一个流。 Official documentation
我有一个接收文件并将其发送到 Camel 路由的服务。在那条路线上,我想使用 BeanIO 解组该文件,但它无法识别 InputStream 类型的输入。
@RestController
@RequestMapping(value = "/file")
public class FileController {
@Autowired
private CamelContext camelContext;
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public void upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {
ProducerTemplate template = camelContext.createProducerTemplate();
template.sendBody("direct:routeTest", new ByteArrayInputStream(multipartFile.getBytes()));
}
}
@Component
public class SampleRouter extends RouteBuilder {
@Override
public void configure() throws Exception {
from("direct:routeTest")
.log("${body}")
.to("dataformat:beanio:unmarshal?mapping=mapping.xml&streamName=testFile")
.process(msg -> msg.getIn()
.getBody(List.class)
.forEach(o -> {...}))
.end();
}
}
我已经测试了使用 File 组件读取文件并将结果发送到 BeanIO 组件的路由。在那种情况下它有效。
如何在 Apache Camel 上将 BeanIO 与 InputStream 类型的输入一起使用?是否有任何组件可以将我的 InputStream 转换为与 BeanIO 组件兼容的东西?
正如 mgyongyosi 所说,当 .log("${body}")
读取流时,位置会转到它的末尾。为了解决这个问题,我们可以在读取后重置 InputStream 的位置:
from("direct:routeTest")
.log("${body}")
.process(exchange -> ((InputStream) exchange.getIn().getBody()).reset())
.to("dataformat:beanio:unmarshal?mapping=mapping.xml&streamName=testFile")
或删除行 .log("${body}")
.
其他解决方案可以是将 .streamCaching()
添加到路线中。然后你可以多次读取同一个流。 Official documentation