検索

このコンテンツは選択した言語では利用できません。

Chapter 3. Apache Camel in Spring Boot

download PDF

3.1. Introduction to Camel Spring Boot

The Camel Spring Boot component provides auto configuration for Apache Camel. Auto-configuration of the Camel context auto-detects 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.

Every Camel Spring Boot application should use dependencyManagement with productized versions, see quickstart pom. Versions that are tagged later can be omitted to not override the versions from BOM.

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>io.fabric8</groupId>
			<artifactId>fabric8-project-bom-camel-spring-boot</artifactId>
			<version>${fabric8.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
</dependencyManagement>
Note

camel-spring-boot jar comes with the spring.factories file which allows you to add that dependency into your classpath and hence Spring Boot will automatically auto-configure Camel.

3.2. Introduction to Camel Spring Boot Starter

Apache Camel includes a Spring Boot starter module that allows you to develop Spring Boot applications using starters.

Note

For more details, see sample application in the source code.

To use the starter, add the following snippet to your Spring Boot pom.xml file:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-spring-boot-starter</artifactId>
</dependency>

The starter allows you to add 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");
    }
}

You can customize the Camel application in the application.properties or application.yml file. 

Camel Spring Boot now supports referring to bean by the id name in the configuration files (application.properties or yaml file) when you configure any of the Camel starter components. In the src/main/resources/application.properties (or yaml) file you can now easily configure the options on the Camel that refers to other beans by refering to the beans ID name. For example, the xslt component can refer to a custom bean using the bean ID as follows:

# refer to a custom bean by the id myExtensionFactory (@Bean("myExtensionFactory")

camel.component.xslt.saxon-extension-functions=myExtensionFactory

Which you can then create via Spring Boot @Bean annotation

    @Bean(name = "myExtensionFactory")

    public ExtensionFunctionDefinition myExtensionFactory() {

    }

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

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

3.3. Auto-configured Camel context

Camel 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.

For example, you can access the camelContext as shown below:

@Configuration
public class MyAppConfig {

  @Autowired
  CamelContext camelContext;

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

}

3.4. Auto-detecting Camel routes

Camel auto configuration collects all the RouteBuilder instances from the Spring context and automatically injects them into the CamelContext. It simplifies the process of creating new Camel route with the Spring Boot starter. You can create the routes by adding 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");
  }

}

To create a new route RouteBuilder bean in your @Configuration class, see below:

@Configuration
public class MyRouterConfiguration {

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

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

    };
  }
 
}

3.5. Camel properties

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

These properties are defined in application.properties file:  

route.from = jms:invoices

Use as system property

java -Droute.to=jms:processed.invoices -jar mySpringApp.jar

Use as placeholders in Camel route:

@Component
public class MyRouter extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from("{{route.from}}").to("{{route.to}}");
  }

}

3.6. Custom Camel context configuration

To perform operations on CamelContext bean created by Camel auto configuration, you need to register CamelContextConfiguration instance in your 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
      }
    };
  }

}
Note

The method CamelContextConfiguration and beforeApplicationStart(CamelContext) will be called before the Spring context is started, so the CamelContext instance 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.

3.7. Disabling JMX

To disable JMX of the auto-configured CamelContext use camel.springboot.jmxEnabled property as JMX is enabled by default.

For example, you could add the following property to your application.properties file:

camel.springboot.jmxEnabled = false

3.8. Auto-configured consumer and producer templates

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

@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 1000. You can change those values using the following Spring properties:

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

3.9. Auto-configured TypeConverter

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

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

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

}

3.10. Spring type conversion API bridge

Spring consist of  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. That 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:

@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.

3.11. Disabling type conversions features

To disable registering type conversion features of Camel Spring Boot such as TypeConverter instance or Spring bridge, set the camel.springboot.typeConversion property to false as shown below:

camel.springboot.typeConversion = false

3.12. Adding XML routes

By default, you can put Camel XML routes in the classpath under the directory camel, which camel-spring-boot will auto detect and include. From Camel version 2.17 onwards you can configure the directory name or disable this feature using the configuration option, as shown below:

// 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 be Camel XML routes and not CamelContext such as:

   <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>

When using Spring XML files with <camelContext>, you can configure Camel in the Spring XML file as well as in the application.properties file. For example, to set a name on Camel and turn On the stream caching, add:

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

3.13. Adding XML Rest-DSL

By default, you can put Camel Rest-DSL XML routes in the classpath under the directory camel-rest, which camel-spring-boot will auto detect and include. You can configure the directory name or disable this feature using the configuration option, as shown below:

// 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 be Camel XML rests and not CamelContext such as:

   <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>

3.14. Testing with Camel Spring Boot

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

When you have multiple Camel routes in different RouteBuilder classes, Camel Spring Boot will include all these routes. 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.

You can specify these patterns in your unit test classes as properties to @SpringBootTest annonation, 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 double asterisk, which matches with any leading package name. /Foo* means the class name must start with Foo, for example, FooRoute. You can run a test using following maven command:

mvn test -Dtest=FooTest

3.15. See Also

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

3.16.1. Using an external messaging broker.

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.

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);
Red Hat logoGithubRedditYoutubeTwitter

詳細情報

試用、購入および販売

コミュニティー

Red Hat ドキュメントについて

Red Hat をお使いのお客様が、信頼できるコンテンツが含まれている製品やサービスを活用することで、イノベーションを行い、目標を達成できるようにします。

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

© 2024 Red Hat, Inc.