How to Choose camel auto?

Author: wenzhang1

Sep. 02, 2024

CamelContext Auto Configuration - Apache Camel

Under these runtimes then the auto configuration is performed by shared code from the camel-main JAR to ensure the configuration is similar on these runtimes.

CAMEL are exported all over the world and different industries with quality first. Our belief is to provide our customers with more and better high value-added products. Let's create a better future together.

The auto configuration is executed in several steps:

Configure optional services that has been registering in the Registry

Configure CamelContext (and more such as components) from properties from external sources like application.properties|yaml

This is used for configuring the standard set of options (more than 100 options) which is listed in the Camel Main Options table at Camel Main .

Auto configuration of Optional Services

After configuring the standard options, then Camel will look in the Registry for custom services to be used. For example to plugin a custom UnitOfWorkFactory.

The services can be anything that can be plugged into Camel (typically services that implement an SPI interface org.apache.camel.spi).

The following SPI services, can only a single instance (singleton) be in the Registry.

SPI Description

AsyncProcessorAwaitManager

To use a custom async processor await manager

BacklogTracer

To use a custom backlog tracer

ClassResolver

To use a custom class resolver (only needed if you run Camel on a special application server to deal with classloading)

Debugger

To use a custom debugger

EventFactory

To use a custom event notifier factory

ExchangeFactory

To use a custom exchange factory

ExecutorServiceManager

To use a custom thread pool manager

FactoryFinderResolver

To use a custom factory finder resolver (only needed if you run Camel on a special application server to deal with classloading)

HealthCheckRegistry

To use a custom health check registry

InflightRepository

To use a custom inflight repository

ManagementObjectNameStrategy

To use a custom JMX MBean object naming

ManagementStrategy

To use a custom JMX management strategy

MessageHistoryFactory

To use a custom factory for message history

ModelJAXBContextFactory

To use a custom JAXBContext factory (only needed if you run Camel on a special application server to deal with JAXB classloading)

NodeIdFactory

To use a custom factory for creating auto generated node ids

ProcessorFactory

To use a custom factory for creating EIP processors

PropertiesComponent

To use a custom properties component

ReactiveExecutor

To use a custom reactive engine in the Camel routing engine

RouteController

To use a custom route controller

RuntimeEndpointRegistry

To use a custom runtime endpoint registry

ShutdownStrategy

To use a custom shutdown strategy

StartupStepRecorder

To use a custom startup recorder

ThreadPoolFactory

To use a custom thread pool factory

UnitOfWorkFactory

To use a custom unit of work factory

UuidGenerator

To use a custom uuid generator

For the following SPI services, there can be multiple (1..n) implementations in the Registry.

SPIs Description

CamelClusterService

Adds all the custom camel-cluster services

EndpointStrategy

Adds all the custom endpoint strategies

EventNotifier

Adds all the custom event notifiers

GlobalSSLContextParametersSupplier

To use a custom supplier for JSSE (Java Security)

InterceptStrategy

Adds all the custom intercept strategies

LifecycleStrategy

Adds all the custom lifecycle strategies

LogListener

Adds all the log listeners

ModelLifecycleStrategy

Adds all the custom model lifecycle strategies

RoutePolicyFactory

Adds all the custom route policy factories

ServiceRegistry

Adds all the custom camel-cloud service registries

ThreadPoolProfile

Adds all the thread pool profiles

TypeConverters

Adds all the custom type converters

Chapter 6. Running Apache Camel application in Spring ...

The Apache Camel Spring Boot component automatically configures Camel context for Spring Boot. Auto-configuration of the Camel context automatically detects the Camel routes available in the Spring context and registers the key Camel utilities such as producer template, consumer template, and the type converter as beans. The Apache Camel component includes a Spring Boot starter module that allows you to develop Spring Boot applications by using starters.

6.1. Introduction to the Camel Spring Boot component

Every Camel Spring Boot application must use the dependencyManagement element in the project&#;s pom.xml to specify the productized versions of the dependencies. These dependencies are defined in the Red Hat Fuse BOM and are supported for the specific version of Red Hat Fuse. You can omit the version number attribute for the additional starters so as not to override the versions from BOM. See quickstart pom for more information.

Example

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.jboss.redhat-fuse</groupId>
			<artifactId>fuse-springboot-bom</artifactId>
			<version>${fuse.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

Note

The camel-spring-boot jar contains with the spring.factories file which allows you to add that dependency to your classpath so Spring Boot will automatically configure Camel context.

6.2. Introduction to the Camel Spring Boot starter module

Starters are the Apache Camel modules that are intended to be used in Spring Boot applications. There is a camel-xxx-starter module for each Camel component (with a few exceptions listed in the Section 6.3, &#;List of the Camel components that do not have starter modules&#; section).

Starters meet the following requirements:

  • Allow auto-configuration of the component by using the native Spring Boot configuration system which is compatible with IDE tooling.
  • Allow auto-configuration of data formats and languages.
  • Manage transitive logging dependencies to integrate with the Spring Boot logging system.
  • Include additional dependencies and align transitive dependencies to minimize the effort of creating a working Spring Boot application.

Each starter has its own integration test in tests/camel-itest-spring-boot, that verifies the compatibility with the current release of Spring Boot.

Note

For more details, see link: Apache Camel Spring-Boot examples.

6.3. List of the Camel components that do not have starter modules

For more information, please visit camel auto.

The following components do not have starter modules because of compatibility issues:

  • camel-blueprint

    (intended for OSGi only)
  • camel-cdi

    (intended for CDI only)
  • camel-core-osgi

    (intended for OSGi only)
  • camel-ejb

    (intended for JEE only)
  • camel-eventadmin

    (intended for OSGi only)
  • camel-ibatis

    (camel-mybatis-starter is included)
  • camel-jclouds

  • camel-mina

    (camel-mina2-starter is included)
  • camel-paxlogging

    (intended for OSGi only)
  • camel-quartz

    (camel-quartz2-starter is included)
  • camel-spark-rest

  • camel-openapi-java

    (camel-openapi-java-starter is included)

6.4. Using Camel Spring Boot starter

Apache Camel provides a starter module that allows you to quickly get started developing Spring Boot applications.

Procedure

  1. Add the following dependency to your Spring Boot pom.xml file:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-boot-starter</artifactId>
    </dependency>
  2. Add the classes with your Camel routes as shown in the snippet below. Once these routes are added to the class path the routes are started automatically.

    package com.example;
    
    import org.apache.camel.builder.RouteBuilder;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyRoute extends RouteBuilder {
    
        @Override
        public void configure() throws Exception {
            from("timer:foo")
              .to("log:bar");
        }
    }
  3. Optional. To keep the main thread blocked so that Camel stays up, do one of the following.

    1. Include the spring-boot-starter-web dependency,
    2. Or add camel.springboot.main-run-controller=true to your application.properties or application.yml file.

      You can customize the Camel application in the application.properties or application.yml file with camel.springboot.* properties.

  4. Optional. To refer to a custom bean by using the bean&#;s ID name, configure the options in the src/main/resources/application.properties (or the application.yml) file. The following example shows how the xslt component refers to a custom bean by using the bean ID.

    1. Refer to a custom bean by the id myExtensionFactory.

      camel.component.xslt.saxon-extension-functions=myExtensionFactory
    2. Then create the custom bean using Spring Boot @Bean annotation.

      @Bean(name = "myExtensionFactory")
      public ExtensionFunctionDefinition myExtensionFactory() {
          }

      Or, for a Jackson ObjectMapper, in the camel-jackson data-format:

      camel.dataformat.json-jackson.object-mapper=myJacksonMapper

6.5. About Camel context auto-configuration for Spring Boot

Camel Spring Boot auto-configuration provides a CamelContext instance and creates a SpringCamelContext. It also initializes and performs shutdown of that context. This Camel context is registered in the Spring application context under camelContext bean name and you can access it like other Spring bean. You can access the camelContext as shown below.

Example

@Configuration
public class MyAppConfig {

  @Autowired
  CamelContext camelContext;

  @Bean
  MyService myService() {
    return new DefaultMyService(camelContext);
  }

}

6.6. Auto-detecting Camel routes in Spring Boot Applications

Camel auto-configuration collects all the RouteBuilder instances from the Spring context and automatically injects them into the CamelContext. This simplifies the process of creating a new Camel route with the Spring Boot starter. You can create the routes as follows:

Example

Add the @Component annotated class to your classpath.

@Component
public class MyRouter extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from("jms:invoices").to("file:/invoices");
  }

}

Or create a new route RouteBuilder bean in your @Configuration class.

@Configuration
public class MyRouterConfiguration {

  @Bean
  RoutesBuilder myRouter() {
    return new RouteBuilder() {

      @Override
      public void configure() throws Exception {
        from("jms:invoices").to("file:/invoices");
      }

    };
  }
 
}

6.7. Configuring Camel properties for Camel Spring Boot auto-configuration

Spring Boot auto-configuration connects to the Spring Boot external configuration such as properties placeholders, OS environment variables, or system properties with Camel properties support.

Procedure

  1. Define the properties either in the application.properties file:  

    route.from = jms:invoices

    Or set the Camel properies as the system properties, for example:

    java -Droute.to=jms:processed.invoices -jar mySpringApp.jar
  2. Use the configured properties as placeholders in Camel route as follows.

    @Component
    public class MyRouter extends RouteBuilder {
    
      @Override
      public void configure() throws Exception {
        from("{{route.from}}").to("{{route.to}}");
      }
    
    }

6.8. Configuring custom Camel context

To perform operations on the CamelContext bean created by Camel Spring Boot auto-configuration, register a CamelContextConfiguration instance in your Spring context.

Procedure

  • Register an instance of CamelContextConfiguration in the Spring context as shown below.

    @Configuration
    public class MyAppConfig {
    
      ...
    
      @Bean
      CamelContextConfiguration contextConfiguration() {
        return new CamelContextConfiguration() {
          @Override
          void beforeApplicationStart(CamelContext context) {
            // your custom configuration goes here
          }
        };
      }
    
    }

The CamelContextConfiguration and beforeApplicationStart(CamelContext) methods are called before the Spring context is started, so the CamelContext instance that is passed to this callback is fully auto-configured. You can add many instances of CamelContextConfiguration into your Spring context and all of them will be executed.

6.9. Disabling JMX in the auto-configured CamelContext

To disable JMX in the auto-configured CamelContext, you can use the camel.springboot.jmxEnabled property as JMX is enabled by default.

Procedure

  • Add the following property to your application.properties file and set it to false:

    camel.springboot.jmxEnabled = false

6.10. Injecting auto-configured consumer and producer templates into Spring-managed beans

Camel auto-configuration provides pre-configured ConsumerTemplate and ProducerTemplate instances. You can inject them into your Spring-managed beans.

Example

@Component
public class InvoiceProcessor {

  @Autowired
  private ProducerTemplate producerTemplate;

  @Autowired
  private ConsumerTemplate consumerTemplate;
  public void processNextInvoice() {
    Invoice invoice = consumerTemplate.receiveBody("jms:invoices", Invoice.class);
    ...
    producerTemplate.sendBody("netty-http:http://invoicing.com/received/" + invoice.id());
  }

}

By default consumer templates and producer templates come with the endpoint cache sizes set to . You can change these values by setting the following Spring properties to the desired cache size, for example:

camel.springboot.consumerTemplateCacheSize = 100
camel.springboot.producerTemplateCacheSize = 200

6.11. About the auto-configured TypeConverter in the Spring context

Camel auto-configuration registers a TypeConverter instance named typeConverter in the Spring context.

Example

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

  public long parseInvoiceValue(Invoice invoice) {
    String invoiceValue = invoice.grossValue();
    return typeConverter.convertTo(Long.class, invoiceValue);
  }

}

6.12. Spring type conversion API bridge

Spring consist of a powerful type conversion API. Spring API is similar to the Camel type converter API. Due to the similarities between the two APIs Camel Spring Boot automatically registers a bridge converter (SpringTypeConverter) that delegates to the Spring conversion API. This means that out-of-the-box Camel will treat Spring Converters similar to Camel.

This allows you to access both Camel and Spring converters using the Camel TypeConverter API, as shown below:

Example

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

  public UUID parseInvoiceId(Invoice invoice) {
    // Using Spring's StringToUUIDConverter
    UUID id = invoice.typeConverter.convertTo(UUID.class, invoice.getId());
  }

}

Here, Spring Boot delegates conversion to the Spring&#;s ConversionService instances available in the application context. If no ConversionService instance is available, Camel Spring Boot auto-configuration creates an instance of ConversionService.

6.13. Disabling type conversions features

To disable the Camel Spring Boot type conversion features, set the camel.springboot.typeConversion property to false. When this property is set to false, the auto-configuration does not register a type converter instance and does not enable the delegation of type conversion to the Spring Boot type conversion API.

Procedure

  • To disable the type conversion features of Camel Spring Boot component, set the camel.springboot.typeConversion property to false as shown below:

    camel.springboot.typeConversion = false

6.14. Adding XML routes to the classpath for auto-configuration

By default, the Camel Spring Boot component auto-detects and includes the Camel XML routes that are in the classpath in the camel directory. You can configure the directory name or disable this feature using the configuration option.

Procedure

  • Configure the Camel Spring Boot XML routes in the classpath as follows.

    // turn off
    camel.springboot.xmlRoutes = false
    // scan in the com/foo/routes classpath
    camel.springboot.xmlRoutes = classpath:com/foo/routes/*.xml

    Note

    The XML files should define the Camel XML route elements and not CamelContext elements, for example:

       <routes xmlns="http://camel.apache.org/schema/spring">
            <route id="test">
                <from uri="timer://trigger"/>
                <transform>
                    <simple>ref:myBean</simple>
                </transform>
                <to uri="log:out"/>
            </route>
        </routes>

Using Spring XML files

To use Spring XML files with the <camelContext>, you can configure a Camel context in the Spring XML file or in the application.properties file. To set the name of the Camel context and turn on the stream caching, add the following in the application.properties file:

camel.springboot.name = MyCamel
camel.springboot.stream-caching-enabled=true

6.15. Adding XML Rest-DSL Routes for auto-configuration

The Camel Spring Boot component auto-detects and embeds the Camel Rest-DSL XML routes that are added in the classpath under the camel-rest directory. You can configure the directory name or disable this feature using the configuration option.

Procedure

  • Configure the Camel Spring Boot Rest-DSL XML routes in the classpath as follows.

    // turn off
    camel.springboot.xmlRests = false
    // scan in the com/foo/routes classpath
    camel.springboot.xmlRests = classpath:com/foo/rests/*.xml

    Note

    The Rest-DSL XML files should define the Camel XML REST elements and not CamelContext elements, for example:

       <rests xmlns="http://camel.apache.org/schema/spring">
          <rest>
             <post uri="/persons">
                <to uri="direct:postPersons"/>
             </post>
             <get uri="/persons">
                <to uri="direct:getPersons"/>
             </get>
             <get uri="/persons/{personId}">
                 <to uri="direct:getPersionId"/>
             </get>
             <put uri="/persons/{personId}">
                 <to uri="direct:putPersionId"/>
             </put>
             <delete uri="/persons/{personId}">
                 <to uri="direct:deletePersionId"/>
             </delete>
          </rest>
        </rests>

6.16. Testing with Camel Spring Boot

When Camel runs on the Spring Boot, Spring Boot automatically embeds Camel and all its routes, which are annotated with @Component. When testing with Spring Boot use @SpringBootTest instead of @ContextConfiguration to specify which configuration class to use.

When you have multiple Camel routes in different RouteBuilder classes, the Camel Spring Boot component automatically embeds all these routes when running the application. Hence, when you wish to test routes from only one RouteBuilder class you can use the following patterns to include or exclude which RouteBuilders to enable:

  • java-routes-include-pattern: Used for including RouteBuilder classes that match the pattern.
  • java-routes-exclude-pattern: Used for excluding RouteBuilder classes that match the pattern. Exclude takes precedence over include.

Procedure

  1. Specify the include or exclude patterns in your unit test classes as properties to @SpringBootTest annotation, as shown below:

    @RunWith(CamelSpringBootRunner.class)
    @SpringBootTest(classes = {MyApplication.class);
       properties = {"camel.springboot.java-routes-include-pattern=**/Foo*"})
    public class FooTest {

    In the FooTest class, the include pattern is **/Foo*, which represents an Ant style pattern. Here, the pattern starts with a double asterisk, which matches with any leading package name. /Foo* means the class name must start with Foo, for example, FooRoute.

  2. Run the test using the following maven command:

    mvn test -Dtest=FooTest

Additional Resources

  • Configuring Camel
  • Component
  • Endpoint
  • Getting Started

6.17. Using Spring Boot, Apache Camel and external messaging brokers

Fuse uses external messaging brokers. See Supported Configurations for more information about the supported broker, client and Camel component combinations.

The Camel component must be connected to the JMS connection-factory. The example below shows how to connect the camel-amqp component to a JMS connection-factory.

Contact us to discuss your requirements of agm car battery technology. Our experienced sales team can help you identify the options that best suit your needs.

import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.apache.camel.component.amqp.AMQPComponent;
import org.apache.qpid.jms.JmsConnectionFactory;
...

AMQPComponent amqpComponent(AMQPConfiguration config) {
       JmsConnectionFactory qpid = new JmsConnectionFactory(config.getUsername(), config.getPassword(), "amqp://"+ config.getHost() + ":" + config.getPort());
       qpid.setTopicPrefix("topic://");

       PooledConnectionFactory factory = new PooledConnectionFactory();
       factory.setConnectionFactory(qpid);

AMQPComponent amqpcomp = new AMQPComponent(factory);

48

0

Comments

Please Join Us to post.

0/2000

All Comments ( 0 )

Guest Posts

If you are interested in sending in a Guest Blogger Submission,welcome to write for us!

Your Name: (required)

Your Email: (required)

Subject:

Your Message: (required)