Camel Components

Avro RPC

Since Camel 2.10

Both producer and consumer are supported

This component provides support for Apache Avro’s rpc, by providing producers and consumers endpoint for using avro over netty or http. Before Camel 3.2 this functionality was a part of camel-avro component.

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-avro-rpc</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The Avro RPC component supports the following options which are listed below.

Name Description Default Type

protocol (common)

The Avro protocol (org.apache.avro.Protocol) that defines the messages, such as the PROTOCOL field of a class generated by the Avro compiler. Set this option or protocolClassName: the endpoint fails to start without a protocol. Camel adds the packages of the protocol to the trusted packages of Avro, which apply to the whole JVM: see serializablePackages.

Protocol

protocolClassName (common)

The fully qualified name of the class that defines the protocol. For a class generated by the Avro compiler, its static PROTOCOL field is used; for any other class or interface, Avro reflection builds the protocol and reflectionProtocol is turned on. Ignored when protocol is set. Camel adds the package of the class to the trusted packages of Avro, which apply to the whole JVM: see serializablePackages.

String

protocolLocation (common)

The location of an Avro protocol file in JSON (.avpr), such as classpath:my-protocol.avpr or file:/path/my-protocol.avpr. Used when neither protocol nor protocolClassName is set. Records of the protocol use the classes generated by the Avro compiler when they are on the classpath. Camel adds the packages of the protocol to the trusted packages of Avro, which apply to the whole JVM: see serializablePackages.

String

reflectionProtocol (common)

Whether the protocol is a reflect protocol, built by Avro reflection from a Java interface, rather than one from classes generated by the Avro compiler. When true, the consumer and producer use the Avro reflect responder and requestor. Set it together with protocol: with protocolClassName it is turned on for a class without a PROTOCOL field.

false

boolean

uriAuthority (common)

Deprecated Deprecated: not used. The component sets it to the host and port of the endpoint URI, and a value set on the endpoint or the component has no effect. Deprecation note: Not used; the host and port of the endpoint URI are used instead.

String

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

singleParameter (consumer)

Whether the consumer sets the message body to the one parameter of the called message, instead of an Object array of all parameters. The endpoint fails to start if the message, or any message of the protocol when messageName is not set, does not have exactly one parameter.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

configuration (advanced)

A shared configuration that every endpoint copies as its starting point. The options of the endpoint URI override its values.

AvroConfiguration

serializablePackages (security)

Comma-separated list of additional packages that contain trusted Avro model classes. Avro 1.12+ validates classes resolved from schemas; Camel automatically trusts org.apache.avro for IPC and packages derived from the configured protocol. Use this option for any additional model packages not inferred from the protocol. Avro has one class validator for the whole JVM. A package trusted by one endpoint is trusted for all Avro class resolution in the JVM, by every endpoint, Avro data format and Camel context, and stays trusted until the JVM is restarted: stopping the endpoint or the route does not remove it.

String

Endpoint Options

The Avro RPC endpoint is configured using URI syntax:

avro:transport:host:port/messageName

With the following path and query parameters:

Path Parameters

Name Description Default Type

transport (common)

Required The transport: http or netty. With http, the consumer runs an Avro HTTP server on Jetty and the producer sends HTTP POST requests; with netty, both use the Avro Netty server and transceiver.

Enum values:

  • http

  • netty

AvroTransport

port (common)

Required The port number. The consumer listens on it, and the producer connects to it.

int

host (common)

Required The host name or IP address. The consumer binds its server to it, and the producer connects to it.

String

messageName (common)

The name of the protocol message to call or serve. The producer calls it unless the CamelAvroMessageName header is set. A consumer with a message name serves only that message; a consumer without one serves every message that no other consumer on the same host and port serves.

String

Query Parameters

Name Description Default Type

protocol (common)

The Avro protocol (org.apache.avro.Protocol) that defines the messages, such as the PROTOCOL field of a class generated by the Avro compiler. Set this option or protocolClassName: the endpoint fails to start without a protocol. Camel adds the packages of the protocol to the trusted packages of Avro, which apply to the whole JVM: see serializablePackages.

Protocol

protocolClassName (common)

The fully qualified name of the class that defines the protocol. For a class generated by the Avro compiler, its static PROTOCOL field is used; for any other class or interface, Avro reflection builds the protocol and reflectionProtocol is turned on. Ignored when protocol is set. Camel adds the package of the class to the trusted packages of Avro, which apply to the whole JVM: see serializablePackages.

String

protocolLocation (common)

The location of an Avro protocol file in JSON (.avpr), such as classpath:my-protocol.avpr or file:/path/my-protocol.avpr. Used when neither protocol nor protocolClassName is set. Records of the protocol use the classes generated by the Avro compiler when they are on the classpath. Camel adds the packages of the protocol to the trusted packages of Avro, which apply to the whole JVM: see serializablePackages.

String

reflectionProtocol (common)

Whether the protocol is a reflect protocol, built by Avro reflection from a Java interface, rather than one from classes generated by the Avro compiler. When true, the consumer and producer use the Avro reflect responder and requestor. Set it together with protocol: with protocolClassName it is turned on for a class without a PROTOCOL field.

false

boolean

uriAuthority (common)

Deprecated Deprecated: not used. The component sets it to the host and port of the endpoint URI, and a value set on the endpoint or the component has no effect. Deprecation note: Not used; the host and port of the endpoint URI are used instead.

String

singleParameter (consumer)

Whether the consumer sets the message body to the one parameter of the called message, instead of an Object array of all parameters. The endpoint fails to start if the message, or any message of the protocol when messageName is not set, does not have exactly one parameter.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

serializablePackages (security)

Comma-separated list of additional packages that contain trusted Avro model classes. Avro 1.12+ validates classes resolved from schemas; Camel automatically trusts org.apache.avro for IPC and packages derived from the configured protocol. Use this option for any additional model packages not inferred from the protocol. Avro has one class validator for the whole JVM. A package trusted by one endpoint is trusted for all Avro class resolution in the JVM, by every endpoint, Avro data format and Camel context, and stays trusted until the JVM is restarted: stopping the endpoint or the route does not remove it.

String

Message Headers

The Avro RPC component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelAvroMessageName (common)

Constant: AVRO_MESSAGE_NAME

The name of the protocol message to call. The producer reads it, and it takes precedence over the messageName of the endpoint. The consumer sets it to the name of the called message.

String

Message Body

The message body at each side of the Avro RPC component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

list (java.lang.Object[])

An Object array of the parameters of the called message, in the order of the protocol, with the message name in the CamelAvroMessageName header. With singleParameter the one parameter itself, such as a record.

  • With singleParameter=true: unknown

Consumer reply

any

The response of the message, of its type in the protocol, such as the record class; it is not converted, so text or a Map fails for a record. Ignored for a message with a null response.

Producer input

list, pojo, text or value

An Object array of the parameters of the message, in the order of the protocol, or the one parameter itself, such as a record. A java.util.List is not unpacked and a Map is not a record: build the parameter types of the protocol. The message name comes from the CamelAvroMessageName header, or else from the endpoint.

Producer output

unknown

The response of the message, of its type in the protocol, such as the record class; no body for a message with a null response.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Apache Avro Overview

Avro allows you to define message types and a protocol using a json like format and then generate java code for the specified types and messages. An example of how a schema looks like is below.

{"namespace": "org.apache.camel.avro.generated",
 "protocol": "KeyValueProtocol",

 "types": [
     {"name": "Key", "type": "record",
      "fields": [
          {"name": "key",   "type": "string"}
      ]
     },
     {"name": "Value", "type": "record",
      "fields": [
          {"name": "value",   "type": "string"}
      ]
     }
 ],

 "messages": {
     "put": {
         "request": [{"name": "key", "type": "Key"}, {"name": "value", "type": "Value"} ],
         "response": "null"
     },
     "get": {
         "request": [{"name": "key", "type": "Key"}],
         "response": "Value"
     }
 }
}

You can easily generate classes from a schema, using maven, ant etc. More details can be found at the Apache Avro documentation.

However, it doesn’t enforce a schema-first approach, and you can create schema for your existing classes. You can use existing protocol interfaces to make RCP calls. You should use interface for the protocol itself and POJO beans or primitive/String classes for parameter and result types. Here is an example of the class that corresponds to the schema above:

Java-only: protocol interface and POJO class definition for Avro RPC
package org.apache.camel.avro.reflection;

public interface KeyValueProtocol {
    void put(String key, Value value);
    Value get(String key);
}

class Value {
    private String value;
    public String getValue() { return value; }
    public void setValue(String value) { this.value = value; }
}

Note: Existing classes can be used only for RPC (see below), not in data format.

Usage

Using Avro RPC in Camel

As mentioned above, Avro also provides RPC support over multiple transports such as http and netty. Camel provides consumers and producers for these two transports.

avro:[transport]:[host]:[port][?options]

The supported transport values are currently http or netty.

You can specify the message name right in the URI:

avro:[transport]:[host]:[port][/messageName][?options]

For consumers, this allows you to have multiple routes attached to the same socket. Dispatching to the correct route will be done by the avro component automatically. Route with no messageName specified (if any) will be used as default.

The consumers on the same host and port share one Avro server, which the first consumer that starts creates with its transport, protocol and reflectionProtocol. A consumer on the same host and port with another transport, another protocol or another reflectionProtocol value fails to start; use another port for it.

The exchange pattern of a consumer follows the called message: InOnly for a message with a null response, else InOut. The exchangePattern option has no effect on the consumer.

When using camel producers for avro ipc, the "in" message body needs to contain the parameters of the operation specified in the avro protocol. The response will be added in the body of the "out" message.

In a similar manner when using camel avro consumers for avro ipc, the request parameters will be placed inside the "in" message body of the created exchange. Once the exchange is processed, the body of the "out" message will be sent as a response.

Note: By default, consumer parameters are wrapped into an array. If you’ve got only one parameter, since 2.12 you can use singleParameter URI option to receive it directly in the "in" message body without array wrapping.

The protocol

The endpoint needs the Avro protocol, from one of these options, in this order:

  • protocol: an org.apache.avro.Protocol instance, such as the PROTOCOL field of a class that the Avro compiler generated.

  • protocolClassName: the class of the protocol. For a class generated by the Avro compiler its PROTOCOL field is used; for any other class or interface, Avro reflection builds the protocol, and reflectionProtocol is turned on.

  • protocolLocation: an Avro protocol file in JSON (.avpr), such as classpath:key-value.avpr. Records of the protocol use the classes that the Avro compiler generated when they are on the classpath. An Avro IDL file (.avdl) is not supported: convert it to .avpr with the Avro tools first.

avro:netty:localhost:9000/get?protocolLocation=classpath:key-value.avpr

Trusted packages apply to the whole JVM

Avro validates the classes it loads for a schema, and only loads classes from trusted packages. Camel adds the packages of the protocol, protocolClassName or protocolLocation option, and the packages of the serializablePackages option, to these trusted packages.

Avro has one class validator for the whole JVM. So a package trusted by one endpoint is trusted for all Avro class resolution in the JVM: for every Avro RPC endpoint, every Avro data format and every Camel context in the same JVM. A trusted package stays trusted until the JVM is restarted; stopping the endpoint or the route does not remove it. Only add packages that hold your own Avro model classes.

Examples

An example of using camel avro producers via http:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("avro:http:localhost:{{avroport}}?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol")
    .to("log:avro");
        <route>
            <from uri="direct:start"/>
            <to uri="avro:http:localhost:{{avroport}}?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <to uri="log:avro"/>
        </route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: avro:http:localhost:{{avroport}}
            parameters:
              protocolClassName: org.apache.camel.avro.generated.KeyValueProtocol
        - to:
            uri: log:avro

In the example above you need to fill CamelAvroMessageName header.

You can use the following syntax to call constant messages:

  • Java

  • XML

  • YAML

from("direct:start")
    .to("avro:http:localhost:{{avroport}}/put?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol")
    .to("log:avro");
        <route>
            <from uri="direct:start"/>
            <to uri="avro:http:localhost:{{avroport}}/put?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <to uri="log:avro"/>
        </route>
- route:
    from:
      uri: direct:start
      steps:
        - to:
            uri: avro:http:localhost:{{avroport}}/put
            parameters:
              protocolClassName: org.apache.camel.avro.generated.KeyValueProtocol
        - to:
            uri: log:avro

An example of consuming messages using camel avro consumers via netty:

  • Java

  • XML

  • YAML

from("avro:netty:localhost:{{avroport}}?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol")
    .choice()
        .when(simple("${header.CamelAvroMessageName} == 'put'"))
            .process("putProcessor")
        .when(simple("${header.CamelAvroMessageName} == 'get'"))
            .process("getProcessor");
        <route>
            <from uri="avro:netty:localhost:{{avroport}}?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <choice>
                <when>
                    <simple>${header.CamelAvroMessageName} == 'put'</simple>
                    <process ref="putProcessor"/>
                </when>
                <when>
                    <simple>${header.CamelAvroMessageName} == 'get'</simple>
                    <process ref="getProcessor"/>
                </when>
            </choice>
        </route>
- route:
    from:
      uri: avro:netty:localhost:{{avroport}}
      parameters:
        protocolClassName: org.apache.camel.avro.generated.KeyValueProtocol
      steps:
        - choice:
            when:
              - simple: "${header.CamelAvroMessageName} == 'put'"
                steps:
                  - process:
                      ref: putProcessor
              - simple: "${header.CamelAvroMessageName} == 'get'"
                steps:
                  - process:
                      ref: getProcessor

You can set up two distinct routes to perform the same task:

  • Java

  • XML

  • YAML

from("avro:netty:localhost:{{avroport}}/put?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol")
    .process("putProcessor");

from("avro:netty:localhost:{{avroport}}/get?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol&singleParameter=true")
    .process("getProcessor");
        <route>
            <from uri="avro:netty:localhost:{{avroport}}/put?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol"/>
            <process ref="putProcessor"/>
        </route>
        <route>
            <from uri="avro:netty:localhost:{{avroport}}/get?protocolClassName=org.apache.camel.avro.generated.KeyValueProtocol&amp;singleParameter=true"/>
            <process ref="getProcessor"/>
        </route>
- route:
    from:
      uri: avro:netty:localhost:{{avroport}}/put
      parameters:
        protocolClassName: org.apache.camel.avro.generated.KeyValueProtocol
      steps:
        - process:
            ref: putProcessor
- route:
    from:
      uri: avro:netty:localhost:{{avroport}}/get
      parameters:
        protocolClassName: org.apache.camel.avro.generated.KeyValueProtocol
        singleParameter: true
      steps:
        - process:
            ref: getProcessor

In the example above, get takes only one parameter, so singleParameter is used and getProcessor will receive the Key directly in the body, while putProcessor will receive an array of size 2 with the Key and the Value as its contents.

Avro via HTTP SPI

The Avro RPC component offers the org.apache.camel.component.avro.spi.AvroRpcHttpServerFactory service provider interface (SPI) so that various platforms can provide their own implementation based on their native HTTP server.

The default implementation available in org.apache.camel:camel-avro-jetty is based on org.apache.avro:avro-ipc-jetty.