Camel 在运行时出现无效负载异常:取消编组Jaxb对象时引发了类型错误的无主体可用

pftdvrlh  于 2022-11-07  发布在  Apache
关注(0)|答案(3)|浏览(201)

我正在通过Java将JAXB对象发送到Rabbit MQ。

JAXBContext jaxbContext = JAXBContext.newInstance(MyDTO.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

    // output pretty printed
    jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
     java.io.StringWriter sw = new StringWriter();
     jaxbMarshaller.marshal(deliveryrequest, sw);

    ConnectionFactory factory = new ConnectionFactory() ;

    //TODO change the hardcoding to the properties file
    factory.setHost("rabbitmq.host.net");
    factory.setUsername("user");
    factory.setPassword("pass");
    Channel channel ;
    Connection connection;

    Map<String, Object> args = new HashMap<String, Object>(); 
    String haPolicyValue = "all"; 
    args.put("x-ha-policy", haPolicyValue); 

    connection = factory.newConnection();
    channel = connection.createChannel();
    //TODO change the hardcoding to the properties file
    channel.queueDeclare("upload.com.some.queue", true, false, false, args);
    //TODO change the hardcoding to the properties file
    channel.basicPublish("com.some.exchange", "someroutingKey", 
            new AMQP.BasicProperties.Builder().contentType("text/plain")
            .deliveryMode(2).priority(1).userId("guest").build(),
            sw.toString().getBytes());

我在不同的应用程序中使用Camel来阅读此内容。

<camel:route id="myRoute">
        <camel:from uri="RabbitMQEndpoint" />
        <camel:to uri="bean:MyHandler" />
    </camel:route>

处理程序正在使用在camel端重做的Jaxb对象

@Handler
 public void handleRequest(MyDTO dto) throws ParseException {

我得到了我没有想到会得到的错误。

Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: byte[] to the required type: com.mycompany.MyDTO with value [B@1b8d3e42
at org.apache.camel.impl.converter.BaseTypeConverterRegistry.mandatoryConvertTo(BaseTypeConverterRegistry.java:181)
at org.apache.camel.impl.MessageSupport.getMandatoryBody(MessageSupport.java:99)

解表示赞赏。

ebdffaop

ebdffaop1#

您来自rabbit的消息正文类型是byte[],而您要调用MyDTO类型的bean。您的类型不匹配。Camel找不到可以将消息正文从byte[]转换为MyDTO类型的类型转换器。
来自Rabbit的byte[]数据是XML格式的吗?MyDTO类上是否有JAXB注解,以便可以使用JAXB将其从xml编组到Java?

iqxoj9l9

iqxoj9l92#

这是Jaxb对象。我的印象是,如果我移动出版商太 Camel 。事情会得到解决。
我将发布者更改为以下版本。

@EndpointInject(context = "myContext" , uri = "direct:myRoute")
    private ProducerTemplate sendAMyContext;

在我调用方法中

@Override
public MyResponse putMyCall(
        MyRequest myrequest) {

        sendMyContext.sendBody(myrequest);

我的 Camel 路线很简单

<camel:camelContext id="MyContext" autoStartup="true" xmlns="http://camel.apache.org/schema/spring">

    <camel:endpoint id="myQueue" uri="${my.queue.1}" />

        <camel:route>
        <camel:from uri="direct:myRoute"/>
        <camel:to uri="bean:mySendHandler"/>
        <camel:convertBodyTo type="String"></camel:convertBodyTo>
        <camel:to uri="ref:myQueue" />
    </camel:route>

</camel:camelContext>

我添加了将Jaxb对象转换为字符串的处理程序(由于错误)

public class MySendHandler {

 @Handler
 public String myDelivery( MyRequest myRequest) throws ParseException, JAXBException {

         JAXBContext jaxbContext = JAXBContext.newInstance(MyRequest.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        java.io.StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(attributedDeliveryRequest, sw);

     return sw.toString();

  }

还是同样的错误

[SpringAMQPConsumer.SpringAMQPExecutor-1] WARN  org.springframework.amqp.support.converter.JsonMessageConverter (JsonMessageConverter.java:111) - Could not convert incoming message with content-type [text/plain]
SpringAMQPConsumer.SpringAMQPExecutor-1] ERROR org.apache.camel.processor.DefaultErrorHandler (MarkerIgnoringBase.java:161) - Failed delivery for (MessageId: ID-Con ExchangeId: ID-65455-1380873539452-3-2). 
Exhausted after delivery attempt: 1 caught: org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: <XML>]
org.apache.camel.CamelExecutionException: Exception occurred during execution on the exchange: Exchange[Message: <xml>
    .....
Caused by: org.apache.camel.InvalidPayloadException: No body available of type: MyDTO but has value: [B@7da255c of type: byte[] on: Message: <xml>
. Caused by: [org.apache.camel.NoTypeConversionAvailableException - No type converter available to convert from type: byte[] to the required type: MyDeliveryDTO with value [B@7da255c]
    at org.apache.camel.impl.MessageSupport.getMandatoryBody(MessageSupport.java:101)
    at org.apache.camel.builder.ExpressionBuilder$38.evaluate(ExpressionBuilder.java:934)
    ... 74 more
Caused by: org.apache.camel.NoTypeConversionAvailableException: No type converter available to convert from type: byte[] to the required type: MyDTO with value [B@7da255c
    at org.apache.camel.impl.converter.BaseTypeConverterRegistry.mandatoryConvertTo(BaseTypeConverterRegistry.java:181)
    at org.apache.camel.impl.MessageSupport.getMandatoryBody(MessageSupport.java:99)
    ... 75 more

我的接收 Camel 路线如下

<camel:route id="processVDelivery">
            <camel:from uri="aVEndpoint" />
            <camel:to uri="bean:myDataHandler" />
        </camel:route>

我补充道

<camel:convertBodyTo type="String"></camel:convertBodyTo>

它给了我一个错误,它不能将它从字符串转换为对象
添加此

<camel:unmarshal></camel:unmarshal>

-------------------------

这个问题的答案是你的mashaller必须是类路径的一部分

---------------------------------

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${jackson.version}</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>${jackson.version}</version>
    </dependency>

-------您也可以使用dataformat自订封送处理器

<camel:dataFormats>

                   <camel:jaxb id="name" contextPath="com.something"/>

    </camel:dataFormats

请确保将jaxb.index文件保存在com.something包中,并使用根级别的Jaxb对象名称

von4xj4u

von4xj4u3#

使用带 Spring Boot 的Camel Rest

rest("/authenticate")
                .post()
                .route()
                .setHeader("Content-Type", constant("application/json"))
                .setHeader("Accept", constant("application/json"))
                .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                  .process(exchange -> {
        org.apache.camel.TypeConverter tc = exchange.getContext().getTypeConverter();
String str_value = tc.convertTo(String.class, exchange.getIn().getBody());
             System.err.println(str_value);
              exchange.getOut().setBody(str_value);
      })
                //.removeHeader(Exchange.HTTP_URI)
                .to("http://localhost:8082/authenticate?bridgeEndpoint=true")
                  //.convertBodyTo(DTO.class)
                .log("Boo!")
                .end()
                .endRest();

相关问题