이 콘텐츠는 선택한 언어로 제공되지 않습니다.
Red Hat build of Apache Camel for Spring Boot Reference
Red Hat build of Apache Camel for Spring Boot Reference
Abstract
Preface 링크 복사링크가 클립보드에 복사되었습니다!
Making open source more inclusive
Red Hat is committed to replacing problematic language in our code, documentation, and web properties. We are beginning with these four terms: master, slave, blacklist, and whitelist. Because of the enormity of this endeavor, these changes will be implemented gradually over several upcoming releases.
Chapter 1. Component Starters 링크 복사링크가 클립보드에 복사되었습니다!
Camel Spring Boot supports the following Camel artifacts as Spring Boot Starters:
The BOM for Red Hat build of Apache Camel for Camel Spring Boot lists both supported and unsupported components. See Component Starters for the latest list of supported components.
| Component | Artifact | Description | Support on IBM Power and IBM Z |
|---|---|---|---|
| camel-amqp-starter | Messaging with AMQP protocol using Apache QPid Client. | Yes | |
| camel-aws2-cw-starter | Sending metrics to AWS CloudWatch using AWS SDK version 2.x. | Yes | |
| camel-aws2-ddb-starter | Store and retrieve data from AWS DynamoDB service using AWS SDK version 2.x. | Yes | |
| camel-aws2-kinesis-starter | Consume and produce records from and to AWS Kinesis Streams using AWS SDK version 2.x. | Yes | |
| camel-aws2-lambda-starter | Manage and invoke AWS Lambda functions using AWS SDK version 2.x. | Yes | |
| camel-aws2-s3-starter | Store and retrieve objects from AWS S3 Storage Service using AWS SDK version 2.x. | Yes | |
| camel-aws2-sns-starter | Send messages to an AWS Simple Notification Topic using AWS SDK version 2.x. | Yes | |
| camel-aws2-sqs-starter | Send and receive messages to/from AWS SQS service using AWS SDK version 2.x. | Yes | |
| camel-aws-secrets-manager-starter | Manage secrets using AWS Secrets Manager. | Yes | |
| camel-azure-key-vault-starter | Manage secrets and keys in Azure Key Vault Service | Yes | |
| camel-azure-servicebus-starter | Send and receive messages to/from Azure Event Bus. | Yes | |
| camel-azure-storage-blob-starter | Store and retrieve blobs from Azure Storage Blob Service using SDK v12. | Yes | |
| camel-azure-storage-queue-starter | The azure-storage-queue component is used for storing and retrieving the messages to/from Azure Storage Queue using Azure SDK v12. | Yes | |
| camel-bean-starter | Invoke methods of Java beans stored in Camel registry. | Yes | |
| camel-bean-validator-starter | Validate the message body using the Java Bean Validation API. | Yes | |
| camel-browse-starter | Inspect the messages received on endpoints supporting BrowsableEndpoint. | Yes | |
| camel-cassandraql-starter | Integrate with Cassandra 2.0 using the CQL3 API (not the Thrift API). Based on Cassandra Java Driver provided by DataStax. | Yes | |
| camel-cics-starter | Interact with CICS® general-purpose transaction processing subsystem. | No | |
| camel-controlbus-starter | Manage and monitor Camel routes. | Yes | |
| camel-cron-starter | A generic interface for triggering events at times specified through the Unix cron syntax. | Yes | |
| camel-crypto-starter | Sign and verify exchanges using the Signature Service of the Java Cryptographic Extension (JCE). | Yes | |
| camel-cxf-soap-starter | Expose SOAP WebServices using Apache CXF or connect to external WebServices using CXF WS client. | Yes | |
| camel-cxf-rest-starter | Expose JAX-RS REST services using Apache CXF or connect to external REST services using CXF REST client. | Yes | |
| camel-dataformat-starter | Use a Camel Data Format as a regular Camel Component. | Yes | |
| camel-dataset-starter | Provide data for load and soak testing of your Camel application. | Yes | |
| camel-direct-starter | Call another endpoint from the same Camel Context synchronously. | Yes | |
| camel-elasticsearch-starter | Send requests to ElasticSearch via Java Client API. | Yes | |
| camel-fhir-starter | Exchange information in the healthcare domain using the FHIR (Fast Healthcare Interoperability Resources) standard. | No | |
| camel-file-starter | Read and write files. | Yes | |
| camel-flink-starter | Send DataSet jobs to an Apache Flink cluster. | Yes | |
| camel-ftp-starter | Upload and download files to/from FTP servers. | Yes | |
| camel-google-bigquery-starter | Google BigQuery data warehouse for analytics. | Yes | |
| camel-google-pubsub-starter | Send and receive messages to/from Google Cloud Platform PubSub Service. | Yes | |
| camel-google-secret-manager-starter | Manage Google Secret Manager Secrets | Yes | |
| camel-grpc-starter | Expose gRPC endpoints and access external gRPC endpoints. | Yes | |
| camel-hashicorp-starter | Manage secrets in Hashicorp Vault Service. | Yes | |
| camel-http-starter | Send requests to external HTTP servers using Apache HTTP Client 4.x. | Yes | |
| camel-infinispan-starter | Read and write from/to Infinispan distributed key/value store and data grid. | No | |
| camel-infinispan-embedded-starter | Read and write from/to Infinispan distributed key/value store and data grid. | Yes | |
| camel-jdbc-starter | Access databases through SQL and JDBC. | Yes | |
| camel-jira-starter | Interact with JIRA issue tracker. | Yes | |
| camel-jms-starter | Sent and receive messages to/from a JMS Queue or Topic. | Yes | |
| camel-jolokia-starter | integrates the Jolokia agent configuration in Spring Boot. | Yes | |
| camel-jpa-starter | Store and retrieve Java objects from databases using Java Persistence API (JPA). | Yes | |
| camel-jslt-starter | Query or transform JSON payloads using an JSLT. | Yes | |
| camel-kafka-starter | Sent and receive messages to/from an Apache Kafka broker. | Yes | |
| camel-kamelet-starter | To call Kamelets | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes ConfigMaps and get notified on ConfigMaps changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Custom Resources and get notified on Deployment changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Deployments and get notified on Deployment changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Events and get notified on Events changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Horizontal Pod Autoscalers (HPA) and get notified on HPA changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Jobs. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Namespaces and get notified on Namespace changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Nodes and get notified on Node changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Persistent Volumes and get notified on Persistent Volume changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Persistent Volumes Claims and get notified on Persistent Volumes Claim changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Pods and get notified on Pod changes. | Yes | |
| camel-kubernetes-starter | Yes Perform operations on Kubernetes Replication Controllers and get notified on Replication Controllers changes. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Resources Quotas. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Secrets. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Service Accounts. | Yes | |
| camel-kubernetes-starter | Perform operations on Kubernetes Services and get notified on Service changes. | Yes | |
| camel-kudu-starter | Interact with Apache Kudu, a free and open source column-oriented data store of the Apache Hadoop ecosystem. | No | |
| camel-language-starter | Execute scripts in any of the languages supported by Camel. | Yes | |
| camel-ldap-starter | Perform searches on LDAP servers. | Yes | |
| camel-log-starter | Log messages to the underlying logging mechanism. | Yes | |
| camel-lra-starter | Camel saga binding for Long-Running-Action framework. | Yes | |
| camel-mail-starter | Send and receive emails using imap, pop3 and smtp protocols. | Yes | |
| camel-mail-microsoft-oauth-starter | Camel Mail OAuth2 Authenticator for Microsoft Exchange Online. | Yes | |
| camel-mapstruct-starter | Type Conversion using Mapstruct. | Yes | |
| camel-master-starter | Have only a single consumer in a cluster consuming from a given endpoint; with automatic failover if the JVM dies. | Yes | |
| camel-micrometer-starter | Collect various metrics directly from Camel routes using the Micrometer library. | Yes | |
| camel-minio-starter | Store and retrieve objects from Minio Storage Service using Minio SDK. | Yes | |
| camel-mllp-starter | Communicate with external systems using the MLLP protocol. | Yes | |
| camel-mock-starter | Test routes and mediation rules using mocks. | Yes | |
| camel-mongodb-starter | Perform operations on MongoDB documents and collections. | Yes | |
| camel-mybatis-starter | Performs a query, poll, insert, update or delete in a relational database using MyBatis. | Yes | |
| camel-netty-starter | Socket level networking using TCP or UDP with Netty 4.x. | Yes | |
| camel-olingo4-starter | Communicate with OData 4.0 services using Apache Olingo OData API. | Yes | |
| camel-opensearch-starter | Send requests to OpenSearch via Java Client API. | Yes | |
| camel-kubernetes-starter | Perform operations on OpenShift Builds. | Yes | |
| camel-kubernetes-starter | Perform operations on Openshift Deployment Configs and get notified on Deployment Config changes. | Yes | |
| camel-netty-http-starter | Netty HTTP server and client using the Netty 4.x. | Yes | |
| camel-paho-starter | Communicate with MQTT message brokers using Eclipse Paho MQTT Client. | Yes | |
| camel-paho-mqtt5-starter | Communicate with MQTT message brokers using Eclipse Paho MQTT v5 Client. | Yes | |
| camel-platform-http-starter | Expose HTTP endpoints using the HTTP server available in the current platform. | Yes | |
| camel-quartz-starter | Schedule sending of messages using the Quartz 2.x scheduler. | Yes | |
| camel-ref-starter | Route messages to an endpoint looked up dynamically by name in the Camel Registry. | Yes | |
| camel-rest-starter | Expose REST services or call external REST services. | Yes | |
| camel-saga-starter | Execute custom actions within a route using the Saga EIP. | Yes | |
| camel-salesforce-starter | Communicate with Salesforce using Java DTOs. | Yes | |
| camel-sap-starter | Uses the SAP Java Connector (SAP JCo) library to facilitate bidirectional communication with SAP and the SAP IDoc library to facilitate the transmission of documents in the Intermediate Document (IDoc) format. | Yes | |
| camel-scheduler-starter | Generate messages in specified intervals using java.util.concurrent.ScheduledExecutorService. | Yes | |
| camel-seda-starter | Asynchronously call another endpoint from any Camel Context in the same JVM. | Yes | |
| camel-servlet-starter | Serve HTTP requests by a Servlet. | Yes | |
| camel-slack-starter | Send and receive messages to/from Slack. | Yes | |
| camel-smb-starter | Receive files from SMB (Server Message Block) shares. | Yes | |
| camel-snmp-starter | Receive traps and poll SNMP (Simple Network Management Protocol) capable devices. | Yes | |
| camel-splunk-starter | Publish or search for events in Splunk. | No | |
| camel-spring-batch-starter | Send messages to Spring Batch for further processing. | Yes | |
| camel-spring-jdbc-starter | Access databases through SQL and JDBC with Spring Transaction support. | Yes | |
| camel-spring-ldap-starter | Perform searches in LDAP servers using filters as the message payload. | Yes | |
| camel-spring-rabbitmq-starter | Send and receive messages from RabbitMQ using Spring RabbitMQ client. | Yes | |
| camel-spring-redis-starter | Send and receive messages from Redis. | Yes | |
| camel-spring-ws-starter | You can use this component to integrate with Spring Web Services. It offers client-side support for accessing web services and server-side support for creating your contract-first web services. | Yes | |
| camel-sql-starter | Perform SQL queries using Spring JDBC. | Yes | |
| camel-sql-starter | Perform SQL queries as a JDBC Stored Procedures using Spring JDBC. | Yes | |
| camel-ssh-starter | Execute commands on remote hosts using SSH. | Yes | |
| camel-stub-starter | Stub out any physical endpoints while in development or testing. | Yes | |
| camel-telegram-starter | Send and receive messages acting as a Telegram Bot Telegram Bot API. | Yes | |
| camel-timer-starter | Generate messages in specified intervals using java.util.Timer. | Yes | |
| camel-validator-starter | Validate the payload using XML Schema and JAXP Validation. | Yes | |
| camel-velocity-starter | Transform messages using a Velocity template. | Yes | |
| camel-vertx-http-starter | Send requests to external HTTP servers using Vert.x. | Yes | |
| camel-vertx-websocket-starter | Expose WebSocket endpoints and connect to remote WebSocket servers using Vert.x. | Yes | |
| camel-webhook-starter | Expose webhook endpoints to receive push notifications for other Camel components. | Yes | |
| camel-xj-starter | Transform JSON and XML message using a XSLT. | Yes | |
| camel-xslt-starter | Transforms XML payload using an XSLT template. | Yes | |
| camel-xslt-saxon-starter | Transform XML payloads using an XSLT template using Saxon. | Yes |
| Component | Artifact | Description | Support on IBM Power and IBM Z |
|---|---|---|---|
| camel-avro-starter | Serialize and deserialize messages using Apache Avro binary data format. | Yes | |
| camel-jackson-avro-starter | Marshal POJOs to Avro and back using Jackson. | Yes | |
| camel-bindy-starter | Marshal and unmarshal between POJOs and key-value pair (KVP) format using Camel Bindy. | Yes | |
| camel-beanio-starter | Marshal and unmarshal Java beans to and from flat files (such as CSV, delimited, or fixed length formats). | Yes | |
| camel-hl7-starter | Marshal and unmarshal HL7 (Health Care) model objects using the HL7 MLLP codec. | Yes | |
| camel-jacksonxml-starter | Unmarshal a XML payloads to POJOs and back using XMLMapper extension of Jackson. | Yes | |
| camel-jaxb-starter | Unmarshal XML payloads to POJOs and back using JAXB2 XML marshalling standard. | Yes | |
| camel-gson-starter | Marshal POJOs to JSON and back using Gson | Yes | |
| camel-jackson-starter | Marshal POJOs to JSON and back using Jackson | Yes | |
| camel-jackson-protobuf-starter | Marshal POJOs to Protobuf and back using Jackson. | Yes | |
| camel-soap-starter | Marshal Java objects to SOAP messages and back. | Yes | |
| camel-zipfile-starter | Compression and decompress streams using java.util.zip.ZipStream. | Yes |
| Language | Artifact | Description | Support on IBM Power and IBM Z |
|---|---|---|---|
| camel-core-starter | A fixed value set only once during the route startup. | Yes | |
| camel-core-starter | Evaluate a compiled simple expression. | Yes | |
| camel-core-starter | Gets a property from the Exchange. | Yes | |
| camel-core-starter | File related capabilities for the Simple language. | Yes | |
| camel-groovy-starter | Evaluates a Groovy script. | Yes | |
| camel-core-starter | Gets a header from the Exchange. | Yes | |
| camel-jq-starter | Evaluates a JQ expression against a JSON message body. | Yes | |
| camel-jsonpath-starter | Evaluates a JSONPath expression against a JSON message body. | Yes | |
| camel-core-starter | Uses an existing expression from the registry. | Yes | |
| camel-core-starter | Evaluates a Camel simple expression. | Yes | |
| camel-core-starter | Tokenize text payloads using delimiter patterns. | Yes | |
| camel-xml-jaxp-starter | Tokenize XML payloads. | Yes | |
| camel-xpath-starter | Evaluates an XPath expression against an XML payload. | Yes | |
| camel-saxon-starter | Query and/or transform XML payloads using XQuery and Saxon. | Yes |
| Extensions | Artifact | Description | Support on IBM Power and IBM Z |
|---|---|---|---|
| camel-jasypt-starter | Security using Jasypt | Yes | |
| camel-kamelet-main-starter | Main to run Kamelet standalone | Yes | |
| camel-openapi-java-starter | Rest-dsl support for using openapi doc | Yes | |
| camel-opentelemetry-starter | Distributed tracing using OpenTelemetry | Yes | |
| camel-spring-security-starter | Security using Spring Security | Yes | |
| camel-yaml-dsl-starter | Camel DSL with YAML | Yes |
Chapter 2. AMQP 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 1.2
Both producer and consumer are supported
The AMQP component supports the AMQP 1.0 protocol using the JMS Client API of the Qpid project.
2.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using camel-amqp with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-amqp-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-amqp-starter</artifactId>
</dependency>
2.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
amqp:[queue:|topic:]destinationName[?options]
amqp:[queue:|topic:]destinationName[?options]
2.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
2.3.1. 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.
2.3.2. 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.
2.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AMQP component supports 100 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| clientId (common) |
Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. The | String | |
| connectionFactory (common) | The connection factory to be use. A connection factory must be configured either on the component or endpoint. | ConnectionFactory | |
| disableReplyTo (common) | Specifies whether Camel ignores the JMSReplyTo header in messages. If true, Camel does not send a reply back to the destination specified in the JMSReplyTo header. You can use this option if you want Camel to consume from a route and you do not want Camel to automatically send back a reply message because another component in your code handles the reply message. You can also use this option if you want to use Camel as a proxy between different message brokers and you want to route message from one system to another. | false | boolean |
| durableSubscriptionName (common) |
The durable subscriber name for specifying durable topic subscriptions. The | String | |
| includeAmqpAnnotations (common) | Whether to include AMQP annotations when mapping from AMQP to Camel Message. Setting this to true maps AMQP message annotations that contain a JMS_AMQP_MA_ prefix to message headers. Due to limitations in Apache Qpid JMS API, currently delivery annotations are ignored. | false | boolean |
| jmsMessageType (common) | Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes, Map, Object, Stream, Text. By default, Camel would determine which JMS message type to use from the In body type. This option allows you to specify it. Enum values:
| JmsMessageType | |
| replyTo (common) | Provides an explicit ReplyTo destination (overrides any incoming value of Message.getJMSReplyTo() in consumer). | String | |
| testConnectionOnStartup (common) | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | boolean |
| acknowledgementModeName (consumer) | The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. Enum values:
| AUTO_ACKNOWLEDGE | String |
| artemisConsumerPriority (consumer) | Consumer priorities allow you to ensure that high priority consumers receive messages while they are active. Normally, active consumers connected to a queue receive messages from it in a round-robin fashion. When consumer priorities are in use, messages are delivered round-robin if multiple active consumers exist with the same high priority. Messages will only going to lower priority consumers when the high priority consumers do not have credit available to consume the message, or those high priority consumers have declined to accept the message (for instance because it does not meet the criteria of any selectors associated with the consumer). | int | |
| asyncConsumer (consumer) | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer picks up the next message from the JMS queue. Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | boolean |
| autoStartup (consumer) | Specifies whether the consumer container should auto-startup. | true | boolean |
| cacheLevel (consumer) | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | int | |
| cacheLevelName (consumer) | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. Enum values:
| CACHE_AUTO | String |
| concurrentConsumers (consumer) | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | int |
| maxConcurrentConsumers (consumer) | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | int | |
| replyToDeliveryPersistent (consumer) | Specifies whether to use persistent delivery by default for replies. | true | boolean |
| selector (consumer) | Sets the JMS selector to use. | String | |
| subscriptionDurable (consumer) | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. | false | boolean |
| subscriptionName (consumer) | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client’s JMS client id, if the client ID is configured. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription, except for a shared subscription (which requires JMS 2.0). | String | |
| subscriptionShared (consumer) | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable, so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | boolean |
| acceptMessagesWhileStopping (consumer (advanced)) | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | boolean |
| allowReplyManagerQuickStop (consumer (advanced)) | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | boolean |
| consumerType (consumer (advanced)) | The consumer type to use, which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. Enum values:
| Default | ConsumerType |
| defaultTaskExecutorType (consumer (advanced)) | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring’s SimpleAsyncTaskExecutor) or ThreadPool (uses Spring’s ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set, it defaults to the previous behaviour, which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. Enum values:
| DefaultTaskExecutorType | |
| eagerLoadingOfProperties (consumer (advanced)) | Enables eager loading of JMS properties and payload as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties. See also the option eagerPoisonBody. | false | boolean |
| eagerPoisonBody (consumer (advanced)) | If eagerLoadingOfProperties is enabled and the JMS message payload (JMS body or JMS properties) is poison (cannot be read/mapped), then set this text as the message body instead so the message can be processed (the cause of the poison are already stored as exception on the Exchange). This can be turned off by setting eagerPoisonBody=false. See also the option eagerLoadingOfProperties. | Poison JMS message due to $\{exception.message} | String |
| exposeListenerSession (consumer (advanced)) | Specifies whether the listener session should be exposed when consuming messages. | false | boolean |
| replyToConsumerType (consumer (advanced)) | The consumer type of the reply consumer (when doing request/reply), which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. Enum values:
| Default | ConsumerType |
| replyToSameDestinationAllowed (consumer (advanced)) | Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself. | false | boolean |
| taskExecutor (consumer (advanced)) | Allows you to specify a custom task executor for consuming messages. | TaskExecutor | |
| deliveryDelay (producer) | Sets delivery delay to use for send calls for JMS. This option requires JMS 2.0 compliant broker. | -1 | long |
| deliveryMode (producer) | Specifies the delivery mode to be used. Possible values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. Enum values:
| Integer | |
| deliveryPersistent (producer) | Specifies whether persistent delivery is used by default. | true | boolean |
| explicitQosEnabled (producer) | Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring’s JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers. | false | Boolean |
| formatDateHeadersToIso8601 (producer) | Sets whether JMS date properties should be formatted according to the ISO 8601 standard. | 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 |
| preserveMessageQos (producer) | Set to true, if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header. | false | boolean |
| priority (producer) | Values greater than 1 specify the message priority when sending (where 1 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. Enum values:
| 4 | int |
| replyToConcurrentConsumers (producer) | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | int |
| replyToMaxConcurrentConsumers (producer) | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | int | |
| replyToOnTimeoutMaxConcurrentConsumers (producer) | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | int |
| replyToOverride (producer) | Provides an explicit ReplyTo destination in the JMS message, which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination. | String | |
| replyToType (producer) | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. Enum values:
| ReplyToType | |
| requestTimeout (producer) | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value, and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. | 20000 | long |
| timeToLive (producer) | When sending messages, specifies the time-to-live of the message (in milliseconds). | -1 | long |
| allowAdditionalHeaders (producer (advanced)) | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma, and use as suffix for wildcard matching. | String | |
| allowNullBody (producer (advanced)) | Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown. | true | boolean |
| alwaysCopyMessage (producer (advanced)) | If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set). | false | boolean |
| correlationProperty (producer (advanced)) | When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel. | String | |
| disableTimeToLive (producer (advanced)) | Use this option to force disabling time to live. For example when you do request/reply over JMS, then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized, so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details. | false | boolean |
| forceSendOriginalMessage (producer (advanced)) | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | boolean |
| includeSentJMSMessageID (producer (advanced)) | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | boolean |
| replyToCacheLevelName (producer (advanced)) | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed, and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. Enum values:
| String | |
| replyToDestinationSelectorName (producer (advanced)) | Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is, if you are not using a temporary reply queue). | String | |
| streamMessageTypeEnabled (producer (advanced)) | Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files, InputStream, etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data. | false | boolean |
| allowAutoWiredConnectionFactory (advanced) | Whether to auto-discover ConnectionFactory from the registry, if no connection factory has been configured. If only one instance of ConnectionFactory is found then it will be used. This is enabled by default. | true | boolean |
| allowAutoWiredDestinationResolver (advanced) | Whether to auto-discover DestinationResolver from the registry, if no destination resolver has been configured. If only one instance of DestinationResolver is found then it will be used. This is enabled by default. | true | boolean |
| allowSerializedHeaders (advanced) | Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean |
| artemisStreamingEnabled (advanced) | Whether optimizing for Apache Artemis streaming mode. This can reduce memory overhead when using Artemis with JMS StreamMessage types. This option must only be enabled if Apache Artemis is being used. | false | boolean |
| asyncStartListener (advanced) | Whether to startup the JmsConsumer message listener asynchronously, when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true, you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used, then beware that if the connection could not be established, then an exception is logged at WARN level, and the consumer will not be able to receive messages; You can then restart the route to retry. | false | boolean |
| asyncStopListener (advanced) | Whether to stop the JmsConsumer message listener asynchronously, when stopping a route. | 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) | To use a shared JMS configuration. | JmsConfiguration | |
| destinationResolver (advanced) | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry). | DestinationResolver | |
| errorHandler (advanced) | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure, than having to code a custom errorHandler. | ErrorHandler | |
| exceptionListener (advanced) | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. | ExceptionListener | |
| idleConsumerLimit (advanced) | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | int |
| idleTaskExecutionLimit (advanced) | Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | int |
| includeAllJMSXProperties (advanced) | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | boolean |
| jmsKeyFormatStrategy (advanced) | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the # notation. Enum values:
| JmsKeyFormatStrategy | |
| mapJmsMessage (advanced) | Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc. | true | boolean |
| maxMessagesPerTask (advanced) | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max), then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | int |
| messageConverter (advanced) | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. | MessageConverter | |
| messageCreatedStrategy (advanced) | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. | MessageCreatedStrategy | |
| messageIdEnabled (advanced) | When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value. | true | boolean |
| messageListenerContainerFactory (advanced) | Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom. | MessageListenerContainerFactory | |
| messageTimestampEnabled (advanced) | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value. | true | boolean |
| pubSubNoLocal (advanced) | Specifies whether to inhibit the delivery of messages published by its own connection. | false | boolean |
| queueBrowseStrategy (advanced) | To use a custom QueueBrowseStrategy when browsing queues. | QueueBrowseStrategy | |
| receiveTimeout (advanced) | The timeout for receiving messages (in milliseconds). | 1000 | long |
| recoveryInterval (advanced) | Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds. | 5000 | long |
| requestTimeoutCheckerInterval (advanced) | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs, then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout. | 1000 | long |
| synchronous (advanced) | Sets whether synchronous processing should be strictly used. | false | boolean |
| transferException (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. Use this with caution as the data is using Java Object serialization and requires the received to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumer!. | false | boolean |
| transferExchange (advanced) | You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload. Use this with caution as the data is using Java Object serialization and requires the receiver to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumers having to use compatible Camel versions!. | false | boolean |
| useMessageIDAsCorrelationID (advanced) | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | boolean |
| waitForProvisionCorrelationToBeUpdatedCounter (advanced) | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | int |
| waitForProvisionCorrelationToBeUpdatedThreadSleepingTime (advanced) | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. | 100 | long |
| headerFilterStrategy (filter) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | |
| errorHandlerLoggingLevel (logging) | Allows to configure the default errorHandler logging level for logging uncaught exceptions. Enum values:
| WARN | LoggingLevel |
| errorHandlerLogStackTrace (logging) | Allows to control whether stacktraces should be logged or not, by the default errorHandler. | true | boolean |
| password (security) | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | String | |
| username (security) | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | String | |
| transacted (transaction) | Specifies whether to use transacted mode. | false | boolean |
| transactedInOut (transaction) | Specifies whether InOut operations (request reply) default to using transacted mode If this flag is set to true, then Spring JmsTemplate will have sessionTransacted set to true, and the acknowledgeMode as transacted on the JmsTemplate used for InOut operations. Note from Spring JMS: that within a JTA transaction, the parameters passed to createQueue, createTopic methods are not taken into account. Depending on the Java EE transaction context, the container makes its own decisions on these values. Analogously, these parameters are not taken into account within a locally managed transaction either, since Spring JMS operates on an existing JMS Session in this case. Setting this flag to true will use a short local JMS transaction when running outside of a managed transaction, and a synchronized local JMS transaction in case of a managed transaction (other than an XA transaction) being present. This has the effect of a local JMS transaction being managed alongside the main transaction (which might be a native JDBC transaction), with the JMS transaction committing right after the main transaction. | false | boolean |
| lazyCreateTransactionManager (transaction (advanced)) | If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true. | true | boolean |
| transactionManager (transaction (advanced)) | The Spring transaction manager to use. | PlatformTransactionManager | |
| transactionName (transaction (advanced)) | The name of the transaction to use. | String | |
| transactionTimeout (transaction (advanced)) | The timeout value of the transaction (in seconds), if using transacted mode. | -1 | int |
2.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AMQP endpoint is configured using URI syntax:
amqp:destinationType:destinationName
amqp:destinationType:destinationName
with the following path and query parameters:
2.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| destinationType (common) | The kind of destination to use. Enum values:
| queue | String |
| destinationName (common) | Required Name of the queue or topic to use as destination. | String |
2.5.2. Query Parameters (96 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| clientId (common) |
Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions with JMS 1.1. The | String | |
| connectionFactory (common) | The connection factory to be use. A connection factory must be configured either on the component or endpoint. | ConnectionFactory | |
| disableReplyTo (common) | Specifies whether Camel ignores the JMSReplyTo header in messages. If true, Camel does not send a reply back to the destination specified in the JMSReplyTo header. You can use this option if you want Camel to consume from a route and you do not want Camel to automatically send back a reply message because another component in your code handles the reply message. You can also use this option if you want to use Camel as a proxy between different message brokers and you want to route message from one system to another. | false | boolean |
| durableSubscriptionName (common) | The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured for a JMS 1.1 durable subscription, and may be configured for JMS 2.0, to create a private durable subscription. | String | |
| jmsMessageType (common) | Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes, Map, Object, Stream, Text. By default, Camel would determine which JMS message type to use from the In body type. This option allows you to specify it. Enum values:
| JmsMessageType | |
| replyTo (common) | Provides an explicit ReplyTo destination (overrides any incoming value of Message.getJMSReplyTo() in consumer). | String | |
| testConnectionOnStartup (common) | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | boolean |
| acknowledgementModeName (consumer) | The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. Enum values:
| AUTO_ACKNOWLEDGE | String |
| artemisConsumerPriority (consumer) | Consumer priorities allow you to ensure that high priority consumers receive messages while they are active. Normally, active consumers connected to a queue receive messages from it in a round-robin fashion. When consumer priorities are in use, messages are delivered round-robin if multiple active consumers exist with the same high priority. Messages will only going to lower priority consumers when the high priority consumers do not have credit available to consume the message, or those high priority consumers have declined to accept the message (for instance because it does not meet the criteria of any selectors associated with the consumer). | int | |
| asyncConsumer (consumer) | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer picks up the next message from the JMS queue. Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | boolean |
| autoStartup (consumer) | Specifies whether the consumer container should auto-startup. | true | boolean |
| cacheLevel (consumer) | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | int | |
| cacheLevelName (consumer) | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. Enum values:
| CACHE_AUTO | String |
| concurrentConsumers (consumer) | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | int |
| maxConcurrentConsumers (consumer) | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | int | |
| replyToDeliveryPersistent (consumer) | Specifies whether to use persistent delivery by default for replies. | true | boolean |
| selector (consumer) | Sets the JMS selector to use. | String | |
| subscriptionDurable (consumer) | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. | false | boolean |
| subscriptionName (consumer) | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client’s JMS client id, if the client ID is configured. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription, except for a shared subscription (which requires JMS 2.0). | String | |
| subscriptionShared (consumer) | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable, so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | boolean |
| acceptMessagesWhileStopping (consumer (advanced)) | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | boolean |
| allowReplyManagerQuickStop (consumer (advanced)) | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | boolean |
| consumerType (consumer (advanced)) | The consumer type to use, which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. Enum values:
| Default | ConsumerType |
| defaultTaskExecutorType (consumer (advanced)) | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring’s SimpleAsyncTaskExecutor) or ThreadPool (uses Spring’s ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set, it defaults to the previous behaviour, which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. Enum values:
| DefaultTaskExecutorType | |
| eagerLoadingOfProperties (consumer (advanced)) | Enables eager loading of JMS properties and payload as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties. See also the option eagerPoisonBody. | false | boolean |
| eagerPoisonBody (consumer (advanced)) | If eagerLoadingOfProperties is enabled and the JMS message payload (JMS body or JMS properties) is poison (cannot be read/mapped), then set this text as the message body instead so the message can be processed (the cause of the poison are already stored as exception on the Exchange). This can be turned off by setting eagerPoisonBody=false. See also the option eagerLoadingOfProperties. | Poison JMS message due to $\{exception.message} | String |
| 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:
| ExchangePattern | |
| exposeListenerSession (consumer (advanced)) | Specifies whether the listener session should be exposed when consuming messages. | false | boolean |
| replyToConsumerType (consumer (advanced)) | The consumer type of the reply consumer (when doing request/reply), which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. Enum values:
| Default | ConsumerType |
| replyToSameDestinationAllowed (consumer (advanced)) | Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself. | false | boolean |
| taskExecutor (consumer (advanced)) | Allows you to specify a custom task executor for consuming messages. | TaskExecutor | |
| deliveryDelay (producer) | Sets delivery delay to use for send calls for JMS. This option requires JMS 2.0 compliant broker. | -1 | long |
| deliveryMode (producer) | Specifies the delivery mode to be used. Possible values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. Enum values:
| Integer | |
| deliveryPersistent (producer) | Specifies whether persistent delivery is used by default. | true | boolean |
| explicitQosEnabled (producer) | Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring’s JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers. | false | Boolean |
| formatDateHeadersToIso8601 (producer) | Sets whether JMS date properties should be formatted according to the ISO 8601 standard. | false | boolean |
| preserveMessageQos (producer) | Set to true, if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header. | false | boolean |
| priority (producer) | Values greater than 1 specify the message priority when sending (where 1 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. Enum values:
| 4 | int |
| replyToConcurrentConsumers (producer) | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | int |
| replyToMaxConcurrentConsumers (producer) | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | int | |
| replyToOnTimeoutMaxConcurrentConsumers (producer) | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | int |
| replyToOverride (producer) | Provides an explicit ReplyTo destination in the JMS message, which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination. | String | |
| replyToType (producer) | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. Enum values:
| ReplyToType | |
| requestTimeout (producer) | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value, and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. | 20000 | long |
| timeToLive (producer) | When sending messages, specifies the time-to-live of the message (in milliseconds). | -1 | long |
| allowAdditionalHeaders (producer (advanced)) | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma, and use as suffix for wildcard matching. | String | |
| allowNullBody (producer (advanced)) | Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown. | true | boolean |
| alwaysCopyMessage (producer (advanced)) | If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set). | false | boolean |
| correlationProperty (producer (advanced)) | When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel. | String | |
| disableTimeToLive (producer (advanced)) | Use this option to force disabling time to live. For example when you do request/reply over JMS, then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized, so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details. | false | boolean |
| forceSendOriginalMessage (producer (advanced)) | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | boolean |
| includeSentJMSMessageID (producer (advanced)) | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | boolean |
| 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 |
| replyToCacheLevelName (producer (advanced)) | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed, and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. Enum values:
| String | |
| replyToDestinationSelectorName (producer (advanced)) | Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is, if you are not using a temporary reply queue). | String | |
| streamMessageTypeEnabled (producer (advanced)) | Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files, InputStream, etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data. | false | boolean |
| allowSerializedHeaders (advanced) | Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | boolean |
| artemisStreamingEnabled (advanced) | Whether optimizing for Apache Artemis streaming mode. This can reduce memory overhead when using Artemis with JMS StreamMessage types. This option must only be enabled if Apache Artemis is being used. | false | boolean |
| asyncStartListener (advanced) | Whether to startup the JmsConsumer message listener asynchronously, when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true, you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used, then beware that if the connection could not be established, then an exception is logged at WARN level, and the consumer will not be able to receive messages; You can then restart the route to retry. | false | boolean |
| asyncStopListener (advanced) | Whether to stop the JmsConsumer message listener asynchronously, when stopping a route. | false | boolean |
| destinationResolver (advanced) | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry). | DestinationResolver | |
| errorHandler (advanced) | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure, than having to code a custom errorHandler. | ErrorHandler | |
| exceptionListener (advanced) | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. | ExceptionListener | |
| headerFilterStrategy (advanced) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | |
| idleConsumerLimit (advanced) | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | int |
| idleTaskExecutionLimit (advanced) | Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | int |
| includeAllJMSXProperties (advanced) | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | boolean |
| jmsKeyFormatStrategy (advanced) | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the # notation. Enum values:
| JmsKeyFormatStrategy | |
| mapJmsMessage (advanced) | Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc. | true | boolean |
| maxMessagesPerTask (advanced) | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max), then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | int |
| messageConverter (advanced) | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. | MessageConverter | |
| messageCreatedStrategy (advanced) | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. | MessageCreatedStrategy | |
| messageIdEnabled (advanced) | When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value. | true | boolean |
| messageListenerContainerFactory (advanced) | Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom. | MessageListenerContainerFactory | |
| messageTimestampEnabled (advanced) | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value. | true | boolean |
| pubSubNoLocal (advanced) | Specifies whether to inhibit the delivery of messages published by its own connection. | false | boolean |
| receiveTimeout (advanced) | The timeout for receiving messages (in milliseconds). | 1000 | long |
| recoveryInterval (advanced) | Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds. | 5000 | long |
| requestTimeoutCheckerInterval (advanced) | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs, then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout. | 1000 | long |
| synchronous (advanced) | Sets whether synchronous processing should be strictly used. | false | boolean |
| transferException (advanced) | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. Use this with caution as the data is using Java Object serialization and requires the received to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumer!. | false | boolean |
| transferExchange (advanced) | You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload. Use this with caution as the data is using Java Object serialization and requires the receiver to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumers having to use compatible Camel versions!. | false | boolean |
| useMessageIDAsCorrelationID (advanced) | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | boolean |
| waitForProvisionCorrelationToBeUpdatedCounter (advanced) | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | int |
| waitForProvisionCorrelationToBeUpdatedThreadSleepingTime (advanced) | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. | 100 | long |
| errorHandlerLoggingLevel (logging) | Allows to configure the default errorHandler logging level for logging uncaught exceptions. Enum values:
| WARN | LoggingLevel |
| errorHandlerLogStackTrace (logging) | Allows to control whether stacktraces should be logged or not, by the default errorHandler. | true | boolean |
| password (security) | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | String | |
| username (security) | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | String | |
| transacted (transaction) | Specifies whether to use transacted mode. | false | boolean |
| transactedInOut (transaction) | Specifies whether InOut operations (request reply) default to using transacted mode If this flag is set to true, then Spring JmsTemplate will have sessionTransacted set to true, and the acknowledgeMode as transacted on the JmsTemplate used for InOut operations. Note from Spring JMS: that within a JTA transaction, the parameters passed to createQueue, createTopic methods are not taken into account. Depending on the Java EE transaction context, the container makes its own decisions on these values. Analogously, these parameters are not taken into account within a locally managed transaction either, since Spring JMS operates on an existing JMS Session in this case. Setting this flag to true will use a short local JMS transaction when running outside of a managed transaction, and a synchronized local JMS transaction in case of a managed transaction (other than an XA transaction) being present. This has the effect of a local JMS transaction being managed alongside the main transaction (which might be a native JDBC transaction), with the JMS transaction committing right after the main transaction. | false | boolean |
| lazyCreateTransactionManager (transaction (advanced)) | If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true. | true | boolean |
| transactionManager (transaction (advanced)) | The Spring transaction manager to use. | PlatformTransactionManager | |
| transactionName (transaction (advanced)) | The name of the transaction to use. | String | |
| transactionTimeout (transaction (advanced)) | The timeout value of the transaction (in seconds), if using transacted mode. | -1 | int |
2.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
As AMQP component is inherited from JMS component, the usage of the former is almost identical to the latter:
Using AMQP component
2.7. Configuring AMQP component 링크 복사링크가 클립보드에 복사되었습니다!
Creating AMQP 1.0 component
AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672");
AMQPComponent authorizedAmqp = AMQPComponent.amqpComponent("amqp://localhost:5672", "user", "password");
AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672");
AMQPComponent authorizedAmqp = AMQPComponent.amqpComponent("amqp://localhost:5672", "user", "password");
You can also add an instance of org.apache.camel.component.amqp.AMQPConnectionDetails to the registry in order to automatically configure the AMQP component. For example for Spring Boot you just have to define bean:
AMQP connection details auto-configuration
Likewise, you can also use CDI producer methods when using Camel-CDI
AMQP connection details auto-configuration for CDI
@Produces
AMQPConnectionDetails amqpConnection() {
return new AMQPConnectionDetails("amqp://localhost:5672");
}
@Produces
AMQPConnectionDetails amqpConnection() {
return new AMQPConnectionDetails("amqp://localhost:5672");
}
You can also rely on the to read the AMQP connection details. Factory method AMQPConnectionDetails.discoverAMQP() attempts to read Camel properties in a Kubernetes-like convention, just as demonstrated on the snippet below:
AMQP connection details auto-configuration
Enabling AMQP specific options
If you, for example, need to enable amqp.traceFrames you can do that by appending the option to your URI, like the following example:
AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672?amqp.traceFrames=true");
AMQPComponent amqp = AMQPComponent.amqpComponent("amqp://localhost:5672?amqp.traceFrames=true");
For reference refer QPID JMS client configuration.
2.8. Using topics 링크 복사링크가 클립보드에 복사되었습니다!
To have using topics working with camel-amqp you need to configure the component to use topic:// as topic prefix, as shown below:
Keep in mind that both AMQPComponent#amqpComponent() methods and AMQPConnectionDetails pre-configure the component with the topic prefix, so you don’t have to configure it explicitly.
2.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 101 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.amqp.accept-messages-while-stopping | Specifies whether the consumer accept messages while it is stopping. You may consider enabling this option, if you start and stop JMS routes at runtime, while there are still messages enqueued on the queue. If this option is false, and you stop the JMS route, then messages may be rejected, and the JMS broker would have to attempt redeliveries, which yet again may be rejected, and eventually the message may be moved at a dead letter queue on the JMS broker. To avoid this its recommended to enable this option. | false | Boolean |
| camel.component.amqp.acknowledgement-mode-name | The JMS acknowledgement name, which is one of: SESSION_TRANSACTED, CLIENT_ACKNOWLEDGE, AUTO_ACKNOWLEDGE, DUPS_OK_ACKNOWLEDGE. | AUTO_ACKNOWLEDGE | String |
| camel.component.amqp.allow-additional-headers | This option is used to allow additional headers which may have values that are invalid according to JMS specification. For example some message systems such as WMQ do this with header names using prefix JMS_IBM_MQMD_ containing values with byte array or other invalid types. You can specify multiple header names separated by comma, and use as suffix for wildcard matching. | String | |
| camel.component.amqp.allow-auto-wired-connection-factory | Whether to auto-discover ConnectionFactory from the registry, if no connection factory has been configured. If only one instance of ConnectionFactory is found then it will be used. This is enabled by default. | true | Boolean |
| camel.component.amqp.allow-auto-wired-destination-resolver | Whether to auto-discover DestinationResolver from the registry, if no destination resolver has been configured. If only one instance of DestinationResolver is found then it will be used. This is enabled by default. | true | Boolean |
| camel.component.amqp.allow-null-body | Whether to allow sending messages with no body. If this option is false and the message body is null, then an JMSException is thrown. | true | Boolean |
| camel.component.amqp.allow-reply-manager-quick-stop | Whether the DefaultMessageListenerContainer used in the reply managers for request-reply messaging allow the DefaultMessageListenerContainer.runningAllowed flag to quick stop in case JmsConfiguration#isAcceptMessagesWhileStopping is enabled, and org.apache.camel.CamelContext is currently being stopped. This quick stop ability is enabled by default in the regular JMS consumers but to enable for reply managers you must enable this flag. | false | Boolean |
| camel.component.amqp.allow-serialized-headers | Controls whether or not to include serialized headers. Applies only when transferExchange is true. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. | false | Boolean |
| camel.component.amqp.always-copy-message | If true, Camel will always make a JMS message copy of the message when it is passed to the producer for sending. Copying the message is needed in some situations, such as when a replyToDestinationSelectorName is set (incidentally, Camel will set the alwaysCopyMessage option to true, if a replyToDestinationSelectorName is set). | false | Boolean |
| camel.component.amqp.artemis-consumer-priority | Consumer priorities allow you to ensure that high priority consumers receive messages while they are active. Normally, active consumers connected to a queue receive messages from it in a round-robin fashion. When consumer priorities are in use, messages are delivered round-robin if multiple active consumers exist with the same high priority. Messages will only going to lower priority consumers when the high priority consumers do not have credit available to consume the message, or those high priority consumers have declined to accept the message (for instance because it does not meet the criteria of any selectors associated with the consumer). | Integer | |
| camel.component.amqp.artemis-streaming-enabled | Whether optimizing for Apache Artemis streaming mode. This can reduce memory overhead when using Artemis with JMS StreamMessage types. This option must only be enabled if Apache Artemis is being used. | false | Boolean |
| camel.component.amqp.async-consumer | Whether the JmsConsumer processes the Exchange asynchronously. If enabled then the JmsConsumer may pickup the next message from the JMS queue, while the previous message is being processed asynchronously (by the Asynchronous Routing Engine). This means that messages may be processed not 100% strictly in order. If disabled (as default) then the Exchange is fully processed before the JmsConsumer picks up the next message from the JMS queue. Note if transacted has been enabled, then asyncConsumer=true does not run asynchronously, as transaction must be executed synchronously (Camel 3.0 may support async transactions). | false | Boolean |
| camel.component.amqp.async-start-listener | Whether to startup the JmsConsumer message listener asynchronously, when starting a route. For example if a JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover. This will cause Camel to block while starting routes. By setting this option to true, you will let routes startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this option is used, then beware that if the connection could not be established, then an exception is logged at WARN level, and the consumer will not be able to receive messages; You can then restart the route to retry. | false | Boolean |
| camel.component.amqp.async-stop-listener | Whether to stop the JmsConsumer message listener asynchronously, when stopping a route. | false | Boolean |
| camel.component.amqp.auto-startup | Specifies whether the consumer container should auto-startup. | true | Boolean |
| camel.component.amqp.autowired-enabled | 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 |
| camel.component.amqp.cache-level | Sets the cache level by ID for the underlying JMS resources. See cacheLevelName option for more details. | Integer | |
| camel.component.amqp.cache-level-name | Sets the cache level by name for the underlying JMS resources. Possible values are: CACHE_AUTO, CACHE_CONNECTION, CACHE_CONSUMER, CACHE_NONE, and CACHE_SESSION. The default setting is CACHE_AUTO. See the Spring documentation and Transactions Cache Levels for more information. | CACHE_AUTO | String |
| camel.component.amqp.client-id | Sets the JMS client ID to use. Note that this value, if specified, must be unique and can only be used by a single JMS connection instance. It is typically only required for durable topic subscriptions with JMS 1.1. | String | |
| camel.component.amqp.concurrent-consumers | Specifies the default number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | 1 | Integer |
| camel.component.amqp.configuration | To use a shared JMS configuration. The option is a org.apache.camel.component.jms.JmsConfiguration type. | JmsConfiguration | |
| camel.component.amqp.connection-factory | The connection factory to be use. A connection factory must be configured either on the component or endpoint. The option is a javax.jms.ConnectionFactory type. | ConnectionFactory | |
| camel.component.amqp.consumer-type | The consumer type to use, which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. | ConsumerType | |
| camel.component.amqp.correlation-property | When using InOut exchange pattern use this JMS property instead of JMSCorrelationID JMS property to correlate messages. If set messages will be correlated solely on the value of this property JMSCorrelationID property will be ignored and not set by Camel. | String | |
| camel.component.amqp.default-task-executor-type | Specifies what default TaskExecutor type to use in the DefaultMessageListenerContainer, for both consumer endpoints and the ReplyTo consumer of producer endpoints. Possible values: SimpleAsync (uses Spring’s SimpleAsyncTaskExecutor) or ThreadPool (uses Spring’s ThreadPoolTaskExecutor with optimal values - cached threadpool-like). If not set, it defaults to the previous behaviour, which uses a cached thread pool for consumer endpoints and SimpleAsync for reply consumers. The use of ThreadPool is recommended to reduce thread trash in elastic configurations with dynamically increasing and decreasing concurrent consumers. | DefaultTaskExecutorType | |
| camel.component.amqp.delivery-delay | Sets delivery delay to use for send calls for JMS. This option requires JMS 2.0 compliant broker. | -1 | Long |
| camel.component.amqp.delivery-mode | Specifies the delivery mode to be used. Possible values are those defined by javax.jms.DeliveryMode. NON_PERSISTENT = 1 and PERSISTENT = 2. | Integer | |
| camel.component.amqp.delivery-persistent | Specifies whether persistent delivery is used by default. | true | Boolean |
| camel.component.amqp.destination-resolver | A pluggable org.springframework.jms.support.destination.DestinationResolver that allows you to use your own resolver (for example, to lookup the real destination in a JNDI registry). The option is a org.springframework.jms.support.destination.DestinationResolver type. | DestinationResolver | |
| camel.component.amqp.disable-reply-to | Specifies whether Camel ignores the JMSReplyTo header in messages. If true, Camel does not send a reply back to the destination specified in the JMSReplyTo header. You can use this option if you want Camel to consume from a route and you do not want Camel to automatically send back a reply message because another component in your code handles the reply message. You can also use this option if you want to use Camel as a proxy between different message brokers and you want to route message from one system to another. | false | Boolean |
| camel.component.amqp.disable-time-to-live | Use this option to force disabling time to live. For example when you do request/reply over JMS, then Camel will by default use the requestTimeout value as time to live on the message being sent. The problem is that the sender and receiver systems have to have their clocks synchronized, so they are in sync. This is not always so easy to archive. So you can use disableTimeToLive=true to not set a time to live value on the sent message. Then the message will not expire on the receiver system. See below in section About time to live for more details. | false | Boolean |
| camel.component.amqp.durable-subscription-name | The durable subscriber name for specifying durable topic subscriptions. The clientId option must be configured as well. | String | |
| camel.component.amqp.eager-loading-of-properties | Enables eager loading of JMS properties and payload as soon as a message is loaded which generally is inefficient as the JMS properties may not be required but sometimes can catch early any issues with the underlying JMS provider and the use of JMS properties. See also the option eagerPoisonBody. | false | Boolean |
| camel.component.amqp.eager-poison-body | If eagerLoadingOfProperties is enabled and the JMS message payload (JMS body or JMS properties) is poison (cannot be read/mapped), then set this text as the message body instead so the message can be processed (the cause of the poison are already stored as exception on the Exchange). This can be turned off by setting eagerPoisonBody=false. See also the option eagerLoadingOfProperties. | Poison JMS message due to $\{exception.message} | String |
| camel.component.amqp.enabled | Whether to enable auto configuration of the amqp component. This is enabled by default. | Boolean | |
| camel.component.amqp.error-handler | Specifies a org.springframework.util.ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default these exceptions will be logged at the WARN level, if no errorHandler has been configured. You can configure logging level and whether stack traces should be logged using errorHandlerLoggingLevel and errorHandlerLogStackTrace options. This makes it much easier to configure, than having to code a custom errorHandler. The option is a org.springframework.util.ErrorHandler type. | ErrorHandler | |
| camel.component.amqp.error-handler-log-stack-trace | Allows to control whether stacktraces should be logged or not, by the default errorHandler. | true | Boolean |
| camel.component.amqp.error-handler-logging-level | Allows to configure the default errorHandler logging level for logging uncaught exceptions. | LoggingLevel | |
| camel.component.amqp.exception-listener | Specifies the JMS Exception Listener that is to be notified of any underlying JMS exceptions. The option is a javax.jms.ExceptionListener type. | ExceptionListener | |
| camel.component.amqp.explicit-qos-enabled | Set if the deliveryMode, priority or timeToLive qualities of service should be used when sending messages. This option is based on Spring’s JmsTemplate. The deliveryMode, priority and timeToLive options are applied to the current endpoint. This contrasts with the preserveMessageQos option, which operates at message granularity, reading QoS properties exclusively from the Camel In message headers. | false | Boolean |
| camel.component.amqp.expose-listener-session | Specifies whether the listener session should be exposed when consuming messages. | false | Boolean |
| camel.component.amqp.force-send-original-message | When using mapJmsMessage=false Camel will create a new JMS message to send to a new JMS destination if you touch the headers (get or set) during the route. Set this option to true to force Camel to send the original JMS message that was received. | false | Boolean |
| camel.component.amqp.format-date-headers-to-iso8601 | Sets whether JMS date properties should be formatted according to the ISO 8601 standard. | false | Boolean |
| camel.component.amqp.header-filter-strategy | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. The option is a org.apache.camel.spi.HeaderFilterStrategy type. | HeaderFilterStrategy | |
| camel.component.amqp.idle-consumer-limit | Specify the limit for the number of consumers that are allowed to be idle at any given time. | 1 | Integer |
| camel.component.amqp.idle-task-execution-limit | Specifies the limit for idle executions of a receive task, not having received any message within its execution. If this limit is reached, the task will shut down and leave receiving to other executing tasks (in the case of dynamic scheduling; see the maxConcurrentConsumers setting). There is additional doc available from Spring. | 1 | Integer |
| camel.component.amqp.include-all-jmsx-properties | Whether to include all JMSXxxx properties when mapping from JMS to Camel Message. Setting this to true will include properties such as JMSXAppID, and JMSXUserID etc. Note: If you are using a custom headerFilterStrategy then this option does not apply. | false | Boolean |
| camel.component.amqp.include-amqp-annotations | Whether to include AMQP annotations when mapping from AMQP to Camel Message. Setting this to true maps AMQP message annotations that contain a JMS_AMQP_MA_ prefix to message headers. Due to limitations in Apache Qpid JMS API, currently delivery annotations are ignored. | false | Boolean |
| camel.component.amqp.include-sent-jms-message-id | Only applicable when sending to JMS destination using InOnly (eg fire and forget). Enabling this option will enrich the Camel Exchange with the actual JMSMessageID that was used by the JMS client when the message was sent to the JMS destination. | false | Boolean |
| camel.component.amqp.jms-key-format-strategy | Pluggable strategy for encoding and decoding JMS keys so they can be compliant with the JMS specification. Camel provides two implementations out of the box: default and passthrough. The default strategy will safely marshal dots and hyphens (. and -). The passthrough strategy leaves the key as is. Can be used for JMS brokers which do not care whether JMS header keys contain illegal characters. You can provide your own implementation of the org.apache.camel.component.jms.JmsKeyFormatStrategy and refer to it using the # notation. | JmsKeyFormatStrategy | |
| camel.component.amqp.jms-message-type | Allows you to force the use of a specific javax.jms.Message implementation for sending JMS messages. Possible values are: Bytes, Map, Object, Stream, Text. By default, Camel would determine which JMS message type to use from the In body type. This option allows you to specify it. | JmsMessageType | |
| camel.component.amqp.lazy-create-transaction-manager | If true, Camel will create a JmsTransactionManager, if there is no transactionManager injected when option transacted=true. | true | Boolean |
| camel.component.amqp.lazy-start-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 |
| camel.component.amqp.map-jms-message | Specifies whether Camel should auto map the received JMS message to a suited payload type, such as javax.jms.TextMessage to a String etc. | true | Boolean |
| camel.component.amqp.max-concurrent-consumers | Specifies the maximum number of concurrent consumers when consuming from JMS (not for request/reply over JMS). See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. When doing request/reply over JMS then the option replyToMaxConcurrentConsumers is used to control number of concurrent consumers on the reply message listener. | Integer | |
| camel.component.amqp.max-messages-per-task | The number of messages per task. -1 is unlimited. If you use a range for concurrent consumers (eg min max), then this option can be used to set a value to eg 100 to control how fast the consumers will shrink when less work is required. | -1 | Integer |
| camel.component.amqp.message-converter | To use a custom Spring org.springframework.jms.support.converter.MessageConverter so you can be in control how to map to/from a javax.jms.Message. The option is a org.springframework.jms.support.converter.MessageConverter type. | MessageConverter | |
| camel.component.amqp.message-created-strategy | To use the given MessageCreatedStrategy which are invoked when Camel creates new instances of javax.jms.Message objects when Camel is sending a JMS message. The option is a org.apache.camel.component.jms.MessageCreatedStrategy type. | MessageCreatedStrategy | |
| camel.component.amqp.message-id-enabled | When sending, specifies whether message IDs should be added. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the message ID set to null; if the provider ignores the hint, the message ID must be set to its normal unique value. | true | Boolean |
| camel.component.amqp.message-listener-container-factory | Registry ID of the MessageListenerContainerFactory used to determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use to consume messages. Setting this will automatically set consumerType to Custom. The option is a org.apache.camel.component.jms.MessageListenerContainerFactory type. | MessageListenerContainerFactory | |
| camel.component.amqp.message-timestamp-enabled | Specifies whether timestamps should be enabled by default on sending messages. This is just an hint to the JMS broker. If the JMS provider accepts this hint, these messages must have the timestamp set to zero; if the provider ignores the hint the timestamp must be set to its normal value. | true | Boolean |
| camel.component.amqp.password | Password to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | String | |
| camel.component.amqp.preserve-message-qos | Set to true, if you want to send message using the QoS settings specified on the message, instead of the QoS settings on the JMS endpoint. The following three headers are considered JMSPriority, JMSDeliveryMode, and JMSExpiration. You can provide all or only some of them. If not provided, Camel will fall back to use the values from the endpoint instead. So, when using this option, the headers override the values from the endpoint. The explicitQosEnabled option, by contrast, will only use options set on the endpoint, and not values from the message header. | false | Boolean |
| camel.component.amqp.priority | Values greater than 1 specify the message priority when sending (where 1 is the lowest priority and 9 is the highest). The explicitQosEnabled option must also be enabled in order for this option to have any effect. | 4 | Integer |
| camel.component.amqp.pub-sub-no-local | Specifies whether to inhibit the delivery of messages published by its own connection. | false | Boolean |
| camel.component.amqp.queue-browse-strategy | To use a custom QueueBrowseStrategy when browsing queues. The option is a org.apache.camel.component.jms.QueueBrowseStrategy type. | QueueBrowseStrategy | |
| camel.component.amqp.receive-timeout | The timeout for receiving messages (in milliseconds). The option is a long type. | 1000 | Long |
| camel.component.amqp.recovery-interval | Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The default is 5000 ms, that is, 5 seconds. The option is a long type. | 5000 | Long |
| camel.component.amqp.reply-to | Provides an explicit ReplyTo destination (overrides any incoming value of Message.getJMSReplyTo() in consumer). | String | |
| camel.component.amqp.reply-to-cache-level-name | Sets the cache level by name for the reply consumer when doing request/reply over JMS. This option only applies when using fixed reply queues (not temporary). Camel will by default use: CACHE_CONSUMER for exclusive or shared w/ replyToSelectorName. And CACHE_SESSION for shared without replyToSelectorName. Some JMS brokers such as IBM WebSphere may require to set the replyToCacheLevelName=CACHE_NONE to work. Note: If using temporary queues then CACHE_NONE is not allowed, and you must use a higher value such as CACHE_CONSUMER or CACHE_SESSION. | String | |
| camel.component.amqp.reply-to-concurrent-consumers | Specifies the default number of concurrent consumers when doing request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | 1 | Integer |
| camel.component.amqp.reply-to-consumer-type | The consumer type of the reply consumer (when doing request/reply), which can be one of: Simple, Default, or Custom. The consumer type determines which Spring JMS listener to use. Default will use org.springframework.jms.listener.DefaultMessageListenerContainer, Simple will use org.springframework.jms.listener.SimpleMessageListenerContainer. When Custom is specified, the MessageListenerContainerFactory defined by the messageListenerContainerFactory option will determine what org.springframework.jms.listener.AbstractMessageListenerContainer to use. | ConsumerType | |
| camel.component.amqp.reply-to-delivery-persistent | Specifies whether to use persistent delivery by default for replies. | true | Boolean |
| camel.component.amqp.reply-to-destination-selector-name | Sets the JMS Selector using the fixed name to be used so you can filter out your own replies from the others when using a shared queue (that is, if you are not using a temporary reply queue). | String | |
| camel.component.amqp.reply-to-max-concurrent-consumers | Specifies the maximum number of concurrent consumers when using request/reply over JMS. See also the maxMessagesPerTask option to control dynamic scaling up/down of threads. | Integer | |
| camel.component.amqp.reply-to-on-timeout-max-concurrent-consumers | Specifies the maximum number of concurrent consumers for continue routing when timeout occurred when using request/reply over JMS. | 1 | Integer |
| camel.component.amqp.reply-to-override | Provides an explicit ReplyTo destination in the JMS message, which overrides the setting of replyTo. It is useful if you want to forward the message to a remote Queue and receive the reply message from the ReplyTo destination. | String | |
| camel.component.amqp.reply-to-same-destination-allowed | Whether a JMS consumer is allowed to send a reply message to the same destination that the consumer is using to consume from. This prevents an endless loop by consuming and sending back the same message to itself. | false | Boolean |
| camel.component.amqp.reply-to-type | Allows for explicitly specifying which kind of strategy to use for replyTo queues when doing request/reply over JMS. Possible values are: Temporary, Shared, or Exclusive. By default Camel will use temporary queues. However if replyTo has been configured, then Shared is used by default. This option allows you to use exclusive queues instead of shared ones. See Camel JMS documentation for more details, and especially the notes about the implications if running in a clustered environment, and the fact that Shared reply queues has lower performance than its alternatives Temporary and Exclusive. | ReplyToType | |
| camel.component.amqp.request-timeout | The timeout for waiting for a reply when using the InOut Exchange Pattern (in milliseconds). The default is 20 seconds. You can include the header CamelJmsRequestTimeout to override this endpoint configured timeout value, and thus have per message individual timeout values. See also the requestTimeoutCheckerInterval option. The option is a long type. | 20000 | Long |
| camel.component.amqp.request-timeout-checker-interval | Configures how often Camel should check for timed out Exchanges when doing request/reply over JMS. By default Camel checks once per second. But if you must react faster when a timeout occurs, then you can lower this interval, to check more frequently. The timeout is determined by the option requestTimeout. The option is a long type. | 1000 | Long |
| camel.component.amqp.selector | Sets the JMS selector to use. | String | |
| camel.component.amqp.stream-message-type-enabled | Sets whether StreamMessage type is enabled or not. Message payloads of streaming kind such as files, InputStream, etc will either by sent as BytesMessage or StreamMessage. This option controls which kind will be used. By default BytesMessage is used which enforces the entire message payload to be read into memory. By enabling this option the message payload is read into memory in chunks and each chunk is then written to the StreamMessage until no more data. | false | Boolean |
| camel.component.amqp.subscription-durable | Set whether to make the subscription durable. The durable subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a durable subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. | false | Boolean |
| camel.component.amqp.subscription-name | Set the name of a subscription to create. To be applied in case of a topic (pub-sub domain) with a shared or durable subscription. The subscription name needs to be unique within this client’s JMS client id. Default is the class name of the specified message listener. Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each subscription, except for a shared subscription (which requires JMS 2.0). | String | |
| camel.component.amqp.subscription-shared | Set whether to make the subscription shared. The shared subscription name to be used can be specified through the subscriptionName property. Default is false. Set this to true to register a shared subscription, typically in combination with a subscriptionName value (unless your message listener class name is good enough as subscription name). Note that shared subscriptions may also be durable, so this flag can (and often will) be combined with subscriptionDurable as well. Only makes sense when listening to a topic (pub-sub domain), therefore this method switches the pubSubDomain flag as well. Requires a JMS 2.0 compatible message broker. | false | Boolean |
| camel.component.amqp.synchronous | Sets whether synchronous processing should be strictly used. | false | Boolean |
| camel.component.amqp.task-executor | Allows you to specify a custom task executor for consuming messages. The option is a org.springframework.core.task.TaskExecutor type. | TaskExecutor | |
| camel.component.amqp.test-connection-on-startup | Specifies whether to test the connection on startup. This ensures that when Camel starts that all the JMS consumers have a valid connection to the JMS broker. If a connection cannot be granted then Camel throws an exception on startup. This ensures that Camel is not started with failed connections. The JMS producers is tested as well. | false | Boolean |
| camel.component.amqp.time-to-live | When sending messages, specifies the time-to-live of the message (in milliseconds). | -1 | Long |
| camel.component.amqp.transacted | Specifies whether to use transacted mode. | false | Boolean |
| camel.component.amqp.transacted-in-out | Specifies whether InOut operations (request reply) default to using transacted mode If this flag is set to true, then Spring JmsTemplate will have sessionTransacted set to true, and the acknowledgeMode as transacted on the JmsTemplate used for InOut operations. Note from Spring JMS: that within a JTA transaction, the parameters passed to createQueue, createTopic methods are not taken into account. Depending on the Java EE transaction context, the container makes its own decisions on these values. Analogously, these parameters are not taken into account within a locally managed transaction either, since Spring JMS operates on an existing JMS Session in this case. Setting this flag to true will use a short local JMS transaction when running outside of a managed transaction, and a synchronized local JMS transaction in case of a managed transaction (other than an XA transaction) being present. This has the effect of a local JMS transaction being managed alongside the main transaction (which might be a native JDBC transaction), with the JMS transaction committing right after the main transaction. | false | Boolean |
| camel.component.amqp.transaction-manager | The Spring transaction manager to use. The option is a org.springframework.transaction.PlatformTransactionManager type. | PlatformTransactionManager | |
| camel.component.amqp.transaction-name | The name of the transaction to use. | String | |
| camel.component.amqp.transaction-timeout | The timeout value of the transaction (in seconds), if using transacted mode. | -1 | Integer |
| camel.component.amqp.transfer-exception | If enabled and you are using Request Reply messaging (InOut) and an Exchange failed on the consumer side, then the caused Exception will be send back in response as a javax.jms.ObjectMessage. If the client is Camel, the returned Exception is rethrown. This allows you to use Camel JMS as a bridge in your routing - for example, using persistent queues to enable robust routing. Notice that if you also have transferExchange enabled, this option takes precedence. The caught exception is required to be serializable. The original Exception on the consumer side can be wrapped in an outer exception such as org.apache.camel.RuntimeCamelException when returned to the producer. Use this with caution as the data is using Java Object serialization and requires the received to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumer!. | false | Boolean |
| camel.component.amqp.transfer-exchange | You can transfer the exchange over the wire instead of just the body and headers. The following fields are transferred: In body, Out body, Fault body, In headers, Out headers, Fault headers, exchange properties, exchange exception. This requires that the objects are serializable. Camel will exclude any non-serializable objects and log it at WARN level. You must enable this option on both the producer and consumer side, so Camel knows the payloads is an Exchange and not a regular payload. Use this with caution as the data is using Java Object serialization and requires the receiver to be able to deserialize the data at Class level, which forces a strong coupling between the producers and consumers having to use compatible Camel versions!. | false | Boolean |
| camel.component.amqp.use-message-id-as-correlation-id | Specifies whether JMSMessageID should always be used as JMSCorrelationID for InOut messages. | false | Boolean |
| camel.component.amqp.username | Username to use with the ConnectionFactory. You can also configure username/password directly on the ConnectionFactory. | String | |
| camel.component.amqp.wait-for-provision-correlation-to-be-updated-counter | Number of times to wait for provisional correlation id to be updated to the actual correlation id when doing request/reply over JMS and when the option useMessageIDAsCorrelationID is enabled. | 50 | Integer |
| camel.component.amqp.wait-for-provision-correlation-to-be-updated-thread-sleeping-time | Interval in millis to sleep each time while waiting for provisional correlation id to be updated. The option is a long type. | 100 | Long |
Chapter 3. Avro 링크 복사링크가 클립보드에 복사되었습니다!
This component provides a dataformat for avro, which allows serialization and deserialization of messages using Apache Avro’s binary dataformat. Since Camel 3.2 rpc functionality was moved into separate camel-avro-rpc component.
You can easily generate classes from a schema, using maven, ant etc. More details can be found at the Apache Avro documentation.
3.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using camel-avro with Red Hat build of Camel Spring Boot, add the following Maven dependency to have support for auto configuration:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-avro-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-avro-starter</artifactId>
</dependency>
3.2. Avro Dataformat Options 링크 복사링크가 클립보드에 복사되었습니다!
The Avro dataformat supports 1 options, which are listed below.
| Name | Default | Java Type | Description |
|---|---|---|---|
| instanceClassName |
| Class name to use for marshal and unmarshalling. |
3.3. Avro Data Format usage 링크 복사링크가 클립보드에 복사되었습니다!
Using the avro data format is as easy as specifying that the class that you want to marshal or unmarshal in your route.
AvroDataFormat format = new AvroDataFormat(Value.SCHEMA$);
from("direct:in").marshal(format).to("direct:marshal");
from("direct:back").unmarshal(format).to("direct:unmarshal");
AvroDataFormat format = new AvroDataFormat(Value.SCHEMA$);
from("direct:in").marshal(format).to("direct:marshal");
from("direct:back").unmarshal(format).to("direct:unmarshal");
Where Value is an Avro Maven Plugin Generated class.
or in XML
An alternative can be to specify the dataformat inside the context and reference it from your route.
In the same manner you can umarshal using the avro data format.
3.4. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
When using avro with Spring Boot make sure to add the Maven dependency to have support for auto configuration. The component supports 2 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.dataformat.avro.enabled | Whether to enable auto configuration of the avro data format. This is enabled by default. | Boolean | |
| camel.dataformat.avro.instance-class-name | Class name to use for marshal and unmarshalling. | String |
Chapter 4. Avro Jackson 링크 복사링크가 클립보드에 복사되었습니다!
Jackson Avro is a Data Format which uses the Jackson library with the Avro extension to unmarshal an Avro payload into Java objects or to marshal Java objects into an Avro payload.
If you are familiar with Jackson, this Avro data format behaves in the same way as its JSON counterpart, and thus can be used with classes annotated for JSON serialization/deserialization.
from("kafka:topic").
unmarshal().avro(AvroLibrary.Jackson, JsonNode.class).
to("log:info");
from("kafka:topic").
unmarshal().avro(AvroLibrary.Jackson, JsonNode.class).
to("log:info");
4.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using avro-jackson with Red Hat build of Camel Spring Boot make sure to add the Maven dependency to have support for auto configuration.
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-jackson-avro-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jackson-avro-starter</artifactId>
</dependency>
4.2. Configuring the SchemaResolver 링크 복사링크가 클립보드에 복사되었습니다!
Since Avro serialization is schema-based, this data format requires that you provide a SchemaResolver object that is able to lookup the schema for each exchange that is going to be marshalled/unmarshalled.
You can add a single SchemaResolver to the registry and it will be looked up automatically. Or you can explicitly specify the reference to a custom SchemaResolver.
4.3. Avro Jackson Options 링크 복사링크가 클립보드에 복사되었습니다!
The Avro Jackson dataformat supports 18 options, which are listed below.
| Name | Default | Java Type | Description |
|---|---|---|---|
| objectMapper |
| Lookup and use the existing ObjectMapper with the given id when using Jackson. | |
| useDefaultObjectMapper |
| Whether to lookup and use default Jackson ObjectMapper from the registry. | |
| unmarshalType |
| Class name of the java type to use when unmarshalling. | |
| jsonView |
| When marshalling a POJO to JSON you might want to exclude certain fields from the JSON output. With Jackson you can use JSON views to accomplish this. This option is to refer to the class which has JsonView annotations. | |
| include |
| If you want to marshal a pojo to JSON, and the pojo has some fields with null values. And you want to skip these null values, you can set this option to NON_NULL. | |
| allowJmsType |
| Used for JMS users to allow the JMSType header from the JMS spec to specify a FQN classname to use to unmarshal to. | |
| collectionType |
| Refers to a custom collection type to lookup in the registry to use. This option should rarely be used, but allows to use different collection types than java.util.Collection based as default. | |
| useList |
| To unmarshal to a List of Map or a List of Pojo. | |
| moduleClassNames |
| To use custom Jackson modules com.fasterxml.jackson.databind.Module specified as a String with FQN class names. Multiple classes can be separated by comma. | |
| moduleRefs |
| To use custom Jackson modules referred from the Camel registry. Multiple modules can be separated by comma. | |
| enableFeatures |
| Set of features to enable on the Jackson com.fasterxml.jackson.databind.ObjectMapper. The features should be a name that matches a enum from com.fasterxml.jackson.databind.SerializationFeature, com.fasterxml.jackson.databind.DeserializationFeature, or com.fasterxml.jackson.databind.MapperFeature Multiple features can be separated by comma. | |
| disableFeatures |
| Set of features to disable on the Jackson com.fasterxml.jackson.databind.ObjectMapper. The features should be a name that matches a enum from com.fasterxml.jackson.databind.SerializationFeature, com.fasterxml.jackson.databind.DeserializationFeature, or com.fasterxml.jackson.databind.MapperFeature Multiple features can be separated by comma. | |
| allowUnmarshallType |
| If enabled then Jackson is allowed to attempt to use the CamelJacksonUnmarshalType header during the unmarshalling. This should only be enabled when desired to be used. | |
| timezone |
| If set then Jackson will use the Timezone when marshalling/unmarshalling. | |
| autoDiscoverObjectMapper |
| If set to true then Jackson will lookup for an objectMapper into the registry. | |
| contentTypeHeader |
| Whether the data format should set the Content-Type header with the type from the data format. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSON. | |
| schemaResolver |
| Optional schema resolver used to lookup schemas for the data in transit. | |
| autoDiscoverSchemaResolver |
| When not disabled, the SchemaResolver will be looked up into the registry. |
4.4. Using custom AvroMapper 링크 복사링크가 클립보드에 복사되었습니다!
You can configure JacksonAvroDataFormat to use a custom AvroMapper in case you need more control of the mapping configuration.
If you setup a single AvroMapper in the registry, then Camel will automatic lookup and use this AvroMapper.
4.5. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 19 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.dataformat.avro-jackson.allow-jms-type | Used for JMS users to allow the JMSType header from the JMS spec to specify a FQN classname to use to unmarshal to. | false | Boolean |
| camel.dataformat.avro-jackson.allow-unmarshall-type | If enabled then Jackson is allowed to attempt to use the CamelJacksonUnmarshalType header during the unmarshalling. This should only be enabled when desired to be used. | false | Boolean |
| camel.dataformat.avro-jackson.auto-discover-object-mapper | If set to true then Jackson will lookup for an objectMapper into the registry. | false | Boolean |
| camel.dataformat.avro-jackson.auto-discover-schema-resolver | When not disabled, the SchemaResolver will be looked up into the registry. | true | Boolean |
| camel.dataformat.avro-jackson.collection-type | Refers to a custom collection type to lookup in the registry to use. This option should rarely be used, but allows to use different collection types than java.util.Collection based as default. | String | |
| camel.dataformat.avro-jackson.content-type-header | Whether the data format should set the Content-Type header with the type from the data format. For example application/xml for data formats marshalling to XML, or application/json for data formats marshalling to JSON. | true | Boolean |
| camel.dataformat.avro-jackson.disable-features | Set of features to disable on the Jackson com.fasterxml.jackson.databind.ObjectMapper. The features should be a name that matches a enum from com.fasterxml.jackson.databind.SerializationFeature, com.fasterxml.jackson.databind.DeserializationFeature, or com.fasterxml.jackson.databind.MapperFeature Multiple features can be separated by comma. | String | |
| camel.dataformat.avro-jackson.enable-features | Set of features to enable on the Jackson com.fasterxml.jackson.databind.ObjectMapper. The features should be a name that matches a enum from com.fasterxml.jackson.databind.SerializationFeature, com.fasterxml.jackson.databind.DeserializationFeature, or com.fasterxml.jackson.databind.MapperFeature Multiple features can be separated by comma. | String | |
| camel.dataformat.avro-jackson.enabled | Whether to enable auto configuration of the avro-jackson data format. This is enabled by default. | Boolean | |
| camel.dataformat.avro-jackson.include | If you want to marshal a pojo to JSON, and the pojo has some fields with null values. And you want to skip these null values, you can set this option to NON_NULL. | String | |
| camel.dataformat.avro-jackson.json-view | When marshalling a POJO to JSON you might want to exclude certain fields from the JSON output. With Jackson you can use JSON views to accomplish this. This option is to refer to the class which has JsonView annotations. | String | |
| camel.dataformat.avro-jackson.module-class-names | To use custom Jackson modules com.fasterxml.jackson.databind.Module specified as a String with FQN class names. Multiple classes can be separated by comma. | String | |
| camel.dataformat.avro-jackson.module-refs | To use custom Jackson modules referred from the Camel registry. Multiple modules can be separated by comma. | String | |
| camel.dataformat.avro-jackson.object-mapper | Lookup and use the existing ObjectMapper with the given id when using Jackson. | String | |
| camel.dataformat.avro-jackson.schema-resolver | Optional schema resolver used to lookup schemas for the data in transit. | String | |
| camel.dataformat.avro-jackson.timezone | If set then Jackson will use the Timezone when marshalling/unmarshalling. | String | |
| camel.dataformat.avro-jackson.unmarshal-type | Class name of the java type to use when unmarshalling. | String | |
| camel.dataformat.avro-jackson.use-default-object-mapper | Whether to lookup and use default Jackson ObjectMapper from the registry. | true | Boolean |
| camel.dataformat.avro-jackson.use-list | To unmarshal to a List of Map or a List of Pojo. | false | Boolean |
Chapter 5. AWS CloudWatch 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The AWS2 Cloudwatch component allows messages to be sent to an Amazon CloudWatch metrics. The implementation of the Amazon API is provided by the AWS SDK.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon CloudWatch. More information is available at Amazon CloudWatch.
5.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-cw with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-cw-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-cw-starter</artifactId>
</dependency>
5.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-cw://namespace[?options]
aws2-cw://namespace[?options]
The metrics will be created if they don’t already exists. You can append query options to the URI in the following format, ?options=value&option2=value&…
5.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
5.3.1. 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.
5.3.2. 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.
5.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS CloudWatch component supports 18 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amazonCwClient (producer) | Autowired To use the AmazonCloudWatch as the client. | CloudWatchClient | |
| configuration (producer) | The component configuration. | Cw2Configuration | |
| 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 |
| name (producer) | The metric name. | String | |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| proxyHost (producer) | To define a proxy host when instantiating the CW client. | String | |
| proxyPort (producer) | To define a proxy port when instantiating the CW client. | Integer | |
| proxyProtocol (producer) | To define a proxy protocol when instantiating the CW client. Enum values:
| HTTPS | Protocol |
| region (producer) | The region in which CW client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| timestamp (producer) | The metric timestamp. | Instant | |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| unit (producer) | The metric unit. | String | |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| value (producer) | The metric value. | Double | |
| 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 |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
5.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS CloudWatch endpoint is configured using URI syntax:
aws2-cw:namespace
aws2-cw:namespace
with the following path and query parameters:
5.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| namespace (producer) | Required The metric namespace. | String |
5.5.2. Query Parameters (16 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amazonCwClient (producer) | Autowired To use the AmazonCloudWatch as the client. | CloudWatchClient | |
| 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 |
| name (producer) | The metric name. | String | |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| proxyHost (producer) | To define a proxy host when instantiating the CW client. | String | |
| proxyPort (producer) | To define a proxy port when instantiating the CW client. | Integer | |
| proxyProtocol (producer) | To define a proxy protocol when instantiating the CW client. Enum values:
| HTTPS | Protocol |
| region (producer) | The region in which CW client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| timestamp (producer) | The metric timestamp. | Instant | |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| unit (producer) | The metric unit. | String | |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| value (producer) | The metric value. | Double | |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
Required CW component options
You have to provide the amazonCwClient in the Registry or your accessKey and secretKey to access the Amazon’s CloudWatch.
5.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
5.6.1. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
- Java system properties - aws.accessKeyId and aws.secretKey
- Environment variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- Web Identity Token from AWS STS.
- The shared credentials and config files.
- Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
- Amazon EC2 Instance profile credentials.
For more information about this you can look at AWS credentials documentation
5.6.2. Message headers evaluated by the CW producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The Amazon CW metric name. |
|
|
| The Amazon CW metric value. |
|
|
| The Amazon CW metric unit. |
|
|
| The Amazon CW metric namespace. |
|
|
| The Amazon CW metric timestamp. |
|
|
| The Amazon CW metric dimension name. |
|
|
| The Amazon CW metric dimension value. |
|
|
| A map of dimension names and dimension values. |
5.6.3. Advanced CloudWatchClient configuration 링크 복사링크가 클립보드에 복사되었습니다!
If you need more control over the CloudWatchClient instance configuration you can create your own instance and refer to it from the URI:
from("direct:start")
.to("aws2-cw://namespace?amazonCwClient=#client");
from("direct:start")
.to("aws2-cw://namespace?amazonCwClient=#client");
The #client refers to a CloudWatchClient in the Registry.
5.7. Examples 링크 복사링크가 클립보드에 복사되었습니다!
5.7.1. Producer Example 링크 복사링크가 클립보드에 복사되었습니다!
from("direct:start")
.to("aws2-cw://http://camel.apache.org/aws-cw");
from("direct:start")
.to("aws2-cw://http://camel.apache.org/aws-cw");
and sends something like
exchange.getIn().setHeader(Cw2Constants.METRIC_NAME, "ExchangesCompleted"); exchange.getIn().setHeader(Cw2Constants.METRIC_VALUE, "2.0"); exchange.getIn().setHeader(Cw2Constants.METRIC_UNIT, "Count");
exchange.getIn().setHeader(Cw2Constants.METRIC_NAME, "ExchangesCompleted");
exchange.getIn().setHeader(Cw2Constants.METRIC_VALUE, "2.0");
exchange.getIn().setHeader(Cw2Constants.METRIC_UNIT, "Count");
5.8. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 19 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-cw.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-cw.amazon-cw-client | To use the AmazonCloudWatch as the client. The option is a software.amazon.awssdk.services.cloudwatch.CloudWatchClient type. | CloudWatchClient | |
| camel.component.aws2-cw.autowired-enabled | 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 |
| camel.component.aws2-cw.configuration | The component configuration. The option is a org.apache.camel.component.aws2.cw.Cw2Configuration type. | Cw2Configuration | |
| camel.component.aws2-cw.enabled | Whether to enable auto configuration of the aws2-cw component. This is enabled by default. | Boolean | |
| camel.component.aws2-cw.lazy-start-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 |
| camel.component.aws2-cw.name | The metric name. | String | |
| camel.component.aws2-cw.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-cw.proxy-host | To define a proxy host when instantiating the CW client. | String | |
| camel.component.aws2-cw.proxy-port | To define a proxy port when instantiating the CW client. | Integer | |
| camel.component.aws2-cw.proxy-protocol | To define a proxy protocol when instantiating the CW client. | Protocol | |
| camel.component.aws2-cw.region | The region in which CW client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-cw.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-cw.timestamp | The metric timestamp. The option is a java.time.Instant type. | Instant | |
| camel.component.aws2-cw.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-cw.unit | The metric unit. | String | |
| camel.component.aws2-cw.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-cw.use-default-credentials-provider | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
| camel.component.aws2-cw.value | The metric value. | Double |
Chapter 6. AWS DynamoDB 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The AWS2 DynamoDB component supports storing and retrieving data from/to service.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon DynamoDB. More information is available at Amazon DynamoDB.
6.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-ddb Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-ddb-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-ddb-starter</artifactId>
</dependency>
6.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-ddb://domainName[?options]
aws2-ddb://domainName[?options]
You can append query options to the URI in the following format, ?options=value&option2=value&…
6.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
6.3.1. 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.
6.3.2. 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.
6.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS DynamoDB component supports 22 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amazonDDBClient (producer) | Autowired To use the AmazonDynamoDB as the client. | DynamoDbClient | |
| configuration (producer) | The component configuration. | Ddb2Configuration | |
| consistentRead (producer) | Determines whether or not strong consistency should be enforced when data is read. | false | boolean |
| enabledInitialDescribeTable (producer) | Set whether the initial Describe table operation in the DDB Endpoint must be done, or not. | true | boolean |
| keyAttributeName (producer) | Attribute name when creating table. | String | |
| keyAttributeType (producer) | Attribute type when creating table. | String | |
| keyScalarType (producer) | The key scalar type, it can be S (String), N (Number) and B (Bytes). | String | |
| 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 |
| operation (producer) | What operation to perform. Enum values:
| PutItem | Ddb2Operations |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| proxyHost (producer) | To define a proxy host when instantiating the DDB client. | String | |
| proxyPort (producer) | The region in which DynamoDB client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | Integer | |
| proxyProtocol (producer) | To define a proxy protocol when instantiating the DDB client. Enum values:
| HTTPS | Protocol |
| readCapacity (producer) | The provisioned throughput to reserve for reading resources from your table. | Long | |
| region (producer) | The region in which DDB client needs to work. | String | |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| writeCapacity (producer) | The provisioned throughput to reserved for writing resources to your table. | Long | |
| 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 |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
6.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS DynamoDB endpoint is configured using URI syntax:
aws2-ddb:tableName
aws2-ddb:tableName
with the following path and query parameters:
6.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| tableName (producer) | Required The name of the table currently worked with. | String |
6.5.2. Query Parameters (20 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amazonDDBClient (producer) | Autowired To use the AmazonDynamoDB as the client. | DynamoDbClient | |
| consistentRead (producer) | Determines whether or not strong consistency should be enforced when data is read. | false | boolean |
| enabledInitialDescribeTable (producer) | Set whether the initial Describe table operation in the DDB Endpoint must be done, or not. | true | boolean |
| keyAttributeName (producer) | Attribute name when creating table. | String | |
| keyAttributeType (producer) | Attribute type when creating table. | String | |
| keyScalarType (producer) | The key scalar type, it can be S (String), N (Number) and B (Bytes). | String | |
| 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 |
| operation (producer) | What operation to perform. Enum values:
| PutItem | Ddb2Operations |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| proxyHost (producer) | To define a proxy host when instantiating the DDB client. | String | |
| proxyPort (producer) | The region in which DynamoDB client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | Integer | |
| proxyProtocol (producer) | To define a proxy protocol when instantiating the DDB client. Enum values:
| HTTPS | Protocol |
| readCapacity (producer) | The provisioned throughput to reserve for reading resources from your table. | Long | |
| region (producer) | The region in which DDB client needs to work. | String | |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| writeCapacity (producer) | The provisioned throughput to reserved for writing resources to your table. | Long | |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
Required DDB component options
You have to provide the amazonDDBClient in the Registry or your accessKey and secretKey to access the Amazon’s DynamoDB.
6.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
6.6.1. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
- Java system properties - aws.accessKeyId and aws.secretKey
- Environment variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- Web Identity Token from AWS STS.
- The shared credentials and config files.
- Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
- Amazon EC2 Instance profile credentials.
For more information about this you can look at AWS credentials documentation
6.6.2. Message headers evaluated by the DDB producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| A map of the table name and corresponding items to get by primary key. |
|
|
| Table Name for this operation. |
|
|
| The primary key that uniquely identifies each item in a table. |
|
|
| Use this parameter if you want to get the attribute name-value pairs before or after they are modified(NONE, ALL_OLD, UPDATED_OLD, ALL_NEW, UPDATED_NEW). |
|
|
| Designates an attribute for a conditional modification. |
|
|
| If attribute names are not specified then all attributes will be returned. |
|
|
| If set to true, then a consistent read is issued, otherwise eventually consistent is used. |
|
|
| If set will be used as Secondary Index for Query operation. |
|
|
| A map of the attributes for the item, and must include the primary key values that define the item. |
|
|
| If set to true, Amazon DynamoDB returns a total number of items that match the query parameters, instead of a list of the matching items and their attributes. |
|
|
| This header specify the selection criteria for the query, and merge together the two old headers CamelAwsDdbHashKeyValue and CamelAwsDdbScanRangeKeyCondition |
|
|
| Primary key of the item from which to continue an earlier query. |
|
|
| Value of the hash component of the composite primary key. |
|
|
| The maximum number of items to return. |
|
|
| A container for the attribute values and comparison operators to use for the query. |
|
|
| Specifies forward or backward traversal of the index. |
|
|
| Evaluates the scan results and returns only the desired values. |
|
|
| Map of attribute name to the new value and action for the update. |
6.6.3. Message headers set during BatchGetItems operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| Table names and the respective item attributes from the tables. |
|
|
| Contains a map of tables and their respective keys that were not processed with the current response. |
6.6.4. Message headers set during DeleteItem operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The list of attributes returned by the operation. |
6.6.5. Message headers set during DeleteTable operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
| ||
|
| The value of the ProvisionedThroughput property for this table | |
|
|
| Creation DateTime of this table. |
|
|
| Item count for this table. |
|
|
| The KeySchema that identifies the primary key for this table. From Camel 2.16.0 the type of this header is List<KeySchemaElement> and not KeySchema |
|
|
| The table name. |
|
|
| The table size in bytes. |
|
|
| The status of the table: CREATING, UPDATING, DELETING, ACTIVE |
6.6.6. Message headers set during DescribeTable operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
| \{{ProvisionedThroughputDescription}} | The value of the ProvisionedThroughput property for this table |
|
|
| Creation DateTime of this table. |
|
|
| Item count for this table. |
|
| \{{KeySchema}} | The KeySchema that identifies the primary key for this table. |
|
|
| The table name. |
|
|
| The table size in bytes. |
|
|
| The status of the table: CREATING, UPDATING, DELETING, ACTIVE |
|
|
| ReadCapacityUnits property of this table. |
|
|
| WriteCapacityUnits property of this table. |
6.6.7. Message headers set during GetItem operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The list of attributes returned by the operation. |
6.6.8. Message headers set during PutItem operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The list of attributes returned by the operation. |
6.6.9. Message headers set during Query operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The list of attributes returned by the operation. |
|
|
| Primary key of the item where the query operation stopped, inclusive of the previous result set. |
|
|
| The number of Capacity Units of the provisioned throughput of the table consumed during the operation. |
|
|
| Number of items in the response. |
6.6.10. Message headers set during Scan operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The list of attributes returned by the operation. |
|
|
| Primary key of the item where the query operation stopped, inclusive of the previous result set. |
|
|
| The number of Capacity Units of the provisioned throughput of the table consumed during the operation. |
|
|
| Number of items in the response. |
|
|
| Number of items in the complete scan before any filters are applied. |
6.6.11. Message headers set during UpdateItem operation 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The list of attributes returned by the operation. |
6.6.12. Advanced AmazonDynamoDB configuration 링크 복사링크가 클립보드에 복사되었습니다!
If you need more control over the AmazonDynamoDB instance configuration you can create your own instance and refer to it from the URI:
from("direct:start")
.to("aws2-ddb://domainName?amazonDDBClient=#client");
from("direct:start")
.to("aws2-ddb://domainName?amazonDDBClient=#client");
The #client refers to a DynamoDbClient in the Registry.
6.7. Supported producer operations 링크 복사링크가 클립보드에 복사되었습니다!
- BatchGetItems
- DeleteItem
- DeleteTable
- DescribeTable
- GetItem
- PutItem
- Query
- Scan
- UpdateItem
- UpdateTable
6.8. Examples 링크 복사링크가 클립보드에 복사되었습니다!
6.8.1. Producer Examples 링크 복사링크가 클립보드에 복사되었습니다!
- PutItem: this operation will create an entry into DynamoDB
Maven users will need to add the following dependency to their pom.xml.
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-ddb</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-ddb</artifactId>
<version>${camel-version}</version>
</dependency>
where {camel-version} must be replaced by the actual version of Camel.
6.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 40 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-ddb.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-ddb.amazon-d-d-b-client | To use the AmazonDynamoDB as the client. The option is a software.amazon.awssdk.services.dynamodb.DynamoDbClient type. | DynamoDbClient | |
| camel.component.aws2-ddb.autowired-enabled | 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 |
| camel.component.aws2-ddb.configuration | The component configuration. The option is a org.apache.camel.component.aws2.ddb.Ddb2Configuration type. | Ddb2Configuration | |
| camel.component.aws2-ddb.consistent-read | Determines whether or not strong consistency should be enforced when data is read. | false | Boolean |
| camel.component.aws2-ddb.enabled | Whether to enable auto configuration of the aws2-ddb component. This is enabled by default. | Boolean | |
| camel.component.aws2-ddb.enabled-initial-describe-table | Set whether the initial Describe table operation in the DDB Endpoint must be done, or not. | true | Boolean |
| camel.component.aws2-ddb.key-attribute-name | Attribute name when creating table. | String | |
| camel.component.aws2-ddb.key-attribute-type | Attribute type when creating table. | String | |
| camel.component.aws2-ddb.key-scalar-type | The key scalar type, it can be S (String), N (Number) and B (Bytes). | String | |
| camel.component.aws2-ddb.lazy-start-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 |
| camel.component.aws2-ddb.operation | What operation to perform. | Ddb2Operations | |
| camel.component.aws2-ddb.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-ddb.proxy-host | To define a proxy host when instantiating the DDB client. | String | |
| camel.component.aws2-ddb.proxy-port | The region in which DynamoDB client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | Integer | |
| camel.component.aws2-ddb.proxy-protocol | To define a proxy protocol when instantiating the DDB client. | Protocol | |
| camel.component.aws2-ddb.read-capacity | The provisioned throughput to reserve for reading resources from your table. | Long | |
| camel.component.aws2-ddb.region | The region in which DDB client needs to work. | String | |
| camel.component.aws2-ddb.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-ddb.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-ddb.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-ddb.use-default-credentials-provider | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
| camel.component.aws2-ddb.write-capacity | The provisioned throughput to reserved for writing resources to your table. | Long | |
| camel.component.aws2-ddbstream.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-ddbstream.amazon-dynamo-db-streams-client | Amazon DynamoDB client to use for all requests for this endpoint. The option is a software.amazon.awssdk.services.dynamodb.streams.DynamoDbStreamsClient type. | DynamoDbStreamsClient | |
| camel.component.aws2-ddbstream.autowired-enabled | 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 |
| camel.component.aws2-ddbstream.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.aws2-ddbstream.configuration | The component configuration. The option is a org.apache.camel.component.aws2.ddbstream.Ddb2StreamConfiguration type. | Ddb2StreamConfiguration | |
| camel.component.aws2-ddbstream.enabled | Whether to enable auto configuration of the aws2-ddbstream component. This is enabled by default. | Boolean | |
| camel.component.aws2-ddbstream.max-results-per-request | Maximum number of records that will be fetched in each poll. | Integer | |
| camel.component.aws2-ddbstream.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-ddbstream.proxy-host | To define a proxy host when instantiating the DDBStreams client. | String | |
| camel.component.aws2-ddbstream.proxy-port | To define a proxy port when instantiating the DDBStreams client. | Integer | |
| camel.component.aws2-ddbstream.proxy-protocol | To define a proxy protocol when instantiating the DDBStreams client. | Protocol | |
| camel.component.aws2-ddbstream.region | The region in which DDBStreams client needs to work. | String | |
| camel.component.aws2-ddbstream.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-ddbstream.stream-iterator-type | Defines where in the DynamoDB stream to start getting records. Note that using FROM_START can cause a significant delay before the stream has caught up to real-time. | Ddb2StreamConfiguration$StreamIteratorType | |
| camel.component.aws2-ddbstream.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-ddbstream.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-ddbstream.use-default-credentials-provider | Set whether the DynamoDB Streams client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
Chapter 7. AWS Kinesis 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The AWS2 Kinesis component supports receiving messages from and sending messages to Amazon Kinesis (no Batch supported) service.
The AWS2 Kinesis component also supports Synchronous and Asynchronous Client. So if you need the connection (client) to be async, configure the 'asyncClient' option (can be found in DSL also) as true.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Kinesis. More information are available at AWS Kinesis.
7.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-kinesis Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-kinesis-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-kinesis-starter</artifactId>
</dependency>
7.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-kinesis://stream-name[?options]
aws2-kinesis://stream-name[?options]
The stream needs to be created prior to it being used. You can append query options to the URI in the following format, ?options=value&option2=value&…
7.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
7.3.1. 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.
7.3.2. 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.
7.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Kinesis component supports 28 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amazonKinesisClient (common) | Autowired Amazon Kinesis client to use for all requests for this endpoint. | KinesisClient | |
| cborEnabled (common) | This option will set the CBOR_ENABLED property during the execution. | true | boolean |
| configuration (common) | Component configuration. | Kinesis2Configuration | |
| overrideEndpoint (common) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| proxyHost (common) | To define a proxy host when instantiating the Kinesis client. | String | |
| proxyPort (common) | To define a proxy port when instantiating the Kinesis client. | Integer | |
| proxyProtocol (common) | To define a proxy protocol when instantiating the Kinesis client. Enum values:
| HTTPS | Protocol |
| region (common) | The region in which Kinesis Firehose client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (common) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (common) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (common) | Set whether the Kinesis client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| iteratorType (consumer) | Defines where in the Kinesis stream to start getting records. Enum values:
| TRIM_HORIZON | ShardIteratorType |
| maxResultsPerRequest (consumer) | Maximum number of records that will be fetched in each poll. | 1 | int |
| resumeStrategy (consumer) | Defines a resume strategy for AWS Kinesis. The default strategy reads the sequenceNumber if provided. | KinesisUserConfigurationResumeStrategy | KinesisResumeStrategy |
| sequenceNumber (consumer) | The sequence number to start polling from. Required if iteratorType is set to AFTER_SEQUENCE_NUMBER or AT_SEQUENCE_NUMBER. | String | |
| shardClosed (consumer) | Define what will be the behavior in case of shard closed. Possible value are ignore, silent and fail. In case of ignore a message will be logged and the consumer will restart from the beginning,in case of silent there will be no logging and the consumer will start from the beginning,in case of fail a ReachedClosedStateException will be raised. Enum values:
| ignore | Kinesis2ShardClosedStrategyEnum |
| shardId (consumer) | Defines which shardId in the Kinesis stream to get records from. | String | |
| 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 |
| asyncClient (advanced) | If we want to a KinesisAsyncClient instance set it to true. | 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 |
| healthCheckConsumerEnabled (health) | Used for enabling or disabling all consumer based health checks from this component. | true | boolean |
| healthCheckProducerEnabled (health) |
Used for enabling or disabling all producer based health checks from this component. NOTE: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting | true | boolean |
| accessKey (security) | Amazon AWS Access Key. | String | |
| profileCredentialsName (security) | If using a profile credentials provider this parameter will set the profile name. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String | |
| sessionToken (security) | Amazon AWS Session Token used when the user needs to assume a IAM role. | String | |
| trustAllCertificates (security) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| useDefaultCredentialsProvider (security) | Set whether the Kinesis client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| useProfileCredentialsProvider (security) | Set whether the Kinesis client should expect to load credentials through a profile credentials provider. | false | boolean |
| useSessionCredentials (security) | Set whether the Kinesis client should expect to use Session Credentials. This is useful in situation in which the user needs to assume a IAM role for doing operations in Kinesis. | false | boolean |
7.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Kinesis endpoint is configured using URI syntax:
aws2-kinesis:streamName
aws2-kinesis:streamName
with the following path and query parameters:
7.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| streamName (common) | Required Name of the stream. | String |
7.5.2. Query Parameters (42 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amazonKinesisClient (common) | Autowired Amazon Kinesis client to use for all requests for this endpoint. | KinesisClient | |
| cborEnabled (common) | This option will set the CBOR_ENABLED property during the execution. | true | boolean |
| overrideEndpoint (common) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| proxyHost (common) | To define a proxy host when instantiating the Kinesis client. | String | |
| proxyPort (common) | To define a proxy port when instantiating the Kinesis client. | Integer | |
| proxyProtocol (common) | To define a proxy protocol when instantiating the Kinesis client. Enum values:
| HTTPS | Protocol |
| region (common) | The region in which Kinesis Firehose client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (common) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (common) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (common) | Set whether the Kinesis client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| iteratorType (consumer) | Defines where in the Kinesis stream to start getting records. Enum values:
| TRIM_HORIZON | ShardIteratorType |
| maxResultsPerRequest (consumer) | Maximum number of records that will be fetched in each poll. | 1 | int |
| resumeStrategy (consumer) | Defines a resume strategy for AWS Kinesis. The default strategy reads the sequenceNumber if provided. | KinesisUserConfigurationResumeStrategy | KinesisResumeStrategy |
| sendEmptyMessageWhenIdle (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean |
| sequenceNumber (consumer) | The sequence number to start polling from. Required if iteratorType is set to AFTER_SEQUENCE_NUMBER or AT_SEQUENCE_NUMBER. | String | |
| shardClosed (consumer) | Define what will be the behavior in case of shard closed. Possible value are ignore, silent and fail. In case of ignore a message will be logged and the consumer will restart from the beginning,in case of silent there will be no logging and the consumer will start from the beginning,in case of fail a ReachedClosedStateException will be raised. Enum values:
| ignore | Kinesis2ShardClosedStrategyEnum |
| shardId (consumer) | Defines which shardId in the Kinesis stream to get records from. | String | |
| 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:
| ExchangePattern | |
| pollStrategy (consumer (advanced)) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | |
| 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 |
| asyncClient (advanced) | If we want to a KinesisAsyncClient instance set it to true. | false | boolean |
| backoffErrorThreshold (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | |
| backoffIdleThreshold (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | |
| backoffMultiplier (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | |
| delay (scheduler) | Milliseconds before the next poll. | 500 | long |
| greedy (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean |
| initialDelay (scheduler) | Milliseconds before the first poll starts. | 1000 | long |
| repeatCount (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long |
| runLoggingLevel (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel |
| scheduledExecutorService (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | |
| scheduler (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object |
| schedulerProperties (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | Map | |
| startScheduler (scheduler) | Whether the scheduler should be auto started. | true | boolean |
| timeUnit (scheduler) | Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit |
| useFixedDelay (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
| accessKey (security) | Amazon AWS Access Key. | String | |
| profileCredentialsName (security) | If using a profile credentials provider this parameter will set the profile name. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String | |
| sessionToken (security) | Amazon AWS Session Token used when the user needs to assume a IAM role. | String | |
| trustAllCertificates (security) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| useDefaultCredentialsProvider (security) | Set whether the Kinesis client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| useProfileCredentialsProvider (security) | Set whether the Kinesis client should expect to load credentials through a profile credentials provider. | false | boolean |
| useSessionCredentials (security) | Set whether the Kinesis client should expect to use Session Credentials. This is useful in situation in which the user needs to assume a IAM role for doing operations in Kinesis. | false | boolean |
Required Kinesis component options
You have to provide the KinesisClient in the Registry with proxies and relevant credentials configured.
7.6. Batch Consumer 링크 복사링크가 클립보드에 복사되었습니다!
This component implements the Batch Consumer.
This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.
The consumer is able to consume either from a single specific shard or all available shards (multiple shards consumption) of Amazon Kinesis. Therefore, if you leave the 'shardId' property in the DSL configuration empty, then it’ll consume all available shards otherwise only the specified shard corresponding to the shardId will be consumed.
7.7. Usage 링크 복사링크가 클립보드에 복사되었습니다!
7.7.1. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
The order of evaluation for Default Credentials Provider is the following:
-
Java system properties -
aws.accessKeyIdandaws.secretKey -
Environment variables -
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. - Web Identity Token from AWS STS.
- The shared credentials and config files.
-
Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable
AWS_CONTAINER_CREDENTIALS_RELATIVE_URIis set. - Amazon EC2 Instance profile credentials.
You have also the possibility of using Profile Credentials Provider, by specifying the useProfileCredentialsProvider option to true and profileCredentialsName to the profile name.
Only one of static, default and profile credentials could be used at the same time.
For more information see AWS credentials documentation.
7.8. Message headers 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description |
|---|---|
| CamelAwsKinesisSequenceNumber (common) Constant: SEQUENCE_NUMBER | The sequence number of the record as defined in PutRecord syntax. |
| CamelAwsKinesisApproximateArrivalTimestamp (common) Constant: APPROX_ARRIVAL_TIME | The time AWS assigned as the arrival time of the record. |
| CamelAwsKinesisPartitionKey (common) Constant: PARTITION_KEY | Identifies which shard in the stream the data record is assigned to. |
| CamelMessageTimestamp (common) Constant: MESSAGE_TIMESTAMP | The timestamp of the message. |
| CamelAwsKinesisShardId (common) Constant: SHARD_ID | The shard ID of the shard where the data record was place |
7.8.1. AmazonKinesis configuration 링크 복사링크가 클립보드에 복사되었습니다!
You then have to reference the KinesisClient in the amazonKinesisClient URI option.
from("aws2-kinesis://mykinesisstream?amazonKinesisClient=#kinesisClient")
.to("log:out?showAll=true");
from("aws2-kinesis://mykinesisstream?amazonKinesisClient=#kinesisClient")
.to("log:out?showAll=true");
7.8.2. Providing AWS Credentials 링크 복사링크가 클립보드에 복사되었습니다!
It is recommended that the credentials are obtained by using the DefaultAWSCredentialsProviderChain that is the default when creating a new ClientConfiguration instance, however, a different AWSCredentialsProvider can be specified when calling createClient(…).
7.8.3. AWS Kinesis KCL Consumer 링크 복사링크가 클립보드에 복사되었습니다!
The component supports also the KCL (Kinesis Client Library) for consuming from a Kinesis Data Stream. To enable this feature, set two different parameters in your endpoint:
from("aws2-kinesis://mykinesisstream?asyncClient=true&useDefaultCredentialsProvider=true&useKclConsumers=true")
.to("log:out?showAll=true");
from("aws2-kinesis://mykinesisstream?asyncClient=true&useDefaultCredentialsProvider=true&useKclConsumers=true")
.to("log:out?showAll=true");
This feature makes it possible to automatically checkpoint the Shard Iterations by combining the usage of KCL, DynamoDB Table and CloudWatch alarms. This works out of the box, by simply using your AWS Credentials.
AWS Kinesis consumer with KCL needs approximately 60-70 seconds to startup.
7.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 50 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-kinesis-firehose.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-kinesis-firehose.amazon-kinesis-firehose-client | Amazon Kinesis Firehose client to use for all requests for this endpoint. The option is a software.amazon.awssdk.services.firehose.FirehoseClient type. | FirehoseClient | |
| camel.component.aws2-kinesis-firehose.autowired-enabled | 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 |
| camel.component.aws2-kinesis-firehose.cbor-enabled | This option will set the CBOR_ENABLED property during the execution. | true | Boolean |
| camel.component.aws2-kinesis-firehose.configuration | Component configuration. The option is a org.apache.camel.component.aws2.firehose.KinesisFirehose2Configuration type. | KinesisFirehose2Configuration | |
| camel.component.aws2-kinesis-firehose.enabled | Whether to enable auto configuration of the aws2-kinesis-firehose component. This is enabled by default. | Boolean | |
| camel.component.aws2-kinesis-firehose.lazy-start-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 |
| camel.component.aws2-kinesis-firehose.operation | The operation to do in case the user don’t want to send only a record. | KinesisFirehose2Operations | |
| camel.component.aws2-kinesis-firehose.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-kinesis-firehose.profile-credentials-name | If using a profile credentials provider this parameter will set the profile name. | String | |
| camel.component.aws2-kinesis-firehose.proxy-host | To define a proxy host when instantiating the Kinesis Firehose client. | String | |
| camel.component.aws2-kinesis-firehose.proxy-port | To define a proxy port when instantiating the Kinesis Firehose client. | Integer | |
| camel.component.aws2-kinesis-firehose.proxy-protocol | To define a proxy protocol when instantiating the Kinesis Firehose client. | Protocol | |
| camel.component.aws2-kinesis-firehose.region | The region in which Kinesis Firehose client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-kinesis-firehose.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-kinesis-firehose.session-token | Amazon AWS Session Token used when the user needs to assume a IAM role. | String | |
| camel.component.aws2-kinesis-firehose.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-kinesis-firehose.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-kinesis-firehose.use-default-credentials-provider | Set whether the Kinesis Firehose client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
| camel.component.aws2-kinesis-firehose.use-profile-credentials-provider | Set whether the Kinesis Firehose client should expect to load credentials through a profile credentials provider. | false | Boolean |
| camel.component.aws2-kinesis-firehose.use-session-credentials | Set whether the Kinesis Firehose client should expect to use Session Credentials. This is useful in situation in which the user needs to assume a IAM role for doing operations in Kinesis Firehose. | false | Boolean |
| camel.component.aws2-kinesis.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-kinesis.amazon-kinesis-client | Amazon Kinesis client to use for all requests for this endpoint. The option is a software.amazon.awssdk.services.kinesis.KinesisClient type. | KinesisClient | |
| camel.component.aws2-kinesis.async-client | If we want to a KinesisAsyncClient instance set it to true. | false | Boolean |
| camel.component.aws2-kinesis.autowired-enabled | 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 |
| camel.component.aws2-kinesis.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.aws2-kinesis.cbor-enabled | This option will set the CBOR_ENABLED property during the execution. | true | Boolean |
| camel.component.aws2-kinesis.configuration | Component configuration. The option is a org.apache.camel.component.aws2.kinesis.Kinesis2Configuration type. | Kinesis2Configuration | |
| camel.component.aws2-kinesis.enabled | Whether to enable auto configuration of the aws2-kinesis component. This is enabled by default. | Boolean | |
| camel.component.aws2-kinesis.health-check-consumer-enabled | Used for enabling or disabling all consumer based health checks from this component. | true | Boolean |
| camel.component.aws2-kinesis.health-check-producer-enabled |
Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting | true | Boolean |
| camel.component.aws2-kinesis.iterator-type | Defines where in the Kinesis stream to start getting records. | ShardIteratorType | |
| camel.component.aws2-kinesis.lazy-start-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 |
| camel.component.aws2-kinesis.max-results-per-request | Maximum number of records that will be fetched in each poll. | 1 | Integer |
| camel.component.aws2-kinesis.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-kinesis.profile-credentials-name | If using a profile credentials provider this parameter will set the profile name. | String | |
| camel.component.aws2-kinesis.proxy-host | To define a proxy host when instantiating the Kinesis client. | String | |
| camel.component.aws2-kinesis.proxy-port | To define a proxy port when instantiating the Kinesis client. | Integer | |
| camel.component.aws2-kinesis.proxy-protocol | To define a proxy protocol when instantiating the Kinesis client. | Protocol | |
| camel.component.aws2-kinesis.region | The region in which Kinesis Firehose client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-kinesis.resume-strategy | Defines a resume strategy for AWS Kinesis. The default strategy reads the sequenceNumber if provided. The option is a org.apache.camel.component.aws2.kinesis.consumer.KinesisResumeStrategy type. | KinesisResumeStrategy | |
| camel.component.aws2-kinesis.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-kinesis.sequence-number | The sequence number to start polling from. Required if iteratorType is set to AFTER_SEQUENCE_NUMBER or AT_SEQUENCE_NUMBER. | String | |
| camel.component.aws2-kinesis.session-token | Amazon AWS Session Token used when the user needs to assume a IAM role. | String | |
| camel.component.aws2-kinesis.shard-closed | Define what will be the behavior in case of shard closed. Possible value are ignore, silent and fail. In case of ignore a message will be logged and the consumer will restart from the beginning,in case of silent there will be no logging and the consumer will start from the beginning,in case of fail a ReachedClosedStateException will be raised. | Kinesis2ShardClosedStrategyEnum | |
| camel.component.aws2-kinesis.shard-id | Defines which shardId in the Kinesis stream to get records from. | String | |
| camel.component.aws2-kinesis.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-kinesis.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-kinesis.use-default-credentials-provider | Set whether the Kinesis client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
| camel.component.aws2-kinesis.use-profile-credentials-provider | Set whether the Kinesis client should expect to load credentials through a profile credentials provider. | false | Boolean |
| camel.component.aws2-kinesis.use-session-credentials | Set whether the Kinesis client should expect to use Session Credentials. This is useful in situation in which the user needs to assume a IAM role for doing operations in Kinesis. | false | Boolean |
Chapter 8. AWS 2 Lambda 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The AWS2 Lambda component supports create, get, list, delete and invoke AWS Lambda functions.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Lambda. More information is available at AWS Lambda.
When creating a Lambda function, you need to specify a IAM role which has at least the AWSLambdaBasicExecuteRole policy attached.
8.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-lambda with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-lambda-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-lambda-starter</artifactId>
</dependency>
8.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-lambda://functionName[?options]
aws2-lambda://functionName[?options]
You can append query options to the URI in the following format, options=value&option2=value&…
8.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
8.3.1. 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.
8.3.2. 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.
8.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Lambda component supports 16 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| configuration (producer) | Component configuration. | Lambda2Configuration | |
| 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 |
| operation (producer) | The operation to perform. It can be listFunctions, getFunction, createFunction, deleteFunction or invokeFunction. Enum values:
| invokeFunction | Lambda2Operations |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| pojoRequest (producer) | If we want to use a POJO request as body or not. | false | boolean |
| region (producer) | The region in which Lambda client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the Lambda client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | 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 |
| awsLambdaClient (advanced) | Autowired To use a existing configured AwsLambdaClient as client. | LambdaClient | |
| proxyHost (proxy) | To define a proxy host when instantiating the Lambda client. | String | |
| proxyPort (proxy) | To define a proxy port when instantiating the Lambda client. | Integer | |
| proxyProtocol (proxy) | To define a proxy protocol when instantiating the Lambda client. Enum values:
| HTTPS | Protocol |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
8.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Lambda endpoint is configured using URI syntax:
aws2-lambda:function
aws2-lambda:function
with the following path and query parameters:
8.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| function (producer) | Required Name of the Lambda function. | String |
8.5.2. Query Parameters (14 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| 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 |
| operation (producer) | The operation to perform. It can be listFunctions, getFunction, createFunction, deleteFunction or invokeFunction. Enum values:
| invokeFunction | Lambda2Operations |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| pojoRequest (producer) | If we want to use a POJO request as body or not. | false | boolean |
| region (producer) | The region in which Lambda client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the Lambda client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| awsLambdaClient (advanced) | Autowired To use a existing configured AwsLambdaClient as client. | LambdaClient | |
| proxyHost (proxy) | To define a proxy host when instantiating the Lambda client. | String | |
| proxyPort (proxy) | To define a proxy port when instantiating the Lambda client. | Integer | |
| proxyProtocol (proxy) | To define a proxy protocol when instantiating the Lambda client. Enum values:
| HTTPS | Protocol |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
Required Lambda component options
You have to provide the awsLambdaClient in the Registry or your accessKey and secretKey to access the Amazon Lambda service..
8.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
8.6.1. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
- Java system properties - aws.accessKeyId and aws.secretKey
- Environment variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- Web Identity Token from AWS STS.
- The shared credentials and config files.
- Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
- Amazon EC2 Instance profile credentials.
For more information about this you can look at AWS credentials documentation
8.6.2. Message headers evaluated by the Lambda producer 링크 복사링크가 클립보드에 복사되었습니다!
| Operation | Header | Type | Description | Required |
|---|---|---|---|---|
| All |
|
| The operation we want to perform. Override operation passed as query parameter | Yes |
| createFunction |
|
| Amazon S3 bucket name where the .zip file containing your deployment package is stored. This bucket must reside in the same AWS region where you are creating the Lambda function. | No |
| createFunction |
|
| The Amazon S3 object (the deployment package) key name you want to upload. | No |
| createFunction |
| String | The Amazon S3 object (the deployment package) version you want to upload. | No |
| createFunction |
|
| The local path of the zip file (the deployment package). Content of zip file can also be put in Message body. | No |
| createFunction |
|
| The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes your function to access any other Amazon Web Services (AWS) resources. | Yes |
| createFunction |
| String | The runtime environment for the Lambda function you are uploading. (nodejs, nodejs4.3, nodejs6.10, java8, python2.7, python3.6, dotnetcore1.0, odejs4.3-edge) | Yes |
| createFunction |
|
| The function within your code that Lambda calls to begin execution. For Node.js, it is the module-name.export value in your function. For Java, it can be package.class-name::handler or package.class-name. | Yes |
| createFunction |
|
| The user-provided description. | No |
| createFunction |
|
| The parent object that contains the target ARN (Amazon Resource Name) of an Amazon SQS queue or Amazon SNS topic. | No |
| createFunction |
|
| The memory size, in MB, you configured for the function. Must be a multiple of 64 MB. | No |
| createFunction |
|
| The Amazon Resource Name (ARN) of the KMS key used to encrypt your function’s environment variables. If not provided, AWS Lambda will use a default service key. | No |
| createFunction |
|
| This boolean parameter can be used to request AWS Lambda to create the Lambda function and publish a version as an atomic operation. | No |
| createFunction |
|
| The function execution time at which Lambda should terminate the function. The default is 3 seconds. | No |
| createFunction |
|
| Your function’s tracing settings (Active or PassThrough). | No |
| createFunction |
|
| The key-value pairs that represent your environment’s configuration settings. | No |
| createFunction |
|
| The list of tags (key-value pairs) assigned to the new function. | No |
| createFunction |
|
| If your Lambda function accesses resources in a VPC, a list of one or more security groups IDs in your VPC. | No |
| createFunction |
|
| If your Lambda function accesses resources in a VPC, a list of one or more subnet IDs in your VPC. | No |
| createAlias |
|
| The function version to set in the alias | Yes |
| createAlias |
|
| The function name to set in the alias | Yes |
| createAlias |
|
| The function description to set in the alias | No |
| deleteAlias |
|
| The function name of the alias | Yes |
| getAlias |
|
| The function name of the alias | Yes |
| listAliases |
|
| The function version to set in the alias | No |
8.7. List of Avalaible Operations 링크 복사링크가 클립보드에 복사되었습니다!
- listFunctions
- getFunction
- createFunction
- deleteFunction
- invokeFunction
- updateFunction
- createEventSourceMapping
- deleteEventSourceMapping
- listEventSourceMapping
- listTags
- tagResource
- untagResource
- publishVersion
- listVersions
- createAlias
- deleteAlias
- getAlias
- listAliases
8.8. Examples 링크 복사링크가 클립보드에 복사되었습니다!
8.8.1. Producer Example 링크 복사링크가 클립보드에 복사되었습니다!
To have a full understanding of how the component works, you may have a look at these integration tests.
8.8.2. Producer Examples 링크 복사링크가 클립보드에 복사되었습니다!
- CreateFunction: this operation will create a function for you in AWS Lambda
from("direct:createFunction").to("aws2-lambda://GetHelloWithName?operation=createFunction").to("mock:result");
from("direct:createFunction").to("aws2-lambda://GetHelloWithName?operation=createFunction").to("mock:result");
and by sending
8.9. Using a POJO as body 링크 복사링크가 클립보드에 복사되었습니다!
Sometimes build an AWS Request can be complex, because of multiple options. We introduce the possibility to use a POJO as body. In AWS Lambda there are multiple operations you can submit, as an example for Get Function request, you can do something like:
from("direct:getFunction")
.setBody(GetFunctionRequest.builder().functionName("test").build())
.to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=getFunction&pojoRequest=true")
from("direct:getFunction")
.setBody(GetFunctionRequest.builder().functionName("test").build())
.to("aws2-lambda://GetHelloWithName?awsLambdaClient=#awsLambdaClient&operation=getFunction&pojoRequest=true")
In this way you’ll pass the request directly without the need of passing headers and options specifically related to this operation.
8.10. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
Maven users will need to add the following dependency to their pom.xml.
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-lambda</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-lambda</artifactId>
<version>${camel-version}</version>
</dependency>
where {camel-version} must be replaced by the actual version of Camel.
8.11. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 17 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-lambda.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-lambda.autowired-enabled | 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 |
| camel.component.aws2-lambda.aws-lambda-client | To use a existing configured AwsLambdaClient as client. The option is a software.amazon.awssdk.services.lambda.LambdaClient type. | LambdaClient | |
| camel.component.aws2-lambda.configuration | Component configuration. The option is a org.apache.camel.component.aws2.lambda.Lambda2Configuration type. | Lambda2Configuration | |
| camel.component.aws2-lambda.enabled | Whether to enable auto configuration of the aws2-lambda component. This is enabled by default. | Boolean | |
| camel.component.aws2-lambda.lazy-start-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 |
| camel.component.aws2-lambda.operation | The operation to perform. It can be listFunctions, getFunction, createFunction, deleteFunction or invokeFunction. | Lambda2Operations | |
| camel.component.aws2-lambda.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-lambda.pojo-request | If we want to use a POJO request as body or not. | false | Boolean |
| camel.component.aws2-lambda.proxy-host | To define a proxy host when instantiating the Lambda client. | String | |
| camel.component.aws2-lambda.proxy-port | To define a proxy port when instantiating the Lambda client. | Integer | |
| camel.component.aws2-lambda.proxy-protocol | To define a proxy protocol when instantiating the Lambda client. | Protocol | |
| camel.component.aws2-lambda.region | The region in which Lambda client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-lambda.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-lambda.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-lambda.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-lambda.use-default-credentials-provider | Set whether the Lambda client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
Chapter 9. AWS S3 Storage Service 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The AWS2 S3 component supports storing and retrieving objects from/to Amazon’s S3 service.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon S3. More information is available at link:https://aws.amazon.com/s3 [Amazon S3].
9.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-s3 with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-s3-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-s3-starter</artifactId>
</dependency>
9.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-s3://bucketNameOrArn[?options]
aws2-s3://bucketNameOrArn[?options]
The bucket will be created if it don’t already exists. You can append query options to the URI in the following format,
options=value&option2=value&…
9.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
9.3.1. 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.
9.3.2. 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.
9.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS S3 Storage Service component supports 50 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amazonS3Client (common) | Autowired Reference to a com.amazonaws.services.s3.AmazonS3 in the registry. | S3Client | |
| amazonS3Presigner (common) | Autowired An S3 Presigner for Request, used mainly in createDownloadLink operation. | S3Presigner | |
| autoCreateBucket (common) | Setting the autocreation of the S3 bucket bucketName. This will apply also in case of moveAfterRead option enabled and it will create the destinationBucket if it doesn’t exist already. | false | boolean |
| configuration (common) | The component configuration. | AWS2S3Configuration | |
| overrideEndpoint (common) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| pojoRequest (common) | If we want to use a POJO request as body or not. | false | boolean |
| policy (common) | The policy for this queue to set in the com.amazonaws.services.s3.AmazonS3#setBucketPolicy() method. | String | |
| proxyHost (common) | To define a proxy host when instantiating the SQS client. | String | |
| proxyPort (common) | Specify a proxy port to be used inside the client definition. | Integer | |
| proxyProtocol (common) | To define a proxy protocol when instantiating the S3 client. Enum values:
| HTTPS | Protocol |
| region (common) | The region in which S3 client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (common) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (common) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (common) | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| customerAlgorithm (common (advanced)) | Define the customer algorithm to use in case CustomerKey is enabled. | String | |
| customerKeyId (common (advanced)) | Define the id of Customer key to use in case CustomerKey is enabled. | String | |
| customerKeyMD5 (common (advanced)) | Define the MD5 of Customer key to use in case CustomerKey is enabled. | String | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| deleteAfterRead (consumer) | Delete objects from S3 after they have been retrieved. The delete is only performed if the Exchange is committed. If a rollback occurs, the object is not deleted. If this option is false, then the same objects will be retrieve over and over again on the polls. Therefore you need to use the Idempotent Consumer EIP in the route to filter out duplicates. You can filter using the AWS2S3Constants#BUCKET_NAME and AWS2S3Constants#KEY headers, or only the AWS2S3Constants#KEY header. | true | boolean |
| delimiter (consumer) | The delimiter which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in. | String | |
| destinationBucket (consumer) | Define the destination bucket where an object must be moved when moveAfterRead is set to true. | String | |
| destinationBucketPrefix (consumer) | Define the destination bucket prefix to use when an object must be moved and moveAfterRead is set to true. | String | |
| destinationBucketSuffix (consumer) | Define the destination bucket suffix to use when an object must be moved and moveAfterRead is set to true. | String | |
| doneFileName (consumer) | If provided, Camel will only consume files if a done file exists. | String | |
| fileName (consumer) | To get the object from the bucket with the given file name. | String | |
| ignoreBody (consumer) | If it is true, the S3 Object Body will be ignored completely, if it is set to false the S3 Object will be put in the body. Setting this to true, will override any behavior defined by includeBody option. | false | boolean |
| includeBody (consumer) | If it is true, the S3Object exchange will be consumed and put into the body and closed. If false the S3Object stream will be put raw into the body and the headers will be set with the S3 object metadata. This option is strongly related to autocloseBody option. In case of setting includeBody to true because the S3Object stream will be consumed then it will also be closed, while in case of includeBody false then it will be up to the caller to close the S3Object stream. However setting autocloseBody to true when includeBody is false it will schedule to close the S3Object stream automatically on exchange completion. | true | boolean |
| includeFolders (consumer) | If it is true, the folders/directories will be consumed. If it is false, they will be ignored, and Exchanges will not be created for those. | true | boolean |
| moveAfterRead (consumer) | Move objects from S3 bucket to a different bucket after they have been retrieved. To accomplish the operation the destinationBucket option must be set. The copy bucket operation is only performed if the Exchange is committed. If a rollback occurs, the object is not moved. | false | boolean |
| prefix (consumer) | The prefix which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in. | String | |
| autocloseBody (consumer (advanced)) | If this option is true and includeBody is false, then the S3Object.close() method will be called on exchange completion. This option is strongly related to includeBody option. In case of setting includeBody to false and autocloseBody to false, it will be up to the caller to close the S3Object stream. Setting autocloseBody to true, will close the S3Object stream automatically. | true | boolean |
| batchMessageNumber (producer) | The number of messages composing a batch in streaming upload mode. | 10 | int |
| batchSize (producer) | The batch size (in bytes) in streaming upload mode. | 1000000 | int |
| deleteAfterWrite (producer) | Delete file object after the S3 file has been uploaded. | false | boolean |
| keyName (producer) | Setting the key name for an element in the bucket through endpoint parameter. | String | |
| 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 |
| multiPartUpload (producer) | If it is true, camel will upload the file with multi part format, the part size is decided by the option of partSize. | false | boolean |
| namingStrategy (producer) | The naming strategy to use in streaming upload mode. Enum values:
| progressive | AWSS3NamingStrategyEnum |
| operation (producer) | The operation to do in case the user don’t want to do only an upload. Enum values:
| AWS2S3Operations | |
| partSize (producer) | Setup the partSize which is used in multi part upload, the default size is 25M. | 26214400 | long |
| restartingPolicy (producer) | The restarting policy to use in streaming upload mode. Enum values:
| override | AWSS3RestartingPolicyEnum |
| storageClass (producer) | The storage class to set in the com.amazonaws.services.s3.model.PutObjectRequest request. | String | |
| streamingUploadMode (producer) | When stream mode is true the upload to bucket will be done in streaming. | false | boolean |
| streamingUploadTimeout (producer) | While streaming upload mode is true, this option set the timeout to complete upload. | long | |
| awsKMSKeyId (producer (advanced)) | Define the id of KMS key to use in case KMS is enabled. | String | |
| useAwsKMS (producer (advanced)) | Define if KMS must be used or not. | false | boolean |
| useCustomerKey (producer (advanced)) | Define if Customer Key must be used or not. | 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 |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
9.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS S3 Storage Service endpoint is configured using URI syntax:
aws2-s3://bucketNameOrArn
aws2-s3://bucketNameOrArn
with the following path and query parameters:
9.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| bucketNameOrArn (common) | Required Bucket name or ARN. | String |
9.5.2. Query Parameters (68 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amazonS3Client (common) | Autowired Reference to a com.amazonaws.services.s3.AmazonS3 in the registry. | S3Client | |
| amazonS3Presigner (common) | Autowired An S3 Presigner for Request, used mainly in createDownloadLink operation. | S3Presigner | |
| autoCreateBucket (common) | Setting the autocreation of the S3 bucket bucketName. This will apply also in case of moveAfterRead option enabled and it will create the destinationBucket if it doesn’t exist already. | false | boolean |
| overrideEndpoint (common) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| pojoRequest (common) | If we want to use a POJO request as body or not. | false | boolean |
| policy (common) | The policy for this queue to set in the com.amazonaws.services.s3.AmazonS3#setBucketPolicy() method. | String | |
| proxyHost (common) | To define a proxy host when instantiating the SQS client. | String | |
| proxyPort (common) | Specify a proxy port to be used inside the client definition. | Integer | |
| proxyProtocol (common) | To define a proxy protocol when instantiating the S3 client. Enum values:
| HTTPS | Protocol |
| region (common) | The region in which S3 client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (common) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (common) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (common) | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| customerAlgorithm (common (advanced)) | Define the customer algorithm to use in case CustomerKey is enabled. | String | |
| customerKeyId (common (advanced)) | Define the id of Customer key to use in case CustomerKey is enabled. | String | |
| customerKeyMD5 (common (advanced)) | Define the MD5 of Customer key to use in case CustomerKey is enabled. | String | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| deleteAfterRead (consumer) | Delete objects from S3 after they have been retrieved. The delete is only performed if the Exchange is committed. If a rollback occurs, the object is not deleted. If this option is false, then the same objects will be retrieve over and over again on the polls. Therefore you need to use the Idempotent Consumer EIP in the route to filter out duplicates. You can filter using the AWS2S3Constants#BUCKET_NAME and AWS2S3Constants#KEY headers, or only the AWS2S3Constants#KEY header. | true | boolean |
| delimiter (consumer) | The delimiter which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in. | String | |
| destinationBucket (consumer) | Define the destination bucket where an object must be moved when moveAfterRead is set to true. | String | |
| destinationBucketPrefix (consumer) | Define the destination bucket prefix to use when an object must be moved and moveAfterRead is set to true. | String | |
| destinationBucketSuffix (consumer) | Define the destination bucket suffix to use when an object must be moved and moveAfterRead is set to true. | String | |
| doneFileName (consumer) | If provided, Camel will only consume files if a done file exists. | String | |
| fileName (consumer) | To get the object from the bucket with the given file name. | String | |
| ignoreBody (consumer) | If it is true, the S3 Object Body will be ignored completely, if it is set to false the S3 Object will be put in the body. Setting this to true, will override any behavior defined by includeBody option. | false | boolean |
| includeBody (consumer) | If it is true, the S3Object exchange will be consumed and put into the body and closed. If false the S3Object stream will be put raw into the body and the headers will be set with the S3 object metadata. This option is strongly related to autocloseBody option. In case of setting includeBody to true because the S3Object stream will be consumed then it will also be closed, while in case of includeBody false then it will be up to the caller to close the S3Object stream. However setting autocloseBody to true when includeBody is false it will schedule to close the S3Object stream automatically on exchange completion. | true | boolean |
| includeFolders (consumer) | If it is true, the folders/directories will be consumed. If it is false, they will be ignored, and Exchanges will not be created for those. | true | boolean |
| maxConnections (consumer) | Set the maxConnections parameter in the S3 client configuration. | 60 | int |
| maxMessagesPerPoll (consumer) | Gets the maximum number of messages as a limit to poll at each polling. Gets the maximum number of messages as a limit to poll at each polling. The default value is 10. Use 0 or a negative number to set it as unlimited. | 10 | int |
| moveAfterRead (consumer) | Move objects from S3 bucket to a different bucket after they have been retrieved. To accomplish the operation the destinationBucket option must be set. The copy bucket operation is only performed if the Exchange is committed. If a rollback occurs, the object is not moved. | false | boolean |
| prefix (consumer) | The prefix which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in. | String | |
| sendEmptyMessageWhenIdle (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean |
| autocloseBody (consumer (advanced)) | If this option is true and includeBody is false, then the S3Object.close() method will be called on exchange completion. This option is strongly related to includeBody option. In case of setting includeBody to false and autocloseBody to false, it will be up to the caller to close the S3Object stream. Setting autocloseBody to true, will close the S3Object stream automatically. | true | 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:
| ExchangePattern | |
| pollStrategy (consumer (advanced)) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | |
| batchMessageNumber (producer) | The number of messages composing a batch in streaming upload mode. | 10 | int |
| batchSize (producer) | The batch size (in bytes) in streaming upload mode. | 1000000 | int |
| deleteAfterWrite (producer) | Delete file object after the S3 file has been uploaded. | false | boolean |
| keyName (producer) | Setting the key name for an element in the bucket through endpoint parameter. | String | |
| 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 |
| multiPartUpload (producer) | If it is true, camel will upload the file with multi part format, the part size is decided by the option of partSize. | false | boolean |
| namingStrategy (producer) | The naming strategy to use in streaming upload mode. Enum values:
| progressive | AWSS3NamingStrategyEnum |
| operation (producer) | The operation to do in case the user don’t want to do only an upload. Enum values:
| AWS2S3Operations | |
| partSize (producer) | Setup the partSize which is used in multi part upload, the default size is 25M. | 26214400 | long |
| restartingPolicy (producer) | The restarting policy to use in streaming upload mode. Enum values:
| override | AWSS3RestartingPolicyEnum |
| storageClass (producer) | The storage class to set in the com.amazonaws.services.s3.model.PutObjectRequest request. | String | |
| streamingUploadMode (producer) | When stream mode is true the upload to bucket will be done in streaming. | false | boolean |
| streamingUploadTimeout (producer) | While streaming upload mode is true, this option set the timeout to complete upload. | long | |
| awsKMSKeyId (producer (advanced)) | Define the id of KMS key to use in case KMS is enabled. | String | |
| useAwsKMS (producer (advanced)) | Define if KMS must be used or not. | false | boolean |
| useCustomerKey (producer (advanced)) | Define if Customer Key must be used or not. | false | boolean |
| backoffErrorThreshold (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | |
| backoffIdleThreshold (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | |
| backoffMultiplier (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | |
| delay (scheduler) | Milliseconds before the next poll. | 500 | long |
| greedy (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean |
| initialDelay (scheduler) | Milliseconds before the first poll starts. | 1000 | long |
| repeatCount (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long |
| runLoggingLevel (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel |
| scheduledExecutorService (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | |
| scheduler (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object |
| schedulerProperties (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | Map | |
| startScheduler (scheduler) | Whether the scheduler should be auto started. | true | boolean |
| timeUnit (scheduler) | Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit |
| useFixedDelay (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
Required S3 component options
You have to provide the amazonS3Client in the Registry or your accessKey and secretKey to access the Amazon’s S3.
9.6. Batch Consumer 링크 복사링크가 클립보드에 복사되었습니다!
This component implements the Batch Consumer.
This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.
9.7. Usage 링크 복사링크가 클립보드에 복사되었습니다!
For example in order to read file hello.txt from bucket helloBucket, use the following snippet:
from("aws2-s3://helloBucket?accessKey=yourAccessKey&secretKey=yourSecretKey&prefix=hello.txt")
.to("file:/var/downloaded");
from("aws2-s3://helloBucket?accessKey=yourAccessKey&secretKey=yourSecretKey&prefix=hello.txt")
.to("file:/var/downloaded");
9.7.1. Message headers evaluated by the S3 producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The bucket Name which this object will be stored or which will be used for the current operation |
|
|
| The bucket Destination Name which will be used for the current operation |
|
|
| The content length of this object. |
|
|
| The content type of this object. |
|
|
| The content control of this object. |
|
|
| The content disposition of this object. |
|
|
| The content encoding of this object. |
|
|
| The md5 checksum of this object. |
|
|
| The Destination key which will be used for the current operation |
|
|
| The key under which this object will be stored or which will be used for the current operation |
|
|
| The last modified timestamp of this object. |
|
|
| The operation to perform. Permitted values are copyObject, deleteObject, listBuckets, deleteBucket, listObjects |
|
|
| The storage class of this object. |
|
|
|
The canned acl that will be applied to the object. see |
|
|
|
A well constructed Amazon S3 Access Control List object. see |
|
| String | Sets the server-side encryption algorithm when encrypting the object using AWS-managed keys. For example use AES256. |
|
|
| The version Id of the object to be stored or returned from the current operation |
|
|
| A map of metadata to be stored with the object in S3. More details about metadata . |
9.7.2. Message headers set by the S3 producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The ETag value for the newly uploaded object. |
|
|
| The optional version ID of the newly uploaded object. |
9.7.3. Message headers set by the S3 consumer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The key under which this object is stored. |
|
|
| The name of the bucket in which this object is contained. |
|
|
| The hex encoded 128-bit MD5 digest of the associated object according to RFC 1864. This data is used as an integrity check to verify that the data received by the caller is the same data that was sent by Amazon S3. |
|
|
| The value of the Last-Modified header, indicating the date and time at which Amazon S3 last recorded a modification to the associated object. |
|
|
| The version ID of the associated Amazon S3 object if available. Version IDs are only assigned to objects when an object is uploaded to an Amazon S3 bucket that has object versioning enabled. |
|
|
| The Content-Type HTTP header, which indicates the type of content stored in the associated object. The value of this header is a standard MIME type. |
|
|
| The base64 encoded 128-bit MD5 digest of the associated object (content - not including headers) according to RFC 1864. This data is used as a message integrity check to verify that the data received by Amazon S3 is the same data that the caller sent. |
|
|
| The Content-Length HTTP header indicating the size of the associated object in bytes. |
|
|
| The optional Content-Encoding HTTP header specifying what content encodings have been applied to the object and what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type field. |
|
|
| The optional Content-Disposition HTTP header, which specifies presentational information such as the recommended filename for the object to be saved as. |
|
|
| The optional Cache-Control HTTP header which allows the user to specify caching behavior along the HTTP request/reply chain. |
|
| String | The server-side encryption algorithm when encrypting the object using AWS-managed keys. |
|
|
| A map of metadata stored with the object in S3. More details about metadata . |
9.7.4. S3 Producer operations 링크 복사링크가 클립보드에 복사되었습니다!
Camel-AWS2-S3 component provides the following operation on the producer side:
- copyObject
- deleteObject
- listBuckets
- deleteBucket
- listObjects
- getObject (this will return an S3Object instance)
- getObjectRange (this will return an S3Object instance)
- createDownloadLink
If you don’t specify an operation explicitly the producer will do: - a single file upload - a multipart upload if multiPartUpload option is enabled.
9.7.5. Advanced AmazonS3 configuration 링크 복사링크가 클립보드에 복사되었습니다!
If your Camel Application is running behind a firewall or if you need to have more control over the S3Client instance configuration, you can create your own instance and refer to it in your Camel aws2-s3 component configuration:
from("aws2-s3://MyBucket?amazonS3Client=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
from("aws2-s3://MyBucket?amazonS3Client=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
9.7.6. Use KMS with the S3 component 링크 복사링크가 클립보드에 복사되었습니다!
To use AWS KMS to encrypt/decrypt data by using AWS infrastructure you can use the options introduced in 2.21.x like in the following example
from("file:tmp/test?fileName=test.txt")
.setHeader(S3Constants.KEY, constant("testFile"))
.to("aws2-s3://mybucket?amazonS3Client=#client&useAwsKMS=true&awsKMSKeyId=3f0637ad-296a-3dfe-a796-e60654fb128c");
from("file:tmp/test?fileName=test.txt")
.setHeader(S3Constants.KEY, constant("testFile"))
.to("aws2-s3://mybucket?amazonS3Client=#client&useAwsKMS=true&awsKMSKeyId=3f0637ad-296a-3dfe-a796-e60654fb128c");
In this way you’ll ask to S3, to use the KMS key 3f0637ad-296a-3dfe-a796-e60654fb128c, to encrypt the file test.txt. When you’ll ask to download this file, the decryption will be done directly before the download.
9.7.7. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
- Java system properties - aws.accessKeyId and aws.secretKey
- Environment variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- Web Identity Token from AWS STS.
- The shared credentials and config files.
- Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
- Amazon EC2 Instance profile credentials.
For more information about this you can look at AWS credentials documentation
9.7.8. S3 Producer Operation examples 링크 복사링크가 클립보드에 복사되었습니다!
- Single Upload: This operation will upload a file to S3 based on the body content
This operation will upload the file camel.txt with the content "Camel rocks!" in the mycamelbucket bucket
- Multipart Upload: This operation will perform a multipart upload of a file to S3 based on the body content
This operation will perform a multipart upload of the file empty.txt with based on the content the file src/empty.txt in the mycamelbucket bucket
- CopyObject: this operation copy an object from one bucket to a different one
This operation will copy the object with the name expressed in the header camelDestinationKey to the camelDestinationBucket bucket, from the bucket mycamelbucket.
- DeleteObject: this operation deletes an object from a bucket
This operation will delete the object camelKey from the bucket mycamelbucket.
- ListBuckets: this operation list the buckets for this account in this region
from("direct:start")
.to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=listBuckets")
.to("mock:result");
from("direct:start")
.to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=listBuckets")
.to("mock:result");
This operation will list the buckets for this account
- DeleteBucket: this operation delete the bucket specified as URI parameter or header
from("direct:start")
.to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=deleteBucket")
.to("mock:result");
from("direct:start")
.to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=deleteBucket")
.to("mock:result");
This operation will delete the bucket mycamelbucket
- ListObjects: this operation list object in a specific bucket
from("direct:start")
.to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=listObjects")
.to("mock:result");
from("direct:start")
.to("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&operation=listObjects")
.to("mock:result");
This operation will list the objects in the mycamelbucket bucket
- GetObject: this operation get a single object in a specific bucket
This operation will return an S3Object instance related to the camelKey object in mycamelbucket bucket.
- GetObjectRange: this operation get a single object range in a specific bucket
This operation will return an S3Object instance related to the camelKey object in mycamelbucket bucket, containing a the bytes from 0 to 9.
- CreateDownloadLink: this operation will return a download link through S3 Presigner
This operation will return a download link url for the file camel-key in the bucket mycamelbucket and region region
9.8. Streaming Upload mode 링크 복사링크가 클립보드에 복사되었습니다!
With the stream mode enabled users will be able to upload data to S3 without knowing ahead of time the dimension of the data, by leveraging multipart upload. The upload will be completed when: the batchSize has been completed or the batchMessageNumber has been reached. There are two possible naming strategy:
progressive
With the progressive strategy each file will have the name composed by keyName option and a progressive counter, and eventually the file extension (if any)
random.
With the random strategy a UUID will be added after keyName and eventually the file extension will appended.
As an example:
The default size for a batch is 1 Mb, but you can adjust it according to your requirements.
When you’ll stop your producer route, the producer will take care of flushing the remaining buffered messaged and complete the upload.
In Streaming upload you’ll be able restart the producer from the point where it left. It’s important to note that this feature is critical only when using the progressive naming strategy.
By setting the restartingPolicy to lastPart, you will restart uploading files and contents from the last part number the producer left.
Example
- Start the route with progressive naming strategy and keyname equals to camel.txt, with batchMessageNumber equals to 20, and restartingPolicy equals to lastPart - Send 70 messages.
- Stop the route
On your S3 bucket you should now see 4 files: * camel.txt
- camel-1.txt
- camel-2.txt
camel-3.txt
The first three will have 20 messages, while the last one only 10.
- Restart the route.
- Send 25 messages.
- Stop the route.
- You’ll now have 2 other files in your bucket: camel-5.txt and camel-6.txt, the first with 20 messages and second with 5 messages.
- Go ahead
This won’t be needed when using the random naming strategy.
On the opposite you can specify the override restartingPolicy. In that case you’ll be able to override whatever you written before (for that particular keyName) on your bucket.
In Streaming upload mode the only keyName option that will be taken into account is the endpoint option. Using the header will throw an NPE and this is done by design. Setting the header means potentially change the file name on each exchange and this is against the aim of the streaming upload producer. The keyName needs to be fixed and static. The selected naming strategy will do the rest of the of the work.
Another possibility is specifying a streamingUploadTimeout with batchMessageNumber and batchSize options. With this option the user will be able to complete the upload of a file after a certain time passed. In this way the upload completion will be passed on three tiers: the timeout, the number of messages and the batch size.
As an example:
from(kafka("topic1").brokers("localhost:9092"))
.log("Kafka Message is: ${body}")
.to(aws2S3("camel-bucket").streamingUploadMode(true).batchMessageNumber(25).streamingUploadTimeout(10000).namingStrategy(AWS2S3EndpointBuilderFactory.AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic1}}/{{kafkaTopic1}}.txt"));
from(kafka("topic1").brokers("localhost:9092"))
.log("Kafka Message is: ${body}")
.to(aws2S3("camel-bucket").streamingUploadMode(true).batchMessageNumber(25).streamingUploadTimeout(10000).namingStrategy(AWS2S3EndpointBuilderFactory.AWSS3NamingStrategyEnum.progressive).keyName("{{kafkaTopic1}}/{{kafkaTopic1}}.txt"));
In this case the upload will be completed after 10 seconds.
9.9. Bucket Autocreation 링크 복사링크가 클립보드에 복사되었습니다!
With the option autoCreateBucket users are able to avoid the autocreation of an S3 Bucket in case it doesn’t exist. The default for this option is true. If set to false any operation on a not-existent bucket in AWS won’t be successful and an error will be returned.
9.10. Moving stuff between a bucket and another bucket 링크 복사링크가 클립보드에 복사되었습니다!
Some users like to consume stuff from a bucket and move the content in a different one without using the copyObject feature of this component. If this is case for you, don’t forget to remove the bucketName header from the incoming exchange of the consumer, otherwise the file will be always overwritten on the same original bucket.
9.11. MoveAfterRead consumer option 링크 복사링크가 클립보드에 복사되었습니다!
In addition to deleteAfterRead it has been added another option, moveAfterRead. With this option enabled the consumed object will be moved to a target destinationBucket instead of being only deleted. This will require specifying the destinationBucket option. As example:
from("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&moveAfterRead=true&destinationBucket=myothercamelbucket")
.to("mock:result");
from("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&moveAfterRead=true&destinationBucket=myothercamelbucket")
.to("mock:result");
In this case the objects consumed will be moved to myothercamelbucket bucket and deleted from the original one (because of deleteAfterRead set to true as default).
You have also the possibility of using a key prefix/suffix while moving the file to a different bucket. The options are destinationBucketPrefix and destinationBucketSuffix.
Taking the above example, you could do something like:
from("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&moveAfterRead=true&destinationBucket=myothercamelbucket&destinationBucketPrefix=RAW(pre-)&destinationBucketSuffix=RAW(-suff)")
.to("mock:result");
from("aws2-s3://mycamelbucket?amazonS3Client=#amazonS3Client&moveAfterRead=true&destinationBucket=myothercamelbucket&destinationBucketPrefix=RAW(pre-)&destinationBucketSuffix=RAW(-suff)")
.to("mock:result");
In this case the objects consumed will be moved to myothercamelbucket bucket and deleted from the original one (because of deleteAfterRead set to true as default).
So if the file name is test, in the myothercamelbucket you should see a file called pre-test-suff.
9.12. Using customer key as encryption 링크 복사링크가 클립보드에 복사되었습니다!
We introduced also the customer key support (an alternative of using KMS). The following code shows an example.
9.13. Using a POJO as body 링크 복사링크가 클립보드에 복사되었습니다!
Sometimes build an AWS Request can be complex, because of multiple options. We introduce the possibility to use a POJO as body. In AWS S3 there are multiple operations you can submit, as an example for List brokers request, you can do something like:
from("direct:aws2-s3")
.setBody(ListObjectsRequest.builder().bucket(bucketName).build())
.to("aws2-s3://test?amazonS3Client=#amazonS3Client&operation=listObjects&pojoRequest=true")
from("direct:aws2-s3")
.setBody(ListObjectsRequest.builder().bucket(bucketName).build())
.to("aws2-s3://test?amazonS3Client=#amazonS3Client&operation=listObjects&pojoRequest=true")
In this way you’ll pass the request directly without the need of passing headers and options specifically related to this operation.
9.14. Create S3 client and add component to registry 링크 복사링크가 클립보드에 복사되었습니다!
Sometimes you would want to perform some advanced configuration using AWS2S3Configuration which also allows to set the S3 client. You can create and set the S3 client in the component configuration as shown in the following example
Now you can configure the S3 component (using the configuration object created above) and add it to the registry in the configure method before initialization of routes.
AWS2S3Component s3Component = new AWS2S3Component(getContext());
s3Component.setConfiguration(configuration);
s3Component.setLazyStartProducer(true);
camelContext.addComponent("aws2-s3", s3Component);
AWS2S3Component s3Component = new AWS2S3Component(getContext());
s3Component.setConfiguration(configuration);
s3Component.setLazyStartProducer(true);
camelContext.addComponent("aws2-s3", s3Component);
Now your component will be used for all the operations implemented in camel routes.
9.15. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
Maven users will need to add the following dependency to their pom.xml.
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-s3</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-s3</artifactId>
<version>${camel-version}</version>
</dependency>
where {camel-version} must be replaced by the actual version of Camel.
9.16. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 51 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-s3.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-s3.amazon-s3-client | Reference to a com.amazonaws.services.s3.AmazonS3 in the registry. The option is a software.amazon.awssdk.services.s3.S3Client type. | S3Client | |
| camel.component.aws2-s3.amazon-s3-presigner | An S3 Presigner for Request, used mainly in createDownloadLink operation. The option is a software.amazon.awssdk.services.s3.presigner.S3Presigner type. | S3Presigner | |
| camel.component.aws2-s3.auto-create-bucket | Setting the autocreation of the S3 bucket bucketName. This will apply also in case of moveAfterRead option enabled and it will create the destinationBucket if it doesn’t exist already. | false | Boolean |
| camel.component.aws2-s3.autoclose-body | If this option is true and includeBody is false, then the S3Object.close() method will be called on exchange completion. This option is strongly related to includeBody option. In case of setting includeBody to false and autocloseBody to false, it will be up to the caller to close the S3Object stream. Setting autocloseBody to true, will close the S3Object stream automatically. | true | Boolean |
| camel.component.aws2-s3.autowired-enabled | 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 |
| camel.component.aws2-s3.aws-k-m-s-key-id | Define the id of KMS key to use in case KMS is enabled. | String | |
| camel.component.aws2-s3.batch-message-number | The number of messages composing a batch in streaming upload mode. | 10 | Integer |
| camel.component.aws2-s3.batch-size | The batch size (in bytes) in streaming upload mode. | 1000000 | Integer |
| camel.component.aws2-s3.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.aws2-s3.configuration | The component configuration. The option is a org.apache.camel.component.aws2.s3.AWS2S3Configuration type. | AWS2S3Configuration | |
| camel.component.aws2-s3.customer-algorithm | Define the customer algorithm to use in case CustomerKey is enabled. | String | |
| camel.component.aws2-s3.customer-key-id | Define the id of Customer key to use in case CustomerKey is enabled. | String | |
| camel.component.aws2-s3.customer-key-m-d5 | Define the MD5 of Customer key to use in case CustomerKey is enabled. | String | |
| camel.component.aws2-s3.delete-after-read | Delete objects from S3 after they have been retrieved. The delete is only performed if the Exchange is committed. If a rollback occurs, the object is not deleted. If this option is false, then the same objects will be retrieve over and over again on the polls. Therefore you need to use the Idempotent Consumer EIP in the route to filter out duplicates. You can filter using the AWS2S3Constants#BUClKET_NAME and AWS2S3Constants#KEY headers, or only the AWS2S3Constants#KEY header. | true | Boolean |
| camel.component.aws2-s3.delete-after-write | Delete file object after the S3 file has been uploaded. | false | Boolean |
| camel.component.aws2-s3.delimiter | The delimiter which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in. | String | |
| camel.component.aws2-s3.destination-bucket | Define the destination bucket where an object must be moved when moveAfterRead is set to true. | String | |
| camel.component.aws2-s3.destination-bucket-prefix | Define the destination bucket prefix to use when an object must be moved and moveAfterRead is set to true. | String | |
| camel.component.aws2-s3.destination-bucket-suffix | Define the destination bucket suffix to use when an object must be moved and moveAfterRead is set to true. | String | |
| camel.component.aws2-s3.done-file-name | If provided, Camel will only consume files if a done file exists. | String | |
| camel.component.aws2-s3.enabled | Whether to enable auto configuration of the aws2-s3 component. This is enabled by default. | Boolean | |
| camel.component.aws2-s3.file-name | To get the object from the bucket with the given file name. | String | |
| camel.component.aws2-s3.ignore-body | If it is true, the S3 Object Body will be ignored completely, if it is set to false the S3 Object will be put in the body. Setting this to true, will override any behavior defined by includeBody option. | false | Boolean |
| camel.component.aws2-s3.include-body | If it is true, the S3Object exchange will be consumed and put into the body and closed. If false the S3Object stream will be put raw into the body and the headers will be set with the S3 object metadata. This option is strongly related to autocloseBody option. In case of setting includeBody to true because the S3Object stream will be consumed then it will also be closed, while in case of includeBody false then it will be up to the caller to close the S3Object stream. However setting autocloseBody to true when includeBody is false it will schedule to close the S3Object stream automatically on exchange completion. | true | Boolean |
| camel.component.aws2-s3.include-folders | If it is true, the folders/directories will be consumed. If it is false, they will be ignored, and Exchanges will not be created for those. | true | Boolean |
| camel.component.aws2-s3.key-name | Setting the key name for an element in the bucket through endpoint parameter. | String | |
| camel.component.aws2-s3.lazy-start-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 |
| camel.component.aws2-s3.move-after-read | Move objects from S3 bucket to a different bucket after they have been retrieved. To accomplish the operation the destinationBucket option must be set. The copy bucket operation is only performed if the Exchange is committed. If a rollback occurs, the object is not moved. | false | Boolean |
| camel.component.aws2-s3.multi-part-upload | If it is true, camel will upload the file with multi part format, the part size is decided by the option of partSize. | false | Boolean |
| camel.component.aws2-s3.naming-strategy | The naming strategy to use in streaming upload mode. | AWSS3NamingStrategyEnum | |
| camel.component.aws2-s3.operation | The operation to do in case the user don’t want to do only an upload. | AWS2S3Operations | |
| camel.component.aws2-s3.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-s3.part-size | Setup the partSize which is used in multi part upload, the default size is 25M. | 26214400 | Long |
| camel.component.aws2-s3.pojo-request | If we want to use a POJO request as body or not. | false | Boolean |
| camel.component.aws2-s3.policy | The policy for this queue to set in the com.amazonaws.services.s3.AmazonS3#setBucketPolicy() method. | String | |
| camel.component.aws2-s3.prefix | The prefix which is used in the com.amazonaws.services.s3.model.ListObjectsRequest to only consume objects we are interested in. | String | |
| camel.component.aws2-s3.proxy-host | To define a proxy host when instantiating the SQS client. | String | |
| camel.component.aws2-s3.proxy-port | Specify a proxy port to be used inside the client definition. | Integer | |
| camel.component.aws2-s3.proxy-protocol | To define a proxy protocol when instantiating the S3 client. | Protocol | |
| camel.component.aws2-s3.region | The region in which S3 client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-s3.restarting-policy | The restarting policy to use in streaming upload mode. | AWSS3RestartingPolicyEnum | |
| camel.component.aws2-s3.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-s3.storage-class | The storage class to set in the com.amazonaws.services.s3.model.PutObjectRequest request. | String | |
| camel.component.aws2-s3.streaming-upload-mode | When stream mode is true the upload to bucket will be done in streaming. | false | Boolean |
| camel.component.aws2-s3.streaming-upload-timeout | While streaming upload mode is true, this option set the timeout to complete upload. | Long | |
| camel.component.aws2-s3.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-s3.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-s3.use-aws-k-m-s | Define if KMS must be used or not. | false | Boolean |
| camel.component.aws2-s3.use-customer-key | Define if Customer Key must be used or not. | false | Boolean |
| camel.component.aws2-s3.use-default-credentials-provider | Set whether the S3 client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
Chapter 10. AWS Simple Notification System (SNS) 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The AWS2 SNS component allows messages to be sent to an Amazon Simple Notification Topic. The implementation of the Amazon API is provided by the AWS SDK.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SNS. More information is available at Amazon SNS.
10.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-sns with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-sns-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-sns-starter</artifactId>
</dependency>
10.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-sns://topicNameOrArn[?options]
aws2-sns://topicNameOrArn[?options]
The topic will be created if they don’t already exists. You can append query options to the URI in the following format,
?options=value&option2=value&…
?options=value&option2=value&…
10.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
10.3.1. 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.
10.3.2. 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.
10.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Simple Notification System (SNS) component supports 24 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amazonSNSClient (producer) | Autowired To use the AmazonSNS as the client. | SnsClient | |
| autoCreateTopic (producer) | Setting the autocreation of the topic. | false | boolean |
| configuration (producer) | Component configuration. | Sns2Configuration | |
| kmsMasterKeyId (producer) | The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. | String | |
| 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 |
| messageDeduplicationIdStrategy (producer) | Only for FIFO Topic. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message. Enum values:
| useExchangeId | String |
| messageGroupIdStrategy (producer) | Only for FIFO Topic. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used. Enum values:
| String | |
| messageStructure (producer) | The message structure to use such as json. | String | |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| policy (producer) | The policy for this topic. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | |
| proxyHost (producer) | To define a proxy host when instantiating the SNS client. | String | |
| proxyPort (producer) | To define a proxy port when instantiating the SNS client. | Integer | |
| proxyProtocol (producer) | To define a proxy protocol when instantiating the SNS client. Enum values:
| HTTPS | Protocol |
| queueUrl (producer) | The queueUrl to subscribe to. | String | |
| region (producer) | The region in which SNS client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| serverSideEncryptionEnabled (producer) | Define if Server Side Encryption is enabled or not on the topic. | false | boolean |
| subject (producer) | The subject which is used if the message header 'CamelAwsSnsSubject' is not present. | String | |
| subscribeSNStoSQS (producer) | Define if the subscription between SNS Topic and SQS must be done or not. | false | boolean |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the SNS client should expect to load credentials on an AWS infra instance or to expect static credentials to be passed in. | 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 |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
10.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Simple Notification System (SNS) endpoint is configured using URI syntax:
aws2-sns:topicNameOrArn
aws2-sns:topicNameOrArn
with the following path and query parameters:
10.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| topicNameOrArn (producer) | Required Topic name or ARN. | String |
10.5.2. Query Parameters (23 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amazonSNSClient (producer) | Autowired To use the AmazonSNS as the client. | SnsClient | |
| autoCreateTopic (producer) | Setting the autocreation of the topic. | false | boolean |
| headerFilterStrategy (producer) | To use a custom HeaderFilterStrategy to map headers to/from Camel. | HeaderFilterStrategy | |
| kmsMasterKeyId (producer) | The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. | String | |
| 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 |
| messageDeduplicationIdStrategy (producer) | Only for FIFO Topic. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message. Enum values:
| useExchangeId | String |
| messageGroupIdStrategy (producer) | Only for FIFO Topic. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used. Enum values:
| String | |
| messageStructure (producer) | The message structure to use such as json. | String | |
| overrideEndpoint (producer) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| policy (producer) | The policy for this topic. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | |
| proxyHost (producer) | To define a proxy host when instantiating the SNS client. | String | |
| proxyPort (producer) | To define a proxy port when instantiating the SNS client. | Integer | |
| proxyProtocol (producer) | To define a proxy protocol when instantiating the SNS client. Enum values:
| HTTPS | Protocol |
| queueUrl (producer) | The queueUrl to subscribe to. | String | |
| region (producer) | The region in which SNS client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| serverSideEncryptionEnabled (producer) | Define if Server Side Encryption is enabled or not on the topic. | false | boolean |
| subject (producer) | The subject which is used if the message header 'CamelAwsSnsSubject' is not present. | String | |
| subscribeSNStoSQS (producer) | Define if the subscription between SNS Topic and SQS must be done or not. | false | boolean |
| trustAllCertificates (producer) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (producer) | Set whether the SNS client should expect to load credentials on an AWS infra instance or to expect static credentials to be passed in. | false | boolean |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
Required SNS component options
You have to provide the amazonSNSClient in the Registry or your accessKey and secretKey to access the Amazon’s SNS.
10.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
10.6.1. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
- Java system properties - aws.accessKeyId and aws.secretKey
- Environment variables - AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.
- Web Identity Token from AWS STS.
- The shared credentials and config files.
- Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set.
- Amazon EC2 Instance profile credentials.
For more information about this you can look at AWS credentials documentation.
10.6.2. Message headers evaluated by the SNS producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
|
The Amazon SNS message subject. If not set, the subject from the |
10.6.3. Message headers set by the SNS producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The Amazon SNS message ID. |
10.6.4. Advanced AmazonSNS configuration 링크 복사링크가 클립보드에 복사되었습니다!
If you need more control over the SnsClient instance configuration you can create your own instance and refer to it from the URI:
from("direct:start")
.to("aws2-sns://MyTopic?amazonSNSClient=#client");
from("direct:start")
.to("aws2-sns://MyTopic?amazonSNSClient=#client");
The #client refers to a AmazonSNS in the Registry.
10.6.5. Create a subscription between an AWS SNS Topic and an AWS SQS Queue 링크 복사링크가 클립보드에 복사되었습니다!
You can create a subscription of an SQS Queue to an SNS Topic in this way:
from("direct:start")
.to("aws2-sns://test-camel-sns1?amazonSNSClient=#amazonSNSClient&subscribeSNStoSQS=true&queueUrl=https://sqs.eu-central-1.amazonaws.com/780410022472/test-camel");
from("direct:start")
.to("aws2-sns://test-camel-sns1?amazonSNSClient=#amazonSNSClient&subscribeSNStoSQS=true&queueUrl=https://sqs.eu-central-1.amazonaws.com/780410022472/test-camel");
The #amazonSNSClient refers to a SnsClient in the Registry. By specifying subscribeSNStoSQS to true and a queueUrl of an existing SQS Queue, you’ll be able to subscribe your SQS Queue to your SNS Topic.
At this point you can consume messages coming from SNS Topic through your SQS Queue
from("aws2-sqs://test-camel?amazonSQSClient=#amazonSQSClient&delay=50&maxMessagesPerPoll=5")
.to(...);
from("aws2-sqs://test-camel?amazonSQSClient=#amazonSQSClient&delay=50&maxMessagesPerPoll=5")
.to(...);
10.7. Topic Autocreation 링크 복사링크가 클립보드에 복사되었습니다!
With the option autoCreateTopic users are able to avoid the autocreation of an SNS Topic in case it doesn’t exist. The default for this option is true. If set to false any operation on a not-existent topic in AWS won’t be successful and an error will be returned.
10.8. SNS FIFO 링크 복사링크가 클립보드에 복사되었습니다!
SNS FIFO are supported. While creating the SQS queue you will subscribe to the SNS topic there is an important point to remember, you’ll need to make possible for the SNS Topic to send message to the SQS Queue.
Example
Suppose you created an SNS FIFO Topic called Order.fifo and an SQS Queue called QueueSub.fifo.
In the access Policy of the QueueSub.fifo you should submit something like this:
This is a critical step to make the subscription work correctly.
10.8.1. SNS Fifo Topic Message group Id Strategy and message Deduplication Id Strategy 링크 복사링크가 클립보드에 복사되었습니다!
When sending something to the FIFO topic you’ll need to always set up a message group Id strategy.
If the content-based message deduplication has been enabled on the SNS Fifo topic, where won’t be the need of setting a message deduplication id strategy, otherwise you’ll have to set it.
10.9. Examples 링크 복사링크가 클립보드에 복사되었습니다!
10.9.1. Producer Examples 링크 복사링크가 클립보드에 복사되었습니다!
Sending to a topic
from("direct:start")
.to("aws2-sns://camel-topic?subject=The+subject+message&autoCreateTopic=true");
from("direct:start")
.to("aws2-sns://camel-topic?subject=The+subject+message&autoCreateTopic=true");
10.10. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
Maven users will need to add the following dependency to their pom.xml.
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-sns</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-sns</artifactId>
<version>${camel-version}</version>
</dependency>
where {camel-version} must be replaced by the actual version of Camel.
10.11. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 25 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-sns.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-sns.amazon-s-n-s-client | To use the AmazonSNS as the client. The option is a software.amazon.awssdk.services.sns.SnsClient type. | SnsClient | |
| camel.component.aws2-sns.auto-create-topic | Setting the autocreation of the topic. | false | Boolean |
| camel.component.aws2-sns.autowired-enabled | 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 |
| camel.component.aws2-sns.configuration | Component configuration. The option is a org.apache.camel.component.aws2.sns.Sns2Configuration type. | Sns2Configuration | |
| camel.component.aws2-sns.enabled | Whether to enable auto configuration of the aws2-sns component. This is enabled by default. | Boolean | |
| camel.component.aws2-sns.kms-master-key-id | The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK. | String | |
| camel.component.aws2-sns.lazy-start-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 |
| camel.component.aws2-sns.message-deduplication-id-strategy | Only for FIFO Topic. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message. | useExchangeId | String |
| camel.component.aws2-sns.message-group-id-strategy | Only for FIFO Topic. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used. | String | |
| camel.component.aws2-sns.message-structure | The message structure to use such as json. | String | |
| camel.component.aws2-sns.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-sns.policy | The policy for this topic. Is loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | |
| camel.component.aws2-sns.proxy-host | To define a proxy host when instantiating the SNS client. | String | |
| camel.component.aws2-sns.proxy-port | To define a proxy port when instantiating the SNS client. | Integer | |
| camel.component.aws2-sns.proxy-protocol | To define a proxy protocol when instantiating the SNS client. | Protocol | |
| camel.component.aws2-sns.queue-url | The queueUrl to subscribe to. | String | |
| camel.component.aws2-sns.region | The region in which SNS client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-sns.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-sns.server-side-encryption-enabled | Define if Server Side Encryption is enabled or not on the topic. | false | Boolean |
| camel.component.aws2-sns.subject | The subject which is used if the message header 'CamelAwsSnsSubject' is not present. | String | |
| camel.component.aws2-sns.subscribe-s-n-sto-s-q-s | Define if the subscription between SNS Topic and SQS must be done or not. | false | Boolean |
| camel.component.aws2-sns.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-sns.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-sns.use-default-credentials-provider | Set whether the SNS client should expect to load credentials on an AWS infra instance or to expect static credentials to be passed in. | false | Boolean |
Chapter 11. AWS Simple Queue Service (SQS) 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The AWS2 SQS component supports sending and receiving messages to Amazon’s SQS service.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon SQS. More information is available at Amazon SQS.
11.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using aws2-sqs with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws2-sqs-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws2-sqs-starter</artifactId>
</dependency>
11.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws2-sqs://queueNameOrArn[?options]
aws2-sqs://queueNameOrArn[?options]
The queue will be created if they don’t already exists. You can append query options to the URI in the following format,
?options=value&option2=value&…
11.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
11.3.1. 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.
11.3.2. 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.
11.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Simple Queue Service (SQS) component supports 43 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amazonAWSHost (common) | The hostname of the Amazon AWS cloud. | amazonaws.com | String |
| amazonSQSClient (common) | Autowired To use the AmazonSQS as client. | SqsClient | |
| autoCreateQueue (common) | Setting the autocreation of the queue. | false | boolean |
| configuration (common) | The AWS SQS default configuration. | Sqs2Configuration | |
| overrideEndpoint (common) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| protocol (common) | The underlying protocol used to communicate with SQS. | https | String |
| proxyProtocol (common) | To define a proxy protocol when instantiating the SQS client. Enum values:
| HTTPS | Protocol |
| queueOwnerAWSAccountId (common) | Specify the queue owner aws account id when you need to connect the queue with different account owner. | String | |
| region (common) | The region in which SQS client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (common) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (common) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (common) | Set whether the SQS client should expect to load credentials on an AWS infra instance or to expect static credentials to be passed in. | false | boolean |
| attributeNames (consumer) | A list of attribute names to receive when consuming. Multiple names can be separated by comma. | String | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| concurrentConsumers (consumer) | Allows you to use multiple threads to poll the sqs queue to increase throughput. | 1 | int |
| defaultVisibilityTimeout (consumer) | The default visibility timeout (in seconds). | Integer | |
| deleteAfterRead (consumer) | Delete message from SQS after it has been read. | true | boolean |
| deleteIfFiltered (consumer) | Whether or not to send the DeleteMessage to the SQS queue if the exchange has property with key Sqs2Constants#SQS_DELETE_FILTERED (CamelAwsSqsDeleteFiltered) set to true. | true | boolean |
| extendMessageVisibility (consumer) | If enabled then a scheduled background task will keep extending the message visibility on SQS. This is needed if it takes a long time to process the message. If set to true defaultVisibilityTimeout must be set. | false | boolean |
| kmsDataKeyReusePeriodSeconds (consumer) | The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). Default: 300 (5 minutes). | Integer | |
| kmsMasterKeyId (consumer) | The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. | String | |
| messageAttributeNames (consumer) | A list of message attribute names to receive when consuming. Multiple names can be separated by comma. | String | |
| serverSideEncryptionEnabled (consumer) | Define if Server Side Encryption is enabled or not on the queue. | false | boolean |
| visibilityTimeout (consumer) | The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request to set in the com.amazonaws.services.sqs.model.SetQueueAttributesRequest. This only make sense if its different from defaultVisibilityTimeout. It changes the queue visibility timeout attribute permanently. | Integer | |
| waitTimeSeconds (consumer) | Duration in seconds (0 to 20) that the ReceiveMessage action call will wait until a message is in the queue to include in the response. | Integer | |
| batchSeparator (producer) | Set the separator when passing a String to send batch message operation. | , | String |
| delaySeconds (producer) | Delay sending messages for a number of seconds. | Integer | |
| 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 |
| messageDeduplicationIdStrategy (producer) | Only for FIFO queues. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message. Enum values:
| useExchangeId | String |
| messageGroupIdStrategy (producer) | Only for FIFO queues. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used. Enum values:
| String | |
| operation (producer) | The operation to do in case the user don’t want to send only a message. Enum values:
| Sqs2Operations | |
| 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 |
| delayQueue (advanced) | Define if you want to apply delaySeconds option to the queue or on single messages. | false | boolean |
| queueUrl (advanced) | To define the queueUrl explicitly. All other parameters, which would influence the queueUrl, are ignored. This parameter is intended to be used, to connect to a mock implementation of SQS, for testing purposes. | String | |
| proxyHost (proxy) | To define a proxy host when instantiating the SQS client. | String | |
| proxyPort (proxy) | To define a proxy port when instantiating the SQS client. | Integer | |
| maximumMessageSize (queue) | The maximumMessageSize (in bytes) an SQS message can contain for this queue. | Integer | |
| messageRetentionPeriod (queue) | The messageRetentionPeriod (in seconds) a message will be retained by SQS for this queue. | Integer | |
| policy (queue) | The policy for this queue. It can be loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | |
| receiveMessageWaitTimeSeconds (queue) | If you do not specify WaitTimeSeconds in the request, the queue attribute ReceiveMessageWaitTimeSeconds is used to determine how long to wait. | Integer | |
| redrivePolicy (queue) | Specify the policy that send message to DeadLetter queue. See detail at Amazon docs. | String | |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
11.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Simple Queue Service (SQS) endpoint is configured using URI syntax:
aws2-sqs:queueNameOrArn
aws2-sqs:queueNameOrArn
with the following path and query parameters:
11.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| queueNameOrArn (common) | Required Queue name or ARN. | String |
11.5.2. Query Parameters (61 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amazonAWSHost (common) | The hostname of the Amazon AWS cloud. | amazonaws.com | String |
| amazonSQSClient (common) | Autowired To use the AmazonSQS as client. | SqsClient | |
| autoCreateQueue (common) | Setting the autocreation of the queue. | false | boolean |
| headerFilterStrategy (common) | To use a custom HeaderFilterStrategy to map headers to/from Camel. | HeaderFilterStrategy | |
| overrideEndpoint (common) | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | boolean |
| protocol (common) | The underlying protocol used to communicate with SQS. | https | String |
| proxyProtocol (common) | To define a proxy protocol when instantiating the SQS client. Enum values:
| HTTPS | Protocol |
| queueOwnerAWSAccountId (common) | Specify the queue owner aws account id when you need to connect the queue with different account owner. | String | |
| region (common) | The region in which SQS client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| trustAllCertificates (common) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| uriEndpointOverride (common) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useDefaultCredentialsProvider (common) | Set whether the SQS client should expect to load credentials on an AWS infra instance or to expect static credentials to be passed in. | false | boolean |
| attributeNames (consumer) | A list of attribute names to receive when consuming. Multiple names can be separated by comma. | String | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| concurrentConsumers (consumer) | Allows you to use multiple threads to poll the sqs queue to increase throughput. | 1 | int |
| defaultVisibilityTimeout (consumer) | The default visibility timeout (in seconds). | Integer | |
| deleteAfterRead (consumer) | Delete message from SQS after it has been read. | true | boolean |
| deleteIfFiltered (consumer) | Whether or not to send the DeleteMessage to the SQS queue if the exchange has property with key Sqs2Constants#SQS_DELETE_FILTERED (CamelAwsSqsDeleteFiltered) set to true. | true | boolean |
| extendMessageVisibility (consumer) | If enabled then a scheduled background task will keep extending the message visibility on SQS. This is needed if it takes a long time to process the message. If set to true defaultVisibilityTimeout must be set. See details at Amazon docs. | false | boolean |
| kmsDataKeyReusePeriodSeconds (consumer) | The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). Default: 300 (5 minutes). | Integer | |
| kmsMasterKeyId (consumer) | The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. | String | |
| maxMessagesPerPoll (consumer) | Gets the maximum number of messages as a limit to poll at each polling. Is default unlimited, but use 0 or negative number to disable it as unlimited. | int | |
| messageAttributeNames (consumer) | A list of message attribute names to receive when consuming. Multiple names can be separated by comma. | String | |
| sendEmptyMessageWhenIdle (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | false | boolean |
| serverSideEncryptionEnabled (consumer) | Define if Server Side Encryption is enabled or not on the queue. | false | boolean |
| visibilityTimeout (consumer) | The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request to set in the com.amazonaws.services.sqs.model.SetQueueAttributesRequest. This only make sense if its different from defaultVisibilityTimeout. It changes the queue visibility timeout attribute permanently. | Integer | |
| waitTimeSeconds (consumer) | Duration in seconds (0 to 20) that the ReceiveMessage action call will wait until a message is in the queue to include in the response. | Integer | |
| 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:
| ExchangePattern | |
| pollStrategy (consumer (advanced)) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | |
| batchSeparator (producer) | Set the separator when passing a String to send batch message operation. | , | String |
| delaySeconds (producer) | Delay sending messages for a number of seconds. | Integer | |
| 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 |
| messageDeduplicationIdStrategy (producer) | Only for FIFO queues. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message. Enum values:
| useExchangeId | String |
| messageGroupIdStrategy (producer) | Only for FIFO queues. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used. Enum values:
| String | |
| operation (producer) | The operation to do in case the user don’t want to send only a message. Enum values:
| Sqs2Operations | |
| delayQueue (advanced) | Define if you want to apply delaySeconds option to the queue or on single messages. | false | boolean |
| queueUrl (advanced) | To define the queueUrl explicitly. All other parameters, which would influence the queueUrl, are ignored. This parameter is intended to be used, to connect to a mock implementation of SQS, for testing purposes. | String | |
| proxyHost (proxy) | To define a proxy host when instantiating the SQS client. | String | |
| proxyPort (proxy) | To define a proxy port when instantiating the SQS client. | Integer | |
| maximumMessageSize (queue) | The maximumMessageSize (in bytes) an SQS message can contain for this queue. | Integer | |
| messageRetentionPeriod (queue) | The messageRetentionPeriod (in seconds) a message will be retained by SQS for this queue. | Integer | |
| policy (queue) | The policy for this queue. It can be loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | |
| receiveMessageWaitTimeSeconds (queue) | If you do not specify WaitTimeSeconds in the request, the queue attribute ReceiveMessageWaitTimeSeconds is used to determine how long to wait. | Integer | |
| redrivePolicy (queue) | Specify the policy that send message to DeadLetter queue. See detail at Amazon docs. | String | |
| backoffErrorThreshold (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | |
| backoffIdleThreshold (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | |
| backoffMultiplier (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | |
| delay (scheduler) | Milliseconds before the next poll. | 500 | long |
| greedy (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean |
| initialDelay (scheduler) | Milliseconds before the first poll starts. | 1000 | long |
| repeatCount (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long |
| runLoggingLevel (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel |
| scheduledExecutorService (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | |
| scheduler (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object |
| schedulerProperties (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | Map | |
| startScheduler (scheduler) | Whether the scheduler should be auto started. | true | boolean |
| timeUnit (scheduler) | Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit |
| useFixedDelay (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String |
Required SQS component options
You have to provide the amazonSQSClient in the Registry or your accessKey and secretKey to access the Amazon’s SQS.
11.6. Batch Consumer 링크 복사링크가 클립보드에 복사되었습니다!
This component implements the Batch Consumer.
This allows you for instance to know how many messages exists in this batch and for instance let the Aggregator aggregate this number of messages.
11.7. Usage 링크 복사링크가 클립보드에 복사되었습니다!
11.7.1. Static credentials vs Default Credential Provider 링크 복사링크가 클립보드에 복사되었습니다!
You have the possibility of avoiding the usage of explicit static credentials, by specifying the useDefaultCredentialsProvider option and set it to true.
-
Java system properties -
aws.accessKeyIdandaws.secretKey -
Environment variables -
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. - Web Identity Token from AWS STS.
- The shared credentials and config files.
-
Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable
AWS_CONTAINER_CREDENTIALS_RELATIVE_URIis set. - Amazon EC2 Instance profile credentials.
For more information about this you can look at AWS credentials documentation
11.7.2. Message headers set by the SQS producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The MD5 checksum of the Amazon SQS message. |
|
|
| The Amazon SQS message ID. |
|
|
| The delay seconds that the Amazon SQS message can be see by others. |
11.7.3. Message headers set by the SQS consumer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Type | Description |
|---|---|---|
|
|
| The MD5 checksum of the Amazon SQS message. |
|
|
| The Amazon SQS message ID. |
|
|
| The Amazon SQS message receipt handle. |
|
|
| The Amazon SQS message attributes. |
11.7.4. Advanced AmazonSQS configuration 링크 복사링크가 클립보드에 복사되었습니다!
If your Camel Application is running behind a firewall or if you need to have more control over the SqsClient instance configuration, you can create your own instance:
from("aws2-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
from("aws2-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
11.7.5. Creating or updating an SQS Queue 링크 복사링크가 클립보드에 복사되었습니다!
In the SQS Component, when an endpoint is started, a check is executed to obtain information about the existence of the queue or not. You’re able to customize the creation through the QueueAttributeName mapping with the SQSConfiguration option.
from("aws2-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
from("aws2-sqs://MyQueue?amazonSQSClient=#client&delay=5000&maxMessagesPerPoll=5")
.to("mock:result");
In this example if the MyQueue queue is not already created on AWS (and the autoCreateQueue option is set to true), it will be created with default parameters from the SQS configuration. If it’s already up on AWS, the SQS configuration options will be used to override the existent AWS configuration.
11.7.6. DelayQueue VS Delay for Single message 링크 복사링크가 클립보드에 복사되었습니다!
When the option delayQueue is set to true, the SQS Queue will be a DelayQueue with the DelaySeconds option as delay. For more information about DelayQueue you can read the AWS SQS documentation. One important information to take into account is the following:
- For standard queues, the per-queue delay setting is not retroactive—changing the setting doesn’t affect the delay of messages already in the queue.
- For FIFO queues, the per-queue delay setting is retroactive—changing the setting affects the delay of messages already in the queue.
as stated in the official documentation. If you want to specify a delay on single messages, you can ignore the delayQueue option, while you can set this option to true, if you need to add a fixed delay to all messages enqueued.
11.7.7. Server Side Encryption 링크 복사링크가 클립보드에 복사되었습니다!
There is a set of Server Side Encryption attributes for a queue. The related option are serverSideEncryptionEnabled, keyMasterKeyId and kmsDataKeyReusePeriod. The SSE is disabled by default. You need to explicitly set the option to true and set the related parameters as queue attributes.
11.8. JMS-style Selectors 링크 복사링크가 클립보드에 복사되었습니다!
SQS does not allow selectors, but you can effectively achieve this by using the Camel Filter EIP and setting an appropriate visibilityTimeout. When SQS dispatches a message, it will wait up to the visibility timeout before it will try to dispatch the message to a different consumer unless a DeleteMessage is received. By default, Camel will always send the DeleteMessage at the end of the route, unless the route ended in failure. To achieve appropriate filtering and not send the DeleteMessage even on successful completion of the route, use a Filter:
from("aws2-sqs://MyQueue?amazonSQSClient=#client&defaultVisibilityTimeout=5000&deleteIfFiltered=false&deleteAfterRead=false")
.filter("${header.login} == true")
.setProperty(Sqs2Constants.SQS_DELETE_FILTERED, constant(true))
.to("mock:filter");
from("aws2-sqs://MyQueue?amazonSQSClient=#client&defaultVisibilityTimeout=5000&deleteIfFiltered=false&deleteAfterRead=false")
.filter("${header.login} == true")
.setProperty(Sqs2Constants.SQS_DELETE_FILTERED, constant(true))
.to("mock:filter");
In the above code, if an exchange doesn’t have an appropriate header, it will not make it through the filter AND also not be deleted from the SQS queue. After 5000 milliseconds, the message will become visible to other consumers.
Note we must set the property Sqs2Constants.SQS_DELETE_FILTERED to true to instruct Camel to send the DeleteMessage, if being filtered.
11.9. Available Producer Operations 링크 복사링크가 클립보드에 복사되었습니다!
- single message (default)
- sendBatchMessage
- deleteMessage
- listQueues
11.10. Send Message 링크 복사링크가 클립보드에 복사되었습니다!
You can set a SendMessageBatchRequest or an Iterable
from("direct:start")
.setBody(constant("Camel rocks!"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
from("direct:start")
.setBody(constant("Camel rocks!"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
11.11. Send Batch Message 링크 복사링크가 클립보드에 복사되었습니다!
You can set a SendMessageBatchRequest or an Iterable
As result you’ll get an exchange containing a SendMessageBatchResponse instance, that you can examinate to check what messages were successfull and what not. The id set on each message of the batch will be a Random UUID.
11.12. Delete single Message 링크 복사링크가 클립보드에 복사되었습니다!
Use deleteMessage operation to delete a single message. You’ll need to set a receipt handle header for the message you want to delete.
from("direct:start")
.setHeader(SqsConstants.SQS_OPERATION, constant("deleteMessage"))
.setHeader(SqsConstants.RECEIPT_HANDLE, constant("123456"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
from("direct:start")
.setHeader(SqsConstants.SQS_OPERATION, constant("deleteMessage"))
.setHeader(SqsConstants.RECEIPT_HANDLE, constant("123456"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
As result you’ll get an exchange containing a DeleteMessageResponse instance, that you can use to check if the message was deleted or not.
11.13. List Queues 링크 복사링크가 클립보드에 복사되었습니다!
Use listQueues operation to list queues.
from("direct:start")
.setHeader(SqsConstants.SQS_OPERATION, constant("listQueues"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
from("direct:start")
.setHeader(SqsConstants.SQS_OPERATION, constant("listQueues"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
As result you’ll get an exchange containing a ListQueuesResponse instance, that you can examinate to check the actual queues.
11.14. Purge Queue 링크 복사링크가 클립보드에 복사되었습니다!
Use purgeQueue operation to purge queue.
from("direct:start")
.setHeader(SqsConstants.SQS_OPERATION, constant("purgeQueue"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
from("direct:start")
.setHeader(SqsConstants.SQS_OPERATION, constant("purgeQueue"))
.to("aws2-sqs://camel-1?accessKey=RAW(xxx)&secretKey=RAW(xxx)®ion=eu-west-1");
As result you’ll get an exchange containing a PurgeQueueResponse instance.
11.15. Queue Autocreation 링크 복사링크가 클립보드에 복사되었습니다!
With the option autoCreateQueue users are able to avoid the autocreation of an SQS Queue in case it doesn’t exist. The default for this option is true. If set to false any operation on a not-existent queue in AWS won’t be successful and an error will be returned.
11.16. Send Batch Message and Message Deduplication Strategy 링크 복사링크가 클립보드에 복사되었습니다!
In case you’re using a SendBatchMessage Operation, you can set two different kind of Message Deduplication Strategy: - useExchangeId - useContentBasedDeduplication
The first one will use a ExchangeIdMessageDeduplicationIdStrategy, that will use the Exchange ID as parameter The other one will use a NullMessageDeduplicationIdStrategy, that will use the body as deduplication element.
In case of send batch message operation, you’ll need to use the useContentBasedDeduplication and on the Queue you’re pointing you’ll need to enable the content based deduplication option.
11.17. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
Maven users will need to add the following dependency to their pom.xml.
pom.xml
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-sqs</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-aws2-sqs</artifactId>
<version>${camel-version}</version>
</dependency>
where {camel-version} must be replaced by the actual version of Camel.
11.18. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 44 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws2-sqs.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws2-sqs.amazon-a-w-s-host | The hostname of the Amazon AWS cloud. | amazonaws.com | String |
| camel.component.aws2-sqs.amazon-s-q-s-client | To use the AmazonSQS as client. The option is a software.amazon.awssdk.services.sqs.SqsClient type. | SqsClient | |
| camel.component.aws2-sqs.attribute-names | A list of attribute names to receive when consuming. Multiple names can be separated by comma. | String | |
| camel.component.aws2-sqs.auto-create-queue | Setting the autocreation of the queue. | false | Boolean |
| camel.component.aws2-sqs.autowired-enabled | 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 |
| camel.component.aws2-sqs.batch-separator | Set the separator when passing a String to send batch message operation. | , | String |
| camel.component.aws2-sqs.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.aws2-sqs.concurrent-consumers | Allows you to use multiple threads to poll the sqs queue to increase throughput. | 1 | Integer |
| camel.component.aws2-sqs.configuration | The AWS SQS default configuration. The option is a org.apache.camel.component.aws2.sqs.Sqs2Configuration type. | Sqs2Configuration | |
| camel.component.aws2-sqs.default-visibility-timeout | The default visibility timeout (in seconds). | Integer | |
| camel.component.aws2-sqs.delay-queue | Define if you want to apply delaySeconds option to the queue or on single messages. | false | Boolean |
| camel.component.aws2-sqs.delay-seconds | Delay sending messages for a number of seconds. | Integer | |
| camel.component.aws2-sqs.delete-after-read | Delete message from SQS after it has been read. | true | Boolean |
| camel.component.aws2-sqs.delete-if-filtered | Whether or not to send the DeleteMessage to the SQS queue if the exchange has property with key Sqs2Constants#SQS_DELETE_FILTERED (CamelAwsSqsDeleteFiltered) set to true. | true | Boolean |
| camel.component.aws2-sqs.enabled | Whether to enable auto configuration of the aws2-sqs component. This is enabled by default. | Boolean | |
| camel.component.aws2-sqs.extend-message-visibility | If enabled then a scheduled background task will keep extending the message visibility on SQS. This is needed if it takes a long time to process the message. If set to true defaultVisibilityTimeout must be set. See details at Amazon docs. | false | Boolean |
| camel.component.aws2-sqs.kms-data-key-reuse-period-seconds | The length of time, in seconds, for which Amazon SQS can reuse a data key to encrypt or decrypt messages before calling AWS KMS again. An integer representing seconds, between 60 seconds (1 minute) and 86,400 seconds (24 hours). Default: 300 (5 minutes). | Integer | |
| camel.component.aws2-sqs.kms-master-key-id | The ID of an AWS-managed customer master key (CMK) for Amazon SQS or a custom CMK. | String | |
| camel.component.aws2-sqs.lazy-start-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 |
| camel.component.aws2-sqs.maximum-message-size | The maximumMessageSize (in bytes) an SQS message can contain for this queue. | Integer | |
| camel.component.aws2-sqs.message-attribute-names | A list of message attribute names to receive when consuming. Multiple names can be separated by comma. | String | |
| camel.component.aws2-sqs.message-deduplication-id-strategy | Only for FIFO queues. Strategy for setting the messageDeduplicationId on the message. Can be one of the following options: useExchangeId, useContentBasedDeduplication. For the useContentBasedDeduplication option, no messageDeduplicationId will be set on the message. | useExchangeId | String |
| camel.component.aws2-sqs.message-group-id-strategy | Only for FIFO queues. Strategy for setting the messageGroupId on the message. Can be one of the following options: useConstant, useExchangeId, usePropertyValue. For the usePropertyValue option, the value of property CamelAwsMessageGroupId will be used. | String | |
| camel.component.aws2-sqs.message-retention-period | The messageRetentionPeriod (in seconds) a message will be retained by SQS for this queue. | Integer | |
| camel.component.aws2-sqs.operation | The operation to do in case the user don’t want to send only a message. | Sqs2Operations | |
| camel.component.aws2-sqs.override-endpoint | Set the need for overidding the endpoint. This option needs to be used in combination with uriEndpointOverride option. | false | Boolean |
| camel.component.aws2-sqs.policy | The policy for this queue. It can be loaded by default from classpath, but you can prefix with classpath:, file:, or http: to load the resource from different systems. | String | |
| camel.component.aws2-sqs.protocol | The underlying protocol used to communicate with SQS. | https | String |
| camel.component.aws2-sqs.proxy-host | To define a proxy host when instantiating the SQS client. | String | |
| camel.component.aws2-sqs.proxy-port | To define a proxy port when instantiating the SQS client. | Integer | |
| camel.component.aws2-sqs.proxy-protocol | To define a proxy protocol when instantiating the SQS client. | Protocol | |
| camel.component.aws2-sqs.queue-owner-a-w-s-account-id | Specify the queue owner aws account id when you need to connect the queue with different account owner. | String | |
| camel.component.aws2-sqs.queue-url | To define the queueUrl explicitly. All other parameters, which would influence the queueUrl, are ignored. This parameter is intended to be used, to connect to a mock implementation of SQS, for testing purposes. | String | |
| camel.component.aws2-sqs.receive-message-wait-time-seconds | If you do not specify WaitTimeSeconds in the request, the queue attribute ReceiveMessageWaitTimeSeconds is used to determine how long to wait. | Integer | |
| camel.component.aws2-sqs.redrive-policy | Specify the policy that send message to DeadLetter queue. See detail at Amazon docs. | String | |
| camel.component.aws2-sqs.region | The region in which SQS client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws2-sqs.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws2-sqs.server-side-encryption-enabled | Define if Server Side Encryption is enabled or not on the queue. | false | Boolean |
| camel.component.aws2-sqs.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws2-sqs.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws2-sqs.use-default-credentials-provider | Set whether the SQS client should expect to load credentials on an AWS infra instance or to expect static credentials to be passed in. | false | Boolean |
| camel.component.aws2-sqs.visibility-timeout | The duration (in seconds) that the received messages are hidden from subsequent retrieve requests after being retrieved by a ReceiveMessage request to set in the com.amazonaws.services.sqs.model.SetQueueAttributesRequest. This only make sense if its different from defaultVisibilityTimeout. It changes the queue visibility timeout attribute permanently. | Integer | |
| camel.component.aws2-sqs.wait-time-seconds | Duration in seconds (0 to 20) that the ReceiveMessage action call will wait until a message is in the queue to include in the response. | Integer |
Chapter 12. AWS Secrets Manager 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The AWS Secrets Manager component supports AWS Secrets Manager service.
Prerequisites
You must have a valid Amazon Web Services developer account, and be signed up to use Amazon Secrets Manager. More information is available at AWS Secrets Manager.
12.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using camel-aws-secrets-manager with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-aws-secrets-manager-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-aws-secrets-manager-starter</artifactId>
</dependency>
12.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
aws-secrets-manager://label[?options]
aws-secrets-manager://label[?options]
You can append query options to the URI in the following format:
`?options=value&option2=value&…`
`?options=value&option2=value&…`
12.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
12.3.1. 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.
12.3.2. 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.
12.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Secrets Manager component supports 23 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| binaryPayload (producer) | Set if the secret is binary or not. | false | boolean |
| configuration (producer) | Component configuration. | SecretsManagerConfiguration | |
| 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 |
| operation (producer) | Required The operation to perform. Enum values:
| SecretsManagerOperations | |
| overrideEndpoint (producer) | Set the need for overriding the endpoint. This option needs to be used in combination with the uriEndpointOverride option. | false | boolean |
| pojoRequest (producer) | If we want to use a POJO request as body or not. | false | boolean |
| profileCredentialsName (producer) | If using a profile credentials provider, this parameter will set the profile name. | String | |
| region (producer) | The region in which a Secrets Manager client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example, ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). Enum values:
| String | |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useProfileCredentialsProvider (producer) | Set whether the Secrets Manager client should expect to load credentials through a profile credentials provider. | 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 |
| secretsManagerClient (advanced) | Autowired To use an existing configured AWS Secrets Manager client. | SecretsManagerClient | |
| healthCheckConsumerEnabled (health) | Used for enabling or disabling all consumer based health checks from this component. | true | boolean |
| healthCheckProducerEnabled (health) | Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean |
| proxyHost (proxy) | To define a proxy host when instantiating the Secrets Manager client. | String | |
| proxyPort (proxy) | To define a proxy port when instantiating the Secrets Manager client. | Integer | |
| proxyProtocol (proxy) | To define a proxy protocol when instantiating the Secrets Manager client. Enum values:
| HTTPS | Protocol |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String | |
| sessionToken (security) | Amazon AWS Session Token used when the user needs to assume an IAM role. | String | |
| trustAllCertificates (security) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| useDefaultCredentialsProvider (security) | Set whether the Translate client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| useSessionCredentials (security) | Set whether the Secrets Manager client should expect to use Session Credentials. This is useful in a situation in which the user needs to assume an IAM role for doing operations in Secrets Manager. | false | boolean |
12.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Secrets Manager endpoint is configured using URI syntax:
aws-secrets-manager:label
aws-secrets-manager:label
With the following path and query parameters:
12.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| label (producer) | Required Logical name. | String |
12.5.2. Query Parameters (19 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| binaryPayload (producer) | Set if the secret is binary or not. | false | boolean |
| operation (producer) | Required The operation to perform. Enum values:
| SecretsManagerOperations | |
| overrideEndpoint (producer) | Set the need for overriding the endpoint. This option needs to be used in combination with the uriEndpointOverride option. | false | boolean |
| pojoRequest (producer) | If we want to use a POJO request as body or not. | false | boolean |
| profileCredentialsName (producer) | If using a profile credentials provider, this parameter will set the profile name. | String | |
| region (producer) | The region in which a Secrets Manager client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example, ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). Enum values:
| String | |
| uriEndpointOverride (producer) | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| useProfileCredentialsProvider (producer) | Set whether the Secrets Manager client should expect to load credentials through a profile credentials provider. | false | boolean |
| 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 |
| secretsManagerClient (advanced) | Autowired To use an existing configured AWS Secrets Manager client. | SecretsManagerClient | |
| proxyHost (proxy) | To define a proxy host when instantiating the Secrets Manager client. | String | |
| proxyPort (proxy) | To define a proxy port when instantiating the Secrets Manager client. | Integer | |
| proxyProtocol (proxy) | To define a proxy protocol when instantiating the Secrets Manager client. Enum values:
| HTTPS | Protocol |
| accessKey (security) | Amazon AWS Access Key. | String | |
| secretKey (security) | Amazon AWS Secret Key. | String | |
| sessionToken (security) | Amazon AWS Session Token used when the user needs to assume an IAM role. | String | |
| trustAllCertificates (security) | If we want to trust all certificates in case of overriding the endpoint. | false | boolean |
| useDefaultCredentialsProvider (security) | Set whether the Translate client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | boolean |
| useSessionCredentials (security) | Set whether the Secrets Manager client should expect to use Session Credentials. This is useful in a situation in which the user needs to assume an IAM role for doing operations in Secrets Manager. | false | boolean |
12.5.3. Static credentials, Default Credential Provider and Profile Credentials Provider 링크 복사링크가 클립보드에 복사되었습니다!
You can avoid the usage of explicit static credentials by specifying the useDefaultCredentialsProvider option and setting it to true.
The order of evaluation for Default Credentials Provider is as per the following:
-
Java system properties -
aws.accessKeyIdandaws.secretKey. -
Environment variables -
AWS_ACCESS_KEY_IDandAWS_SECRET_ACCESS_KEY. - Web Identity Token from AWS STS.
- The shared credentials and config files.
-
Amazon ECS container credentials - loaded from the Amazon ECS if the environment variable
AWS_CONTAINER_CREDENTIALS_RELATIVE_URIis set. - Amazon EC2 Instance profile credentials.
You can use the Profile Credentials Provider, by specifying the useProfileCredentialsProvider option to true and profileCredentialsName to the profile name.
Only one of static, default and profile credentials could be used at the same time. For more information about this, see AWS credentials documentation.
12.5.4. Using AWS Secrets Manager Property Function 링크 복사링크가 클립보드에 복사되었습니다!
To use this function, you need to provide credentials to AWS Secrets Manager Service as environment variables:
export CAMEL_VAULT_AWS_ACCESS_KEY=accessKey export CAMEL_VAULT_AWS_SECRET_KEY=secretKey export CAMEL_VAULT_AWS_REGION=region
export CAMEL_VAULT_AWS_ACCESS_KEY=accessKey
export CAMEL_VAULT_AWS_SECRET_KEY=secretKey
export CAMEL_VAULT_AWS_REGION=region
You can also configure the credentials in the application.properties file such as:
camel.vault.aws.accessKey = accessKey camel.vault.aws.secretKey = secretKey camel.vault.aws.region = region
camel.vault.aws.accessKey = accessKey
camel.vault.aws.secretKey = secretKey
camel.vault.aws.region = region
If you want to use the AWS default credentials provider instead, you need to provide the following env variables:
export CAMEL_VAULT_AWS_USE_DEFAULT_CREDENTIALS_PROVIDER=true export CAMEL_VAULT_AWS_REGION=region
export CAMEL_VAULT_AWS_USE_DEFAULT_CREDENTIALS_PROVIDER=true
export CAMEL_VAULT_AWS_REGION=region
You can also configure the credentials in the application.properties file such as:
camel.vault.aws.defaultCredentialsProvider = true camel.vault.aws.region = region
camel.vault.aws.defaultCredentialsProvider = true
camel.vault.aws.region = region
It is also possible to specify a particular profile name for accessing AWS Secrets Manager as follows:
export CAMEL_VAULT_AWS_USE_PROFILE_CREDENTIALS_PROVIDER=true export CAMEL_VAULT_AWS_PROFILE_NAME=test-account export CAMEL_VAULT_AWS_REGION=region
export CAMEL_VAULT_AWS_USE_PROFILE_CREDENTIALS_PROVIDER=true
export CAMEL_VAULT_AWS_PROFILE_NAME=test-account
export CAMEL_VAULT_AWS_REGION=region
You can also configure the credentials in the application.properties file such as:
camel.vault.aws.profileCredentialsProvider = true camel.vault.aws.profileName = test-account camel.vault.aws.region = region
camel.vault.aws.profileCredentialsProvider = true
camel.vault.aws.profileName = test-account
camel.vault.aws.region = region
camel.vault.aws configuration only applies to the AWS Secrets Manager properties function (for example, when resolving properties). When using the operation option to create, get, list secrets etc., provide the usual options for connecting to AWS Services.
At this point, you can reference a property in the following way:
Where the route will be the name of the secret stored in the AWS Secrets Manager Service.
You could specify a default value in case the secret is not present on AWS Secret Manager:
In this case, if the secret doesn’t exist, the property will fall back to "default" as value.
Also, you are able to get a particular field of the secret, if you have, for example, a secret named database of this form:
You can get a single secret value in your route as follows:
Or re-use the property as part of an endpoint.
You can specify a default value in case the particular field of secret is not present on AWS Secret Manager:
In this case, if the secret does not exist or the secret exists, but the username field is not part of the secret, the property will fall back to "admin" as its value.
There is also the syntax to get a particular version of the secret for both the approach, with field/default value specified or only with secret:
This approach will return the RAW route secret with the version 'bf9b4f4b-8e63-43fd-a73c-3e2d3748b451'.
This approach will return the route secret value with version 'bf9b4f4b-8e63-43fd-a73c-3e2d3748b451' or default value in case the secret doesn’t exist or the version doesn’t exist.
This approach will return the username field of the database secret with version 'bf9b4f4b-8e63-43fd-a73c-3e2d3748b451' or admin in case the secret doesn’t exist or the version doesn’t exist.
The only requirement is adding the camel-aws-secrets-manager jar to your Camel application.
12.5.5. Automatic Camel context reloading on Secret Refresh 링크 복사링크가 클립보드에 복사되었습니다!
Being able to reload Camel context on a Secret Refresh could be done by specifying the usual credentials (the same used for AWS Secret Manager Property Function).
With Environment variables:
export CAMEL_VAULT_AWS_USE_DEFAULT_CREDENTIALS_PROVIDER=accessKey export CAMEL_VAULT_AWS_REGION=region
export CAMEL_VAULT_AWS_USE_DEFAULT_CREDENTIALS_PROVIDER=accessKey
export CAMEL_VAULT_AWS_REGION=region
or as plain Camel main properties:
camel.vault.aws.useDefaultCredentialProvider = true camel.vault.aws.region = region
camel.vault.aws.useDefaultCredentialProvider = true
camel.vault.aws.region = region
Or by specifying accessKey/SecretKey and region, instead of using the default credentials provider chain.
To enable the automatic refresh, set the additional properties as follows:
camel.vault.aws.refreshEnabled=true camel.vault.aws.refreshPeriod=60000 camel.vault.aws.secrets=Secret camel.main.context-reload-enabled = true
camel.vault.aws.refreshEnabled=true
camel.vault.aws.refreshPeriod=60000
camel.vault.aws.secrets=Secret
camel.main.context-reload-enabled = true
where camel.vault.aws.refreshEnabled will enable the automatic context reload, camel.vault.aws.refreshPeriod is the interval of time between two different checks for update events and camel.vault.aws.secrets is a regex representing the secrets we want to track for updates.
Note that camel.vault.aws.secrets is not mandatory. If it is not specified, the task responsible for checking updates events will take it into accounts or the properties with an aws: prefix.
Another option is to use AWS EventBridge in conjunction with the AWS SQS service.
On the AWS side, the following resources need to be created:
- an AWS Couldtrail trail
- an AWS SQS Queue
- an Eventbridge rule of the following kind
This rule will make the event related to AWS Secrets Manager filtered
- You need to set the a Rule target to the AWS SQS Queue for Eventbridge rule
- You need to give permission to the Eventbrige rule, to write on the above SQS Queue. For doing this you’ll need to define a json file like this:
{
"Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"<queue_arn>/SQSDefaultPolicy\",\"Statement\":[{\"Sid\": \"EventsToMyQueue\", \"Effect\": \"Allow\", \"Principal\": {\"Service\": \"events.amazonaws.com\"}, \"Action\": \"sqs:SendMessage\", \"Resource\": \"<queue_arn>\", \"Condition\": {\"ArnEquals\": {\"aws:SourceArn\": \"<eventbridge_rule_arn>\"}}}]}"
}
{
"Policy": "{\"Version\":\"2012-10-17\",\"Id\":\"<queue_arn>/SQSDefaultPolicy\",\"Statement\":[{\"Sid\": \"EventsToMyQueue\", \"Effect\": \"Allow\", \"Principal\": {\"Service\": \"events.amazonaws.com\"}, \"Action\": \"sqs:SendMessage\", \"Resource\": \"<queue_arn>\", \"Condition\": {\"ArnEquals\": {\"aws:SourceArn\": \"<eventbridge_rule_arn>\"}}}]}"
}
Change the values for queue_arn and eventbridge_rule_arn and save the file with policy.json name and run the following command with AWS CLI:
aws sqs set-queue-attributes --queue-url <queue_url> --attributes file://policy.json
aws sqs set-queue-attributes --queue-url <queue_url> --attributes file://policy.json
where queue_url is the AWS SQS Queue URL of the just created Queue.
Now you should be able to set up the configuration on the Camel side. To enable the SQS notification add the following properties:
where queue_url is the AWS SQS Queue URL of the just created Queue.
Whenever an event of PutSecretValue for the Secret named Secret happens, a message will be enqueued in the AWS SQS Queue and consumed on the Camel side and a context reload will be triggered.
12.6. Message Headers 링크 복사링크가 클립보드에 복사되었습니다!
The AWS Secrets Manager component supports 8 message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| CamelAwsSecretsManagerOperation (producer) Constant: OPERATION | The operation we want to perform. | String | |
| CamelAwsSecretsManagerMaxResults (producer) Constant: MAX_RESULTS | The number of results to include in the response. | Integer | |
| CamelAwsSecretsManagerSecretName (producer) Constant: SECRET_NAME | The name of the secret. | String | |
| CamelAwsSecretsManagerSecretDescription (producer) Constant: SECRET_DESCRIPTION | The description of the secret. | String | |
| CamelAwsSecretsManagerSecretId (producer) Constant: SECRET_ID | The ARN or name of the secret. | String | |
| CamelAwsSecretsManagerLambdaRotationFunctionArn (producer) Constant: LAMBDA_ROTATION_FUNCTION_ARN | The ARN of the Lambda rotation function that can rotate the secret. | String | |
| CamelAwsSecretsManagerSecretVersionId (producer) Constant: SECRET_VERSION_ID | The unique identifier of the version of the secret. | String | |
| CamelAwsSecretsManagerSecretReplicationRegions (producer) Constant: SECRET_REPLICATION_REGIONS | A comma separated list of Regions in which to replicate the secret. | String |
12.6.1. Secrets Manager Producer operations 링크 복사링크가 클립보드에 복사되었습니다!
Camel-AWS-Secrets-manager component provides the following operation on the producer side:
- listSecrets
- createSecret
- deleteSecret
- describeSecret
- rotateSecret
- getSecret
- updateSecret
- replicateSecretToRegions
12.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 24 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.aws-secrets-manager.access-key | Amazon AWS Access Key. | String | |
| camel.component.aws-secrets-manager.autowired-enabled | 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 |
| camel.component.aws-secrets-manager.binary-payload | Set if the secret is binary or not. | false | Boolean |
| camel.component.aws-secrets-manager.configuration | Component configuration. The option is a org.apache.camel.component.aws.secretsmanager.SecretsManagerConfiguration type. | SecretsManagerConfiguration | |
| camel.component.aws-secrets-manager.enabled | Whether to enable auto configuration of the aws-secrets-manager component. This is enabled by default. | Boolean | |
| camel.component.aws-secrets-manager.health-check-consumer-enabled | Used for enabling or disabling all consumer based health checks from this component. | true | Boolean |
| camel.component.aws-secrets-manager.health-check-producer-enabled | Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | Boolean |
| camel.component.aws-secrets-manager.lazy-start-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 |
| camel.component.aws-secrets-manager.operation | The operation to perform. | SecretsManagerOperations | |
| camel.component.aws-secrets-manager.override-endpoint | Set the need for overriding the endpoint. This option needs to be used in combination with the uriEndpointOverride option. | false | Boolean |
| camel.component.aws-secrets-manager.pojo-request | If we want to use a POJO request as body or not. | false | Boolean |
| camel.component.aws-secrets-manager.profile-credentials-name | If using a profile credentials provider, this parameter will set the profile name. | String | |
| camel.component.aws-secrets-manager.proxy-host | To define a proxy host when instantiating the Secrets Manager client. | String | |
| camel.component.aws-secrets-manager.proxy-port | To define a proxy port when instantiating the Secrets Manager client. | Integer | |
| camel.component.aws-secrets-manager.proxy-protocol | To define a proxy protocol when instantiating the Secrets Manager client. | Protocol | |
| camel.component.aws-secrets-manager.region | The region in which a Secrets Manager client needs to work. When using this parameter, the configuration will expect the lowercase name of the region (for example, ap-east-1) You’ll need to use the name Region.EU_WEST_1.id(). | String | |
| camel.component.aws-secrets-manager.secret-key | Amazon AWS Secret Key. | String | |
| camel.component.aws-secrets-manager.secrets-manager-client | To use an existing configured AWS Secrets Manager client. The option is a software.amazon.awssdk.services.secretsmanager.SecretsManagerClient type. | SecretsManagerClient | |
| camel.component.aws-secrets-manager.session-token | Amazon AWS Session Token used when the user needs to assume an IAM role. | String | |
| camel.component.aws-secrets-manager.trust-all-certificates | If we want to trust all certificates in case of overriding the endpoint. | false | Boolean |
| camel.component.aws-secrets-manager.uri-endpoint-override | Set the overriding uri endpoint. This option needs to be used in combination with overrideEndpoint option. | String | |
| camel.component.aws-secrets-manager.use-default-credentials-provider | Set whether the Translate client should expect to load credentials through a default credentials provider or to expect static credentials to be passed in. | false | Boolean |
| camel.component.aws-secrets-manager.use-profile-credentials-provider | Set whether the Secrets Manager client should expect to load credentials through a profile credentials provider. | false | Boolean |
| camel.component.aws-secrets-manager.use-session-credentials | Set whether the Secrets Manager client should expect to use Session Credentials. This is useful in a situation in which the user needs to assume an IAM role for doing operations in Secrets Manager. | false | Boolean |
Chapter 13. Azure Key Vault 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The azure-key-vault component that integrates Azure Key Vault.
Prerequisites
You must have a valid Windows Azure Key Vault account. More information is available at Azure Documentation Portal.
13.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using camel-azure-key-vault with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-key-vault-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-azure-key-vault-starter</artifactId>
</dependency>
13.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
azure-key-vault://vaultName[?options]
azure-key-vault://vaultName[?options]
13.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
13.3.1. 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.
13.3.2. 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.
13.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Key Vault component supports 2 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| 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 |
13.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Key Vault endpoint is configured using URI syntax:
azure-key-vault:vaultName
azure-key-vault:vaultName
With the following path and query parameters:
13.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| vaultName (producer) | Vault Name to be used. | String |
13.5.2. Query Parameters (7 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| credentialType (common) | Determines the credential strategy to adopt. Enum values:
| CLIENT_SECRET | CredentialType |
| operation (producer) | Operation to be performed. Enum values:
| KeyVaultOperation | |
| secretClient (producer) | Autowired Instance of Secret client. | SecretClient | |
| 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 |
| clientId (security) | Client Id to be used. | String | |
| clientSecret (security) | Client Secret to be used. | String | |
| tenantId (security) | Tenant Id to be used. | String |
13.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
13.6.1. Using Azure Key Vault Property Function 링크 복사링크가 클립보드에 복사되었습니다!
To use this function, you’ll need to provide credentials to Azure Key Vault Service as environment variables:
export $CAMEL_VAULT_AZURE_TENANT_ID=tenantId export $CAMEL_VAULT_AZURE_CLIENT_ID=clientId export $CAMEL_VAULT_AZURE_CLIENT_SECRET=clientSecret export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
export $CAMEL_VAULT_AZURE_TENANT_ID=tenantId
export $CAMEL_VAULT_AZURE_CLIENT_ID=clientId
export $CAMEL_VAULT_AZURE_CLIENT_SECRET=clientSecret
export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
You can also configure the credentials in the application.properties file such as:
camel.vault.azure.tenantId = accessKey camel.vault.azure.clientId = clientId camel.vault.azure.clientSecret = clientSecret camel.vault.azure.vaultName = vaultName
camel.vault.azure.tenantId = accessKey
camel.vault.azure.clientId = clientId
camel.vault.azure.clientSecret = clientSecret
camel.vault.azure.vaultName = vaultName
Or you can enable the usage of Azure Identity in the following way:
export $CAMEL_VAULT_AZURE_IDENTITY_ENABLED=true export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
export $CAMEL_VAULT_AZURE_IDENTITY_ENABLED=true
export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
You can also enable the usage of Azure Identity in the application.properties file such as:
camel.vault.azure.azureIdentityEnabled = true camel.vault.azure.vaultName = vaultName
camel.vault.azure.azureIdentityEnabled = true
camel.vault.azure.vaultName = vaultName
camel.vault.azure configuration only applies to the Azure Key Vault properties function (E.g when resolving properties). When using the operation option to create, get, list secrets etc., you should provide the usual options for connecting to Azure Services.
At this point, you’ll be able to reference a property in the following way:
Where route will be the name of the secret stored in the Azure Key Vault Service.
You could specify a default value in case the secret is not present on Azure Key Vault Service:
In this case, if the secret doesn’t exist, the property will fall back to "default" as value.
Also, you are able to get a particular field of the secret, if you have, for example, a secret named database of this form:
You’re able to do get single secret value in your route, like for example:
Or re-use the property as part of an endpoint.
You could specify a default value in case the particular field of secret is not present on Azure Key Vault:
In this case, if the secret doesn’t exist or the secret exists, but the username field is not part of the secret, the property will fall back to "admin" as value.
There is also the syntax to get a particular version of the secret for both the approach, with field/default value specified or only with secret:
This approach will return the RAW route secret with the version 'bf9b4f4b-8e63-43fd-a73c-3e2d3748b451'.
This approach will return the route secret value with version 'bf9b4f4b-8e63-43fd-a73c-3e2d3748b451' or default value in case the secret doesn’t exist or the version doesn’t exist.
This approach will return the username field of the database secret with version 'bf9b4f4b-8e63-43fd-a73c-3e2d3748b451' or admin in case the secret doesn’t exist or the version doesn’t exist.
For the moment we are not considering the rotation function if any are applied, but it is in the work to be done.
The only requirement is adding the camel-azure-key-vault jar to your Camel application.
13.6.2. Automatic Camel context reloading on Secret Refresh 링크 복사링크가 클립보드에 복사되었습니다!
Being able to reload Camel context on a Secret Refresh could be done by specifying the usual credentials (the same used for Azure Key Vault Property Function).
With Environment variables:
export $CAMEL_VAULT_AZURE_TENANT_ID=tenantId export $CAMEL_VAULT_AZURE_CLIENT_ID=clientId export $CAMEL_VAULT_AZURE_CLIENT_SECRET=clientSecret export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
export $CAMEL_VAULT_AZURE_TENANT_ID=tenantId
export $CAMEL_VAULT_AZURE_CLIENT_ID=clientId
export $CAMEL_VAULT_AZURE_CLIENT_SECRET=clientSecret
export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
or as plain Camel main properties:
camel.vault.azure.tenantId = accessKey camel.vault.azure.clientId = clientId camel.vault.azure.clientSecret = clientSecret camel.vault.azure.vaultName = vaultName
camel.vault.azure.tenantId = accessKey
camel.vault.azure.clientId = clientId
camel.vault.azure.clientSecret = clientSecret
camel.vault.azure.vaultName = vaultName
If you want to use Azure Identity with environment variables, you can do in the following way:
export $CAMEL_VAULT_AZURE_IDENTITY_ENABLED=true export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
export $CAMEL_VAULT_AZURE_IDENTITY_ENABLED=true
export $CAMEL_VAULT_AZURE_VAULT_NAME=vaultName
You can also enable the usage of Azure Identity in the application.properties file such as:
camel.vault.azure.azureIdentityEnabled = true camel.vault.azure.vaultName = vaultName
camel.vault.azure.azureIdentityEnabled = true
camel.vault.azure.vaultName = vaultName
To enable the automatic refresh, you’ll need additional properties to set:
where camel.vault.azure.refreshEnabled will enable the automatic context reload, camel.vault.azure.refreshPeriod is the interval of time between two different checks for update events and camel.vault.azure.secrets is a regex representing the secrets we want to track for updates.
where camel.vault.azure.eventhubConnectionString is the eventhub connection string to get notification from, camel.vault.azure.blobAccountName, camel.vault.azure.blobContainerName and camel.vault.azure.blobAccessKey are the Azure Storage Blob parameters for the checkpoint store needed by Azure Eventhub.
Note that camel.vault.azure.secrets is not mandatory: if not specified the task responsible for checking updates events will take into accounts or the properties with an azure: prefix.
The only requirement is adding the camel-azure-key-vault jar to your Camel application.
First of all we need to create an application
az ad app create --display-name test-app-key-vault
az ad app create --display-name test-app-key-vault
Then we need to obtain credentials
az ad app credential reset --id <appId> --append --display-name 'Description: Key Vault app client' --end-date '2024-12-31'
az ad app credential reset --id <appId> --append --display-name 'Description: Key Vault app client' --end-date '2024-12-31'
This will return a result like this
{
"appId": "appId",
"password": "pwd",
"tenant": "tenantId"
}
{
"appId": "appId",
"password": "pwd",
"tenant": "tenantId"
}
You should take note of the password and use it as clientSecret parameter, together with the clientId and tenantId.
Now create the key vault
az keyvault create --name <vaultName> --resource-group <resourceGroup>
az keyvault create --name <vaultName> --resource-group <resourceGroup>
Create a service principal associated with the application Id
az ad sp create --id <appId>
az ad sp create --id <appId>
At this point we need to add a role to the application with role assignment
az role assignment create --assignee <appId> --role "Key Vault Administrator" --scope /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.KeyVault/vaults/<vaultName>
az role assignment create --assignee <appId> --role "Key Vault Administrator" --scope /subscriptions/<subscriptionId>/resourceGroups/<resourceGroup>/providers/Microsoft.KeyVault/vaults/<vaultName>
Last step is to create policy on what can be or cannot be done with the application. In this case we just want to read the secret value. So This should be enough.
az keyvault set-policy --name <vaultName> --spn <appId> --secret-permissions get
az keyvault set-policy --name <vaultName> --spn <appId> --secret-permissions get
You can create a secret through Azure CLI with the following command:
az keyvault secret set --name <secret_name> --vault-name <vaultName> -f <json-secret>
az keyvault secret set --name <secret_name> --vault-name <vaultName> -f <json-secret>
Now we need to setup the Eventhub/EventGrid notification for being informed about secrets updates.
First of all we’ll need a Blob account and Blob container, to track Eventhub consuming activities.
az storage account create --name <blobAccountName> --resource-group <resourceGroup>
az storage account create --name <blobAccountName> --resource-group <resourceGroup>
Then create a container
az storage container create --account-name <blobAccountName> --name <blobContainerName>
az storage container create --account-name <blobAccountName> --name <blobContainerName>
Then recover the access key for this purpose
az storage account keys list -g <resourceGroup> -n <blobAccountName>
az storage account keys list -g <resourceGroup> -n <blobAccountName>
Take note of the blob Account name, blob Container name and Blob Access Key to be used for setting up the vault.
Let’s now create the Eventhub side
Create the namespace first
az eventhubs namespace create --resource-group <resourceGroup> --name <eventhub-namespace> --location westus --sku Standard --enable-auto-inflate --maximum-throughput-units 20
az eventhubs namespace create --resource-group <resourceGroup> --name <eventhub-namespace> --location westus --sku Standard --enable-auto-inflate --maximum-throughput-units 20
Now create the resource
az eventhubs eventhub create --resource-group <resourceGroup> --namespace-name <eventhub-namespace> --name <eventhub-name> --cleanup-policy Delete --partition-count 15
az eventhubs eventhub create --resource-group <resourceGroup> --namespace-name <eventhub-namespace> --name <eventhub-name> --cleanup-policy Delete --partition-count 15
In the Azure portal create a shared policy for the just created eventhub resource with "MANAGE" permissions and copy the connection string.
You now have all the required parameters to set up the vault.
13.7. Message Headers 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Key Vault component supports 2 message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| CamelAzureKeyVaultProducerOperation (producer) Constant: OPERATION | Overrides the desired operation to be used in the producer. | KeyVaultOperationDefinition | |
| CamelAzureKeyVaultSecretName (producer) Constant: SECRET_NAME | The secret name to be used in Key Vault. | String |
13.7.1. Azure Key Vault Producer operations 링크 복사링크가 클립보드에 복사되었습니다!
Azure Key Vault component provides the following operation on the producer side:
- createSecret
- getSecret
- deleteSecret
- purgeDeletedSecret
13.8. Examples 링크 복사링크가 클립보드에 복사되었습니다!
13.8.1. Producer Examples 링크 복사링크가 클립보드에 복사되었습니다!
- createSecret: this operation will create a secret in Azure Key Vault
from("direct:createSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.setBody(constant("Test"))
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})")
from("direct:createSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.setBody(constant("Test"))
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})")
- getSecret: this operation will get a secret from Azure Key Vault
from("direct:getSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=getSecret")
from("direct:getSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=getSecret")
- deleteSecret: this operation will delete a Secret from Azure Key Vault
from("direct:deleteSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=deleteSecret")
from("direct:deleteSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=deleteSecret")
- purgeDeletedSecret: this operation will purge a deleted Secret from Azure Key Vault
from("direct:purgeDeletedSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=purgeDeletedSecret")
from("direct:purgeDeletedSecret")
.setHeader(KeyVaultConstants.SECRET_NAME, "Test")
.to("azure-key-vault://test123?clientId=RAW({{clientId}})&clientSecret=RAW({{clientSecret}})&tenantId=RAW({{tenantId}})&operation=purgeDeletedSecret")
13.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 3 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.azure-key-vault.autowired-enabled | 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 |
| camel.component.azure-key-vault.enabled | Whether to enable auto configuration of the azure-key-vault component. This is enabled by default. | Boolean | |
| camel.component.azure-key-vault.lazy-start-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 |
Chapter 14. Azure ServiceBus 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 3.12
Both producer and consumer are supported
The azure-servicebus component that integrates Azure ServiceBus. Azure ServiceBus is a fully managed enterprise integration message broker. Service Bus can decouple applications and services. Service Bus offers a reliable and secure platform for asynchronous transfer of data and state. Data is transferred between different applications and services using messages.
Prerequisites
You must have a valid Windows Azure Storage account. More information is available at Azure Documentation Portal.
14.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using azure-servicebus with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-servicebus-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-azure-servicebus-starter</artifactId>
</dependency>
14.2. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
14.2.1. 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.
14.2.2. 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.
14.3. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure ServiceBus component supports 25 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| amqpRetryOptions (common) | Sets the retry options for Service Bus clients. If not specified, the default retry options are used. | AmqpRetryOptions | |
| amqpTransportType (common) | Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is AmqpTransportType#AMQP. Enum values:
| AMQP | AmqpTransportType |
| clientOptions (common) | Sets the ClientOptions to be sent from the client built from this builder, enabling customization of certain properties, as well as support the addition of custom header information. Refer to the ClientOptions documentation for more information. | ClientOptions | |
| configuration (common) | The component configurations. | ServiceBusConfiguration | |
| proxyOptions (common) | Sets the proxy configuration to use for ServiceBusSenderAsyncClient. When a proxy is configured, AmqpTransportType#AMQP_WEB_SOCKETS must be used for the transport type. | ProxyOptions | |
| serviceBusType (common) | Required The service bus type of connection to execute. Queue is for typical queue option and topic for subscription based model. Enum values:
| queue | ServiceBusType |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| consumerOperation (consumer) | Sets the desired operation to be used in the consumer. Enum values:
| receiveMessages | ServiceBusConsumerOperationDefinition |
| disableAutoComplete (consumer) | Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is \\{link ServiceBusReceiverAsyncClient#complete(ServiceBusReceivedMessage) completed}. If an error happens when the message is processed, it is \\{link ServiceBusReceiverAsyncClient#abandon(ServiceBusReceivedMessage) abandoned}. | false | boolean |
| maxAutoLockRenewDuration (consumer) | Sets the amount of time to continue auto-renewing the lock. Setting Duration#ZERO or null disables auto-renewal. For \\{link ServiceBusReceiveMode#RECEIVE_AND_DELETE RECEIVE_AND_DELETE} mode, auto-renewal is disabled. | 5m | Duration |
| peekNumMaxMessages (consumer) | Set the max number of messages to be peeked during the peek operation. | Integer | |
| prefetchCount (consumer) | Sets the prefetch count of the receiver. For both \\{link ServiceBusReceiveMode#PEEK_LOCK PEEK_LOCK} and \\{link ServiceBusReceiveMode#RECEIVE_AND_DELETE RECEIVE_AND_DELETE} modes the default value is 1. Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and before the application asks for one using ServiceBusReceiverAsyncClient#receiveMessages(). Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. | int | |
| receiverAsyncClient (consumer) | Autowired Sets the receiverAsyncClient in order to consume messages by the consumer. | ServiceBusReceiverAsyncClient | |
| serviceBusReceiveMode (consumer) | Sets the receive mode for the receiver. Enum values:
| PEEK_LOCK | ServiceBusReceiveMode |
| subQueue (consumer) | Sets the type of the SubQueue to connect to. Enum values:
| SubQueue | |
| subscriptionName (consumer) | Sets the name of the subscription in the topic to listen to. topicOrQueueName and serviceBusType=topic must also be set. This property is required if serviceBusType=topic and the consumer is in use. | String | |
| 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 |
| producerOperation (producer) | Sets the desired operation to be used in the producer. Enum values:
| sendMessages | ServiceBusProducerOperationDefinition |
| scheduledEnqueueTime (producer) | Sets OffsetDateTime at which the message should appear in the Service Bus queue or topic. | OffsetDateTime | |
| senderAsyncClient (producer) | Autowired Sets SenderAsyncClient to be used in the producer. | ServiceBusSenderAsyncClient | |
| serviceBusTransactionContext (producer) | Represents transaction in service. This object just contains transaction id. | ServiceBusTransactionContext | |
| 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 |
| connectionString (security) | Sets the connection string for a Service Bus namespace or a specific Service Bus resource. | String | |
| fullyQualifiedNamespace (security) | Fully Qualified Namespace of the service bus. | String | |
| tokenCredential (security) | A TokenCredential for Azure AD authentication, implemented in com.azure.identity. | TokenCredential |
14.4. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure ServiceBus endpoint is configured using URI syntax:
azure-servicebus:topicOrQueueName
azure-servicebus:topicOrQueueName
with the following path and query parameters:
14.4.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| topicOrQueueName (common) | Selected topic name or the queue name, that is depending on serviceBusType config. For example if serviceBusType=queue, then this will be the queue name and if serviceBusType=topic, this will be the topic name. | String |
14.4.2. Query Parameters (25 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| amqpRetryOptions (common) | Sets the retry options for Service Bus clients. If not specified, the default retry options are used. | AmqpRetryOptions | |
| amqpTransportType (common) | Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is AmqpTransportType#AMQP. Enum values:
| AMQP | AmqpTransportType |
| clientOptions (common) | Sets the ClientOptions to be sent from the client built from this builder, enabling customization of certain properties, as well as support the addition of custom header information. Refer to the ClientOptions documentation for more information. | ClientOptions | |
| proxyOptions (common) | Sets the proxy configuration to use for ServiceBusSenderAsyncClient. When a proxy is configured, AmqpTransportType#AMQP_WEB_SOCKETS must be used for the transport type. | ProxyOptions | |
| serviceBusType (common) | Required The service bus type of connection to execute. Queue is for typical queue option and topic for subscription based model. Enum values:
| queue | ServiceBusType |
| consumerOperation (consumer) | Sets the desired operation to be used in the consumer. Enum values:
| receiveMessages | ServiceBusConsumerOperationDefinition |
| disableAutoComplete (consumer) | Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is \\{link ServiceBusReceiverAsyncClient#complete(ServiceBusReceivedMessage) completed}. If an error happens when the message is processed, it is \\{link ServiceBusReceiverAsyncClient#abandon(ServiceBusReceivedMessage) abandoned}. | false | boolean |
| maxAutoLockRenewDuration (consumer) | Sets the amount of time to continue auto-renewing the lock. Setting Duration#ZERO or null disables auto-renewal. For \\{link ServiceBusReceiveMode#RECEIVE_AND_DELETE RECEIVE_AND_DELETE} mode, auto-renewal is disabled. | 5m | Duration |
| peekNumMaxMessages (consumer) | Set the max number of messages to be peeked during the peek operation. | Integer | |
| prefetchCount (consumer) | Sets the prefetch count of the receiver. For both \\{link ServiceBusReceiveMode#PEEK_LOCK PEEK_LOCK} and \\{link ServiceBusReceiveMode#RECEIVE_AND_DELETE RECEIVE_AND_DELETE} modes the default value is 1. Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and before the application asks for one using ServiceBusReceiverAsyncClient#receiveMessages(). Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. | int | |
| receiverAsyncClient (consumer) | Autowired Sets the receiverAsyncClient in order to consume messages by the consumer. | ServiceBusReceiverAsyncClient | |
| serviceBusReceiveMode (consumer) | Sets the receive mode for the receiver. Enum values:
| PEEK_LOCK | ServiceBusReceiveMode |
| subQueue (consumer) | Sets the type of the SubQueue to connect to. Enum values:
| SubQueue | |
| subscriptionName (consumer) | Sets the name of the subscription in the topic to listen to. topicOrQueueName and serviceBusType=topic must also be set. This property is required if serviceBusType=topic and the consumer is in use. | String | |
| bridgeErrorHandler (consumer (advanced)) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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:
| ExchangePattern | |
| producerOperation (producer) | Sets the desired operation to be used in the producer. Enum values:
| sendMessages | ServiceBusProducerOperationDefinition |
| scheduledEnqueueTime (producer) | Sets OffsetDateTime at which the message should appear in the Service Bus queue or topic. | OffsetDateTime | |
| senderAsyncClient (producer) | Autowired Sets SenderAsyncClient to be used in the producer. | ServiceBusSenderAsyncClient | |
| serviceBusTransactionContext (producer) | Represents transaction in service. This object just contains transaction id. | ServiceBusTransactionContext | |
| 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 |
| connectionString (security) | Sets the connection string for a Service Bus namespace or a specific Service Bus resource. | String | |
| fullyQualifiedNamespace (security) | Fully Qualified Namespace of the service bus. | String | |
| tokenCredential (security) | A TokenCredential for Azure AD authentication, implemented in com.azure.identity. | TokenCredential |
14.5. Async Consumer and Producer 링크 복사링크가 클립보드에 복사되었습니다!
This component implements the async Consumer and producer. This allows camel route to consume and produce events asynchronously without blocking any threads.
14.6. Message Headers 링크 복사링크가 클립보드에 복사되었습니다!
The Azure ServiceBus component supports 25 message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| CamelAzureServiceBusApplicationProperties (common) Constant: APPLICATION_PROPERTIES | The application properties (also known as custom properties) on messages sent and received by the producer and consumer, respectively. | Map | |
| CamelAzureServiceBusContentType (consumer) Constant: CONTENT_TYPE | Gets the content type of the message. | String | |
| CamelAzureServiceBusCorrelationId (consumer) Constant: CORRELATION_ID | Gets a correlation identifier. | String | |
| CamelAzureServiceBusDeadLetterErrorDescription (consumer) Constant: DEAD_LETTER_ERROR_DESCRIPTION | Gets the description for a message that has been dead-lettered. | String | |
| CamelAzureServiceBusDeadLetterReason (consumer) Constant: DEAD_LETTER_REASON | Gets the reason a message was dead-lettered. | String | |
| CamelAzureServiceBusDeadLetterSource (consumer) Constant: DEAD_LETTER_SOURCE | Gets the name of the queue or subscription that this message was enqueued on, before it was dead-lettered. | String | |
| CamelAzureServiceBusDeliveryCount (consumer) Constant: DELIVERY_COUNT | Gets the number of the times this message was delivered to clients. | long | |
| CamelAzureServiceBusEnqueuedSequenceNumber (consumer) Constant: ENQUEUED_SEQUENCE_NUMBER | Gets the enqueued sequence number assigned to a message by Service Bus. | long | |
| CamelAzureServiceBusEnqueuedTime (consumer) Constant: ENQUEUED_TIME | Gets the datetime at which this message was enqueued in Azure Service Bus. | OffsetDateTime | |
| CamelAzureServiceBusExpiresAt (consumer) Constant: EXPIRES_AT | Gets the datetime at which this message will expire. | OffsetDateTime | |
| CamelAzureServiceBusLockToken (consumer) Constant: LOCK_TOKEN | Gets the lock token for the current message. | String | |
| CamelAzureServiceBusLockedUntil (consumer) Constant: LOCKED_UNTIL | Gets the datetime at which the lock of this message expires. | OffsetDateTime | |
| CamelAzureServiceBusMessageId (consumer) Constant: MESSAGE_ID | Gets the identifier for the message. | String | |
| CamelAzureServiceBusPartitionKey (consumer) Constant: PARTITION_KEY | Gets the partition key for sending a message to a partitioned entity. | String | |
| CamelAzureServiceBusRawAmqpMessage (consumer) Constant: RAW_AMQP_MESSAGE | The representation of message as defined by AMQP protocol. | AmqpAnnotatedMessage | |
| CamelAzureServiceBusReplyTo (consumer) Constant: REPLY_TO | Gets the address of an entity to send replies to. | String | |
| CamelAzureServiceBusReplyToSessionId (consumer) Constant: REPLY_TO_SESSION_ID | Gets or sets a session identifier augmenting the ReplyTo address. | String | |
| CamelAzureServiceBusSequenceNumber (consumer) Constant: SEQUENCE_NUMBER | Gets the unique number assigned to a message by Service Bus. | long | |
| CamelAzureServiceBusSessionId (consumer) Constant: SESSION_ID | Gets the session id of the message. | String | |
| CamelAzureServiceBusSubject (consumer) Constant: SUBJECT | Gets the subject for the message. | String | |
| CamelAzureServiceBusTimeToLive (consumer) Constant: TIME_TO_LIVE | Gets the duration before this message expires. | Duration | |
| CamelAzureServiceBusTo (consumer) Constant: TO | Gets the to address. | String | |
| CamelAzureServiceBusScheduledEnqueueTime (common) Constant: SCHEDULED_ENQUEUE_TIME | (producer)Overrides the OffsetDateTime at which the message should appear in the Service Bus queue or topic. (consumer) Gets the scheduled enqueue time of this message. | OffsetDateTime | |
| CamelAzureServiceBusServiceBusTransactionContext (producer) Constant: SERVICE_BUS_TRANSACTION_CONTEXT | Overrides the transaction in service. This object just contains transaction id. | ServiceBusTransactionContext | |
| CamelAzureServiceBusProducerOperation (producer) Constant: PRODUCER_OPERATION | Overrides the desired operation to be used in the producer. Enum values:
| ServiceBusProducerOperationDefinition |
14.6.1. Message Body 링크 복사링크가 클립보드에 복사되었습니다!
In the producer, this component accepts message body of String type or List<String> to send batch messages.
In the consumer, the returned message body will be of type `String.
14.6.2. Azure ServiceBus Producer operations 링크 복사링크가 클립보드에 복사되었습니다!
| Operation | Description |
|---|---|
|
| Sends a set of messages to a Service Bus queue or topic using a batched approach. |
|
| Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is enqueued and made available to receivers only at the scheduled enqueue time. |
14.6.3. Azure ServiceBus Consumer operations 링크 복사링크가 클립보드에 복사되었습니다!
| Operation | Description |
|---|---|
|
| Receives an <b>infinite</b> stream of messages from the Service Bus entity. |
|
| Reads the next batch of active messages without changing the state of the receiver or the message source. |
14.6.3.1. Examples 링크 복사링크가 클립보드에 복사되었습니다!
-
sendMessages
-
scheduleMessages
-
receiveMessages
from("azure-servicebus:test//?connectionString=test")
.log("${body}")
.to("mock:result");
from("azure-servicebus:test//?connectionString=test")
.log("${body}")
.to("mock:result");
-
peekMessages
from("azure-servicebus:test//?connectionString=test&consumerOperation=peekMessages&peekNumMaxMessages=3")
.log("${body}")
.to("mock:result");
from("azure-servicebus:test//?connectionString=test&consumerOperation=peekMessages&peekNumMaxMessages=3")
.log("${body}")
.to("mock:result");
14.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 26 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.azure-servicebus.amqp-retry-options | Sets the retry options for Service Bus clients. If not specified, the default retry options are used. The option is a com.azure.core.amqp.AmqpRetryOptions type. | AmqpRetryOptions | |
| camel.component.azure-servicebus.amqp-transport-type | Sets the transport type by which all the communication with Azure Service Bus occurs. Default value is AmqpTransportType#AMQP. | AmqpTransportType | |
| camel.component.azure-servicebus.autowired-enabled | 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 |
| camel.component.azure-servicebus.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.azure-servicebus.client-options | Sets the ClientOptions to be sent from the client built from this builder, enabling customization of certain properties, as well as support the addition of custom header information. Refer to the ClientOptions documentation for more information. The option is a com.azure.core.util.ClientOptions type. | ClientOptions | |
| camel.component.azure-servicebus.configuration | The component configurations. The option is a org.apache.camel.component.azure.servicebus.ServiceBusConfiguration type. | ServiceBusConfiguration | |
| camel.component.azure-servicebus.connection-string | Sets the connection string for a Service Bus namespace or a specific Service Bus resource. | String | |
| camel.component.azure-servicebus.consumer-operation | Sets the desired operation to be used in the consumer. | ServiceBusConsumerOperationDefinition | |
| camel.component.azure-servicebus.disable-auto-complete | Disables auto-complete and auto-abandon of received messages. By default, a successfully processed message is \\{link ServiceBusReceiverAsyncClient#complete(ServiceBusReceivedMessage) completed}. If an error happens when the message is processed, it is \\{link ServiceBusReceiverAsyncClient#abandon(ServiceBusReceivedMessage) abandoned}. | false | Boolean |
| camel.component.azure-servicebus.enabled | Whether to enable auto configuration of the azure-servicebus component. This is enabled by default. | Boolean | |
| camel.component.azure-servicebus.fully-qualified-namespace | Fully Qualified Namespace of the service bus. | String | |
| camel.component.azure-servicebus.lazy-start-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 |
| camel.component.azure-servicebus.max-auto-lock-renew-duration | Sets the amount of time to continue auto-renewing the lock. Setting Duration#ZERO or null disables auto-renewal. For \\{link ServiceBusReceiveMode#RECEIVE_AND_DELETE RECEIVE_AND_DELETE} mode, auto-renewal is disabled. The option is a java.time.Duration type. | Duration | |
| camel.component.azure-servicebus.peek-num-max-messages | Set the max number of messages to be peeked during the peek operation. | Integer | |
| camel.component.azure-servicebus.prefetch-count | Sets the prefetch count of the receiver. For both \\{link ServiceBusReceiveMode#PEEK_LOCK PEEK_LOCK} and \\{link ServiceBusReceiveMode#RECEIVE_AND_DELETE RECEIVE_AND_DELETE} modes the default value is 1. Prefetch speeds up the message flow by aiming to have a message readily available for local retrieval when and before the application asks for one using ServiceBusReceiverAsyncClient#receiveMessages(). Setting a non-zero value will prefetch that number of messages. Setting the value to zero turns prefetch off. | Integer | |
| camel.component.azure-servicebus.producer-operation | Sets the desired operation to be used in the producer. | ServiceBusProducerOperationDefinition | |
| camel.component.azure-servicebus.proxy-options | Sets the proxy configuration to use for ServiceBusSenderAsyncClient. When a proxy is configured, AmqpTransportType#AMQP_WEB_SOCKETS must be used for the transport type. The option is a com.azure.core.amqp.ProxyOptions type. | ProxyOptions | |
| camel.component.azure-servicebus.receiver-async-client | Sets the receiverAsyncClient in order to consume messages by the consumer. The option is a com.azure.messaging.servicebus.ServiceBusReceiverAsyncClient type. | ServiceBusReceiverAsyncClient | |
| camel.component.azure-servicebus.scheduled-enqueue-time | Sets OffsetDateTime at which the message should appear in the Service Bus queue or topic. The option is a java.time.OffsetDateTime type. | OffsetDateTime | |
| camel.component.azure-servicebus.sender-async-client | Sets SenderAsyncClient to be used in the producer. The option is a com.azure.messaging.servicebus.ServiceBusSenderAsyncClient type. | ServiceBusSenderAsyncClient | |
| camel.component.azure-servicebus.service-bus-receive-mode | Sets the receive mode for the receiver. | ServiceBusReceiveMode | |
| camel.component.azure-servicebus.service-bus-transaction-context | Represents transaction in service. This object just contains transaction id. The option is a com.azure.messaging.servicebus.ServiceBusTransactionContext type. | ServiceBusTransactionContext | |
| camel.component.azure-servicebus.service-bus-type | The service bus type of connection to execute. Queue is for typical queue option and topic for subscription based model. | ServiceBusType | |
| camel.component.azure-servicebus.sub-queue | Sets the type of the SubQueue to connect to. | SubQueue | |
| camel.component.azure-servicebus.subscription-name | Sets the name of the subscription in the topic to listen to. topicOrQueueName and serviceBusType=topic must also be set. This property is required if serviceBusType=topic and the consumer is in use. | String | |
| camel.component.azure-servicebus.token-credential | A TokenCredential for Azure AD authentication, implemented in com.azure.identity. The option is a com.azure.core.credential.TokenCredential type. | TokenCredential |
Chapter 15. Azure Storage Blob Service 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The Azure Storage Blob component is used for storing and retrieving blobs from Azure Storage Blob Service using Azure APIs v12. However in case of versions above v12, we will see if this component can adopt these changes depending on how much breaking changes can result.
Prerequisites
You must have a valid Windows Azure Storage account. More information is available at Azure Documentation Portal .
15.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using azure-storage-blob with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-storage-blob-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-azure-storage-blob-starter</artifactId>
</dependency>
15.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
azure-storage-blob://accountName[/containerName][?options]
azure-storage-blob://accountName[/containerName][?options]
In case of consumer, accountName, containerName are required. In case of producer, it depends on the operation that being requested, for example if operation is on a container level, for example, createContainer, accountName and containerName are only required, but in case of operation being requested in blob level, for example, getBlob, accountName, containerName and blobName are required.
The blob will be created if it does not already exist. You can append query options to the URI in the following format,
?options=value&option2=value&…
15.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
15.3.1. 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.
15.3.2. 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.
15.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Storage Blob Service component supports 35 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| blobName (common) | The blob name, to consume specific blob from a container. However on producer, is only required for the operations on the blob level. | String | |
| blobOffset (common) | Set the blob offset for the upload or download operations, default is 0. | 0 | long |
| blobType (common) | The blob type in order to initiate the appropriate settings for each blob type. Enum values:
| blockblob | BlobType |
| closeStreamAfterRead (common) | Close the stream after read or keep it open, default is true. | true | boolean |
| configuration (common) | The component configurations. | BlobConfiguration | |
| credentials (common) | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information. | StorageSharedKeyCredential | |
| credentialType (common) | Determines the credential strategy to adopt. Enum values:
| AZURE_IDENTITY | CredentialType |
| dataCount (common) | How many bytes to include in the range. Must be greater than or equal to 0 if specified. | Long | |
| fileDir (common) | The file directory where the downloaded blobs will be saved to, this can be used in both, producer and consumer. | String | |
| maxResultsPerPage (common) | Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. | Integer | |
| maxRetryRequests (common) | Specifies the maximum number of additional HTTP Get requests that will be made while reading the data from a response body. | 0 | int |
| prefix (common) | Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. | String | |
| regex (common) | Filters the results to return only blobs whose names match the specified regular expression. May be null to return all if both prefix and regex are set, regex takes the priority and prefix is ignored. | String | |
| sasToken (common) | Set a SAS Token in case of usage of Shared Access Signature | String | |
| serviceClient (common) | Autowired Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through BlobServiceClient#getBlobContainerClient(String), and operations on a blob are available on BlobClient through BlobContainerClient#getBlobClient(String). | BlobServiceClient | |
| timeout (common) | An optional timeout value beyond which a RuntimeException will be raised. | Duration | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| blobSequenceNumber (producer) | A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 263 - 1.The default value is 0. | 0 | Long |
| blockListType (producer) | Specifies which type of blocks to return. Enum values:
| COMMITTED | BlockListType |
| changeFeedContext (producer) | When using getChangeFeed producer operation, this gives additional context that is passed through the Http pipeline during the service call. | Context | |
| changeFeedEndTime (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. | OffsetDateTime | |
| changeFeedStartTime (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. | OffsetDateTime | |
| closeStreamAfterWrite (producer) | Close the stream after write or keep it open, default is true. | true | boolean |
| commitBlockListLater (producer) | When is set to true, the staged blocks will not be committed directly. | true | boolean |
| createAppendBlob (producer) | When is set to true, the append blocks will be created when committing append blocks. | true | boolean |
| createPageBlob (producer) | When is set to true, the page blob will be created when uploading page blob. | true | boolean |
| downloadLinkExpiration (producer) | Override the default expiration (millis) of URL download link. | Long | |
| 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 |
| operation (producer) | The blob operation that can be used with this component on the producer. Enum values:
| listBlobContainers | BlobOperationsDefinition |
| pageBlobSize (producer) | Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. | 512 | Long |
| 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 |
| healthCheckConsumerEnabled (health) | Used for enabling or disabling all consumer based health checks from this component. | true | boolean |
| healthCheckProducerEnabled (health) | Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | boolean |
| accessKey (security) | Access key for the associated azure account name to be used for authentication with azure blob services. | String | |
| sourceBlobAccessKey (security) | Source Blob Access Key: for copyblob operation, sadly, we need to have an accessKey for the source blob we want to copy Passing an accessKey as header, it’s unsafe so we could set as key. | String |
15.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Storage Blob Service endpoint is configured using URI syntax:
azure-storage-blob:accountName/containerName
azure-storage-blob:accountName/containerName
with the following path and query parameters:
15.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| accountName (common) | Azure account name to be used for authentication with azure blob services. | String | |
| containerName (common) | The blob container name. | String |
15.5.2. Query Parameters (50 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| blobName (common) | The blob name, to consume specific blob from a container. However on producer, is only required for the operations on the blob level. | String | |
| blobOffset (common) | Set the blob offset for the upload or download operations, default is 0. | 0 | long |
| blobServiceClient (common) | Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through getBlobContainerClient(String), and operations on a blob are available on BlobClient through getBlobContainerClient(String).getBlobClient(String). | BlobServiceClient | |
| blobType (common) | The blob type in order to initiate the appropriate settings for each blob type. Enum values:
| blockblob | BlobType |
| closeStreamAfterRead (common) | Close the stream after read or keep it open, default is true. | true | boolean |
| credentials (common) | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information. | StorageSharedKeyCredential | |
| credentialType (common) | Determines the credential strategy to adopt. Enum values:
| AZURE_IDENTITY | CredentialType |
| dataCount (common) | How many bytes to include in the range. Must be greater than or equal to 0 if specified. | Long | |
| fileDir (common) | The file directory where the downloaded blobs will be saved to, this can be used in both, producer and consumer. | String | |
| maxResultsPerPage (common) | Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. | Integer | |
| maxRetryRequests (common) | Specifies the maximum number of additional HTTP Get requests that will be made while reading the data from a response body. | 0 | int |
| prefix (common) | Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. | String | |
| regex (common) | Filters the results to return only blobs whose names match the specified regular expression. May be null to return all if both prefix and regex are set, regex takes the priority and prefix is ignored. | String | |
| sasToken (common) | Set a SAS Token in case of usage of Shared Access Signature. | String | |
| serviceClient (common) | Autowired Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through BlobServiceClient#getBlobContainerClient(String), and operations on a blob are available on BlobClient through BlobContainerClient#getBlobClient(String). | BlobServiceClient | |
| timeout (common) | An optional timeout value beyond which a RuntimeException will be raised. | Duration | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| sendEmptyMessageWhenIdle (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | 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:
| ExchangePattern | |
| pollStrategy (consumer (advanced)) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | |
| blobSequenceNumber (producer) | A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 263 - 1.The default value is 0. | 0 | Long |
| blockListType (producer) | Specifies which type of blocks to return. Enum values:
| COMMITTED | BlockListType |
| changeFeedContext (producer) | When using getChangeFeed producer operation, this gives additional context that is passed through the Http pipeline during the service call. | Context | |
| changeFeedEndTime (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. | OffsetDateTime | |
| changeFeedStartTime (producer) | When using getChangeFeed producer operation, this filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. | OffsetDateTime | |
| closeStreamAfterWrite (producer) | Close the stream after write or keep it open, default is true. | true | boolean |
| commitBlockListLater (producer) | When is set to true, the staged blocks will not be committed directly. | true | boolean |
| createAppendBlob (producer) | When is set to true, the append blocks will be created when committing append blocks. | true | boolean |
| createPageBlob (producer) | When is set to true, the page blob will be created when uploading page blob. | true | boolean |
| downloadLinkExpiration (producer) | Override the default expiration (millis) of URL download link. | Long | |
| 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 |
| operation (producer) | The blob operation that can be used with this component on the producer. Enum values:
| listBlobContainers | BlobOperationsDefinition |
| pageBlobSize (producer) | Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. | 512 | Long |
| backoffErrorThreshold (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | |
| backoffIdleThreshold (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | |
| backoffMultiplier (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | |
| delay (scheduler) | Milliseconds before the next poll. | 500 | long |
| greedy (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean |
| initialDelay (scheduler) | Milliseconds before the first poll starts. | 1000 | long |
| repeatCount (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long |
| runLoggingLevel (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel |
| scheduledExecutorService (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | |
| scheduler (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object |
| schedulerProperties (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | Map | |
| startScheduler (scheduler) | Whether the scheduler should be auto started. | true | boolean |
| timeUnit (scheduler) | Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit |
| useFixedDelay (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
| accessKey (security) | Access key for the associated azure account name to be used for authentication with azure blob services. | String | |
| sourceBlobAccessKey (security) | Source Blob Access Key: for copyblob operation, sadly, we need to have an accessKey for the source blob we want to copy Passing an accessKey as header, it’s unsafe so we could set as key. | String |
Required information options
To use this component, you have 3 options in order to provide the required Azure authentication information:
-
Provide a link: BlobServiceClient instance which can be injected into blobServiceClient. Note: No need to create a specific client, for Examples:
BlockBlobClient, theBlobServiceClientrepresents the upper level which can be used to retrieve lower level clients. -
Provide an Azure Identity, when specifying
credentialType=AZURE_IDENTITYand providing required environment variables. This enables service principal (for example, app registration) authentication with secret/certificate as well as username password. Note that this is the default authentication strategy. -
Provide a shared storage account key, when specifying
credentialType=SHARED_ACCOUNT_KEYand providingaccountNameandaccessKeyfor your Azure account, this is the simplest way to get started. TheaccessKeycan be generated through your Azure portal. -
Provide a shared storage account key, when specifying
credentialType=SHARED_KEY_CREDENTIALand providing a StorageSharedKeyCredential instance which can be injected into credentials option. -
Via Azure SAS, when specifying
credentialType=AZURE_SASand providing a SAS Token parameter through the sasToken parameter.
15.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
For example, in order to download a blob content from the block blob hello.txt located on the container1 in the camelazure storage account, use the following snippet:
from("azure-storage-blob://camelazure/container1?blobName=hello.txt&credentialType=SHARED_ACCOUNT_KEY&accessKey=RAW(yourAccessKey)").to("file://blobdirectory");
from("azure-storage-blob://camelazure/container1?blobName=hello.txt&credentialType=SHARED_ACCOUNT_KEY&accessKey=RAW(yourAccessKey)").to("file://blobdirectory");
15.6.1. Message headers 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Storage Blob Service component supports 63 message header(s), which is/are listed below:
| Header | Variable Name | Type | Operations | Description |
|---|---|---|---|---|
|
|
|
| All | An optional timeout value beyond which a {@link RuntimeException} will be raised. |
|
|
|
| Operations related to container and blob | Metadata to associate with the container or blob. |
|
|
|
|
|
Specifies how the data in this container is available to the public. Pass |
|
|
|
| Operations related to container and blob | This contains values which will restrict the successful operation of a variety of requests to the conditions present. These conditions are entirely optional. |
|
|
|
|
| The details for listing specific blobs |
|
|
|
|
| Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. |
|
|
|
|
| Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. |
|
|
|
|
| Defines options available to configure the behavior of a call to listBlobsFlatSegment on a {@link BlobContainerClient} object. |
|
|
|
|
| Additional parameters for a set of operations. |
|
|
|
|
| Defines values for AccessTier. |
|
|
|
| Most operations related to upload blob | An MD5 hash of the block content. This hash is used to verify the integrity of the block during transport. When this header is specified, the storage service compares the hash of the content that has arrived with this header value. Note that this MD5 hash is not stored with the blob. If the two hashes do not match, the operation will fail. |
|
|
|
| Operations related to page blob | A {@link PageRange} object. Given that pages must be aligned with 512-byte boundaries, the start offset must be a modulus of 512 and the end offset must be a modulus of 512 - 1. Examples of valid byte ranges are 0-511, 512-1023, etc. |
|
|
|
|
|
When is set to |
|
|
|
|
|
When is set to |
|
|
|
|
|
When is set to |
|
|
|
|
| Specifies which type of blocks to return. |
|
|
|
|
| Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. |
|
|
|
|
| A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 2^63 - 1.The default value is 0. |
|
|
|
|
| Specifies the behavior for deleting the snapshots on this blob. \{@code Include} will delete the base blob and all snapshots. \{@code Only} will delete only the snapshots. If a snapshot is being deleted, you must pass null. |
|
|
|
|
| A {@link ListBlobContainersOptions} which specifies what data should be returned by the service. |
|
|
|
|
| {@link ParallelTransferOptions} to use to download to file. Number of parallel transfers parameter is ignored. |
|
|
|
|
| The file directory where the downloaded blobs will be saved to. |
|
|
|
|
| Override the default expiration (millis) of URL download link. |
|
|
|
| Operations related to blob | Override/set the blob name on the exchange headers. |
|
|
|
| Operations related to container and blob | Override/set the container name on the exchange headers. |
|
|
|
| All | Specify the producer operation to execute, please see the doc on this page related to producer operation. |
|
|
|
|
| Filters the results to return only blobs whose names match the specified regular expression. May be null to return all. If both prefix and regex are set, regex takes the priority and prefix is ignored. |
|
|
|
|
| It filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. |
|
|
|
|
| It filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. |
|
|
|
|
| This gives additional context that is passed through the Http pipeline during the service call. |
|
|
|
|
| The source blob account name to be used as source account name in a copy blob operation |
|
|
|
|
| The source blob container name to be used as source container name in a copy blob operation |
15.6.2. Message headers set by either component producer or consumer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Variable Name | Type | Description |
|---|---|---|---|
|
|
|
| Access tier of the blob. |
|
|
|
| Datetime when the access tier of the blob last changed. |
|
|
|
| Archive status of the blob. |
|
|
|
| Creation time of the blob. |
|
|
|
| The current sequence number for a page blob. |
|
|
|
| The size of the blob. |
|
|
|
| The type of the blob. |
|
|
|
| Cache control specified for the blob. |
|
|
|
| Number of blocks committed to an append blob |
|
|
|
| Content disposition specified for the blob. |
|
|
|
| Content encoding specified for the blob. |
|
|
|
| Content language specified for the blob. |
|
|
|
| Content MD5 specified for the blob. |
|
|
|
| Content type specified for the blob. |
|
|
|
| Datetime when the last copy operation on the blob completed. |
|
|
|
| Snapshot identifier of the last incremental copy snapshot for the blob. |
|
|
|
| Identifier of the last copy operation performed on the blob. |
|
|
|
| Progress of the last copy operation performed on the blob. |
|
|
|
| Source of the last copy operation performed on the blob. |
|
|
|
| Status of the last copy operation performed on the blob. |
|
|
|
| Description of the last copy operation on the blob. |
|
|
|
| The E Tag of the blob |
|
|
|
| Flag indicating if the access tier of the blob was inferred from properties of the blob. |
|
|
|
| Flag indicating if the blob was incrementally copied. |
|
|
|
| Flag indicating if the blob’s content is encrypted on the server. |
|
|
|
| Datetime when the blob was last modified. |
|
|
|
| Type of lease on the blob. |
|
|
|
| State of the lease on the blob. |
|
|
|
| Status of the lease on the blob. |
|
|
|
| Additional metadata associated with the blob. |
|
|
|
| The offset at which the block was committed to the block blob. |
|
|
|
|
The downloaded filename from the operation |
|
|
|
|
The download link generated by |
|
|
|
| Returns non-parsed httpHeaders that can be used by the user. |
15.6.3. Advanced Azure Storage Blob configuration 링크 복사링크가 클립보드에 복사되었습니다!
If your Camel Application is running behind a firewall or if you need to have more control over the BlobServiceClient instance configuration, you can create your own instance:
Then refer to this instance in your Camel azure-storage-blob component configuration:
from("azure-storage-blob://cameldev/container1?blobName=myblob&serviceClient=#client")
.to("mock:result");
from("azure-storage-blob://cameldev/container1?blobName=myblob&serviceClient=#client")
.to("mock:result");
15.6.4. Automatic detection of BlobServiceClient client in registry 링크 복사링크가 클립보드에 복사되었습니다!
The component is capable of detecting the presence of an BlobServiceClient bean into the registry. If it’s the only instance of that type it will be used as client and you won’t have to define it as uri parameter, like the example above. This may be really useful for smarter configuration of the endpoint.
15.6.5. Azure Storage Blob Producer operations 링크 복사링크가 클립보드에 복사되었습니다!
Camel Azure Storage Blob component provides wide range of operations on the producer side:
Operations on the service level
For these operations, accountName is required.
| Operation | Description |
|---|---|
|
| Get the content of the blob. You can restrict the output of this operation to a blob range. |
|
| Returns transaction logs of all the changes that occur to the blobs and the blob metadata in your storage account. The change feed provides ordered, guaranteed, durable, immutable, read-only log of these changes. |
Operations on the container level
For these operations, accountName and containerName are required.
| Operation | Description |
|---|---|
|
| Creates a new container within a storage account. If a container with the same name already exists, the producer will ignore it. |
|
| Deletes the specified container in the storage account. If the container doesn’t exist the operation fails. |
|
| Returns a list of blobs in this container, with folder structures flattened. |
Operations on the blob level
For these operations, accountName, containerName and blobName are required.
| Operation | Blob Type | Description |
|---|---|---|
|
| Common | Get the content of the blob. You can restrict the output of this operation to a blob range. |
|
| Common | Delete a blob. |
|
| Common | Downloads the entire blob into a file specified by the path.The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} will be thrown. |
|
| Common | Generates the download link for the specified blob using shared access signatures (SAS). This by default only limit to 1hour of allowed access. However, you can override the default expiration duration through the headers. |
|
| BlockBlob | Creates a new block blob, or updates the content of an existing block blob. Updating an existing block blob overwrites any existing metadata on the blob. Partial updates are not supported with PutBlob; the content of the existing blob is overwritten with the new content. |
|
|
|
Uploads the specified block to the block blob’s "staging area" to be later committed by a call to commitBlobBlockList. However in case header |
|
|
|
Writes a blob by specifying the list of block IDs that are to make up the blob. In order to be written as part of a blob, a block must have been successfully written to the server in a prior |
|
|
| Returns the list of blocks that have been uploaded as part of a block blob using the specified block list filter. |
|
|
| Creates a 0-length append blob. Call commitAppendBlo`b operation to append data to an append blob. |
|
|
|
Commits a new block of data to the end of the existing append blob. In case of header |
|
|
|
Creates a page blob of the specified length. Call |
|
|
|
Writes one or more pages to the page blob. The write size must be a multiple of 512. In case of header |
|
|
| Resizes the page blob to the specified size (which must be a multiple of 512). |
|
|
| Frees the specified pages from the page blob. The size of the range must be a multiple of 512. |
|
|
| Returns the list of valid page ranges for a page blob or snapshot of a page blob. |
|
|
| Copy a blob from one container to another one, even from different accounts. |
Refer to the example section in this page to learn how to use these operations into your camel application.
15.6.6. Consumer Examples 링크 복사링크가 클립보드에 복사되었습니다!
To consume a blob into a file using file component, this can be done like this:
from("azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey").
to("file://blobdirectory");
from("azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey").
to("file://blobdirectory");
However, you can also write to file directly without using the file component, you will need to specify fileDir folder path in order to save your blob in your machine.
from("azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir").
to("mock:results");
from("azure-storage-blob://camelazure/container1?blobName=hello.txt&accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir").
to("mock:results");
Also, the component supports batch consumer, hence you can consume multiple blobs with only specifying the container name, the consumer will return multiple exchanges depending on the number of the blobs in the container.
Example
from("azure-storage-blob://camelazure/container1?accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir").
to("mock:results");
from("azure-storage-blob://camelazure/container1?accountName=yourAccountName&accessKey=yourAccessKey&fileDir=/var/to/awesome/dir").
to("mock:results");
15.6.7. Producer Operations Examples 링크 복사링크가 클립보드에 복사되었습니다!
-
listBlobContainers
-
createBlobContainer
-
deleteBlobContainer:
-
listBlobs:
-
getBlob:
We can either set an outputStream in the exchange body and write the data to it. E.g:
If we don’t set a body, then this operation will give us an InputStream instance which can proceeded further downstream:
-
deleteBlob:
-
downloadBlobToFile:
-
downloadLink
-
uploadBlockBlob
-
stageBlockBlobList
-
commitBlockBlobList
-
getBlobBlockList
from("direct:start")
.to("azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlobBlockList&serviceClient=#client")
.log("${body}")
.to("mock:result");
from("direct:start")
.to("azure-storage-blob://camelazure/container1?blobName=blob&operation=getBlobBlockList&serviceClient=#client")
.log("${body}")
.to("mock:result");
-
createAppendBlob
from("direct:start")
.to("azure-storage-blob://camelazure/container1?blobName=blob&operation=createAppendBlob&serviceClient=#client")
.to("mock:result");
from("direct:start")
.to("azure-storage-blob://camelazure/container1?blobName=blob&operation=createAppendBlob&serviceClient=#client")
.to("mock:result");
-
commitAppendBlob
-
createPageBlob
from("direct:start")
.to("azure-storage-blob://camelazure/container1?blobName=blob&operation=createPageBlob&serviceClient=#client")
.to("mock:result");
from("direct:start")
.to("azure-storage-blob://camelazure/container1?blobName=blob&operation=createPageBlob&serviceClient=#client")
.to("mock:result");
-
uploadPageBlob
-
resizePageBlob
-
clearPageBlob
-
getPageBlobRanges
-
copyBlob
In this way the file.txt in the container containerblob1 of the account 'account', will be copied to the container containerblob2 of the same account.
15.6.8. SAS Token generation example 링크 복사링크가 클립보드에 복사되었습니다!
SAS Blob Container tokens can be generated programmatically or via Azure UI. To generate the token with java code, the following can be done:
The generated SAS token can be then stored to an application.properties file so that it can be loaded by the camel route, for example:
camel.component.azure-storage-blob.sas-token=MY_TOKEN_HERE
from("direct:copyBlob")
.to("azure-storage-blob://account/containerblob2?operation=uploadBlockBlob&credentialType=AZURE_SAS")
camel.component.azure-storage-blob.sas-token=MY_TOKEN_HERE
from("direct:copyBlob")
.to("azure-storage-blob://account/containerblob2?operation=uploadBlockBlob&credentialType=AZURE_SAS")
15.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 36 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.azure-storage-blob.access-key | Access key for the associated azure account name to be used for authentication with azure blob services. | String | |
| camel.component.azure-storage-blob.autowired-enabled | 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 |
| camel.component.azure-storage-blob.blob-name | The blob name, to consume specific blob from a container. However on producer, is only required for the operations on the blob level. | String | |
| camel.component.azure-storage-blob.blob-offset | Set the blob offset for the upload or download operations, default is 0. | 0 | Long |
| camel.component.azure-storage-blob.blob-sequence-number | A user-controlled value that you can use to track requests. The value of the sequence number must be between 0 and 263 - 1.The default value is 0. | 0 | Long |
| camel.component.azure-storage-blob.blob-type | The blob type in order to initiate the appropriate settings for each blob type. | BlobType | |
| camel.component.azure-storage-blob.block-list-type | Specifies which type of blocks to return. | BlockListType | |
| camel.component.azure-storage-blob.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.azure-storage-blob.change-feed-context | When using getChangeFeed producer operation, this gives additional context that is passed through the Http pipeline during the service call. The option is a com.azure.core.util.Context type. | Context | |
| camel.component.azure-storage-blob.change-feed-end-time | When using getChangeFeed producer operation, this filters the results to return events approximately before the end time. Note: A few events belonging to the next hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the end time up by an hour. The option is a java.time.OffsetDateTime type. | OffsetDateTime | |
| camel.component.azure-storage-blob.change-feed-start-time | When using getChangeFeed producer operation, this filters the results to return events approximately after the start time. Note: A few events belonging to the previous hour can also be returned. A few events belonging to this hour can be missing; to ensure all events from the hour are returned, round the start time down by an hour. The option is a java.time.OffsetDateTime type. | OffsetDateTime | |
| camel.component.azure-storage-blob.close-stream-after-read | Close the stream after read or keep it open, default is true. | true | Boolean |
| camel.component.azure-storage-blob.close-stream-after-write | Close the stream after write or keep it open, default is true. | true | Boolean |
| camel.component.azure-storage-blob.commit-block-list-later | When is set to true, the staged blocks will not be committed directly. | true | Boolean |
| camel.component.azure-storage-blob.configuration | The component configurations. The option is a org.apache.camel.component.azure.storage.blob.BlobConfiguration type. | BlobConfiguration | |
| camel.component.azure-storage-blob.create-append-blob | When is set to true, the append blocks will be created when committing append blocks. | true | Boolean |
| camel.component.azure-storage-blob.create-page-blob | When is set to true, the page blob will be created when uploading page blob. | true | Boolean |
| camel.component.azure-storage-blob.credential-type | Determines the credential strategy to adopt. | CredentialType | |
| camel.component.azure-storage-blob.credentials | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information. The option is a com.azure.storage.common.StorageSharedKeyCredential type. | StorageSharedKeyCredential | |
| camel.component.azure-storage-blob.data-count | How many bytes to include in the range. Must be greater than or equal to 0 if specified. | Long | |
| camel.component.azure-storage-blob.download-link-expiration | Override the default expiration (millis) of URL download link. | Long | |
| camel.component.azure-storage-blob.enabled | Whether to enable auto configuration of the azure-storage-blob component. This is enabled by default. | Boolean | |
| camel.component.azure-storage-blob.file-dir | The file directory where the downloaded blobs will be saved to, this can be used in both, producer and consumer. | String | |
| camel.component.azure-storage-blob.health-check-consumer-enabled | Used for enabling or disabling all consumer based health checks from this component. | true | Boolean |
| camel.component.azure-storage-blob.health-check-producer-enabled | Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true. | true | Boolean |
| camel.component.azure-storage-blob.lazy-start-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 |
| camel.component.azure-storage-blob.max-results-per-page | Specifies the maximum number of blobs to return, including all BlobPrefix elements. If the request does not specify maxResultsPerPage or specifies a value greater than 5,000, the server will return up to 5,000 items. | Integer | |
| camel.component.azure-storage-blob.max-retry-requests | Specifies the maximum number of additional HTTP Get requests that will be made while reading the data from a response body. | 0 | Integer |
| camel.component.azure-storage-blob.operation | The blob operation that can be used with this component on the producer. | BlobOperationsDefinition | |
| camel.component.azure-storage-blob.page-blob-size | Specifies the maximum size for the page blob, up to 8 TB. The page blob size must be aligned to a 512-byte boundary. | 512 | Long |
| camel.component.azure-storage-blob.prefix | Filters the results to return only blobs whose names begin with the specified prefix. May be null to return all blobs. | String | |
| camel.component.azure-storage-blob.regex | Filters the results to return only blobs whose names match the specified regular expression. May be null to return all if both prefix and regex are set, regex takes the priority and prefix is ignored. | String | |
| camel.component.azure-storage-blob.sas-token | Set a SAS Token in case of usage of Shared Access Signature | String | |
| camel.component.azure-storage-blob.service-client | Client to a storage account. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. It may also be used to construct URLs to blobs and containers. This client contains operations on a service account. Operations on a container are available on BlobContainerClient through BlobServiceClient#getBlobContainerClient(String), and operations on a blob are available on BlobClient through BlobContainerClient#getBlobClient(String). The option is a com.azure.storage.blob.BlobServiceClient type. | BlobServiceClient | |
| camel.component.azure-storage-blob.source-blob-access-key | Source Blob Access Key: for copyblob operation, sadly, we need to have an accessKey for the source blob we want to copy Passing an accessKey as header, it’s unsafe so we could set as key. | String | |
| camel.component.azure-storage-blob.timeout | An optional timeout value beyond which a RuntimeException will be raised. The option is a java.time.Duration type. | Duration |
Chapter 16. Azure Storage Queue Service 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The Azure Storage Queue component supports storing and retrieving the messages to/from Azure Storage Queue service using Azure APIs v12. However in case of versions above v12, we will see if this component can adopt these changes depending on how much breaking changes can result.
Prerequisites
You must have a valid Windows Azure Storage account. More information is available at Azure Documentation Portal.
16.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using azure-storage-queue with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-azure-storage-queue-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-azure-storage-queue-starter</artifactId>
</dependency>
16.2. URI Format 링크 복사링크가 클립보드에 복사되었습니다!
azure-storage-queue://accountName[/queueName][?options]
azure-storage-queue://accountName[/queueName][?options]
In case of consumer, accountName and queueName are required. In case of producer, it depends on the operation that being requested, for example if operation is on a service level, e.b: listQueues, only accountName is required, but in case of operation being requested on the queue level, for example, createQueue, sendMessage.. etc, both accountName and queueName are required.
The queue will be created if it does not already exist. You can append query options to the URI in the following format,
?options=value&option2=value&…
16.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
16.3.1. 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.
16.3.2. 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.
16.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Storage Queue Service component supports 15 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| configuration (common) | The component configurations. | QueueConfiguration | |
| serviceClient (common) | Autowired Service client to a storage account to interact with the queue service. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. This client contains all the operations for interacting with a queue account in Azure Storage. Operations allowed by the client are creating, listing, and deleting queues, retrieving and updating properties of the account, and retrieving statistics of the account. | QueueServiceClient | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| createQueue (producer) | When is set to true, the queue will be automatically created when sending messages to the queue. | 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 |
| operation (producer) | Queue service operation hint to the producer. Enum values:
| QueueOperationDefinition | |
| 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 |
| maxMessages (queue) | Maximum number of messages to get, if there are less messages exist in the queue than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed range is 1 to 32 messages. | 1 | Integer |
| messageId (queue) | The ID of the message to be deleted or updated. | String | |
| popReceipt (queue) | Unique identifier that must match for the message to be deleted or updated. | String | |
| timeout (queue) | An optional timeout applied to the operation. If a response is not returned before the timeout concludes a RuntimeException will be thrown. | Duration | |
| timeToLive (queue) | How long the message will stay alive in the queue. If unset the value will default to 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number. The format should be in this form: PnDTnHnMn.nS., e.g: PT20.345S — parses as 20.345 seconds, P2D — parses as 2 days However, in case you are using EndpointDsl/ComponentDsl, you can do something like Duration.ofSeconds() since these Java APIs are typesafe. | Duration | |
| visibilityTimeout (queue) | The timeout period for how long the message is invisible in the queue. The timeout must be between 1 seconds and 7 days. The format should be in this form: PnDTnHnMn.nS., e.g: PT20.345S — parses as 20.345 seconds, P2D — parses as 2 days However, in case you are using EndpointDsl/ComponentDsl, you can do something like Duration.ofSeconds() since these Java APIs are typesafe. | Duration | |
| accessKey (security) | Access key for the associated azure account name to be used for authentication with azure queue services. | String | |
| credentials (security) | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information. | StorageSharedKeyCredential |
16.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Azure Storage Queue Service endpoint is configured using URI syntax:
azure-storage-queue:accountName/queueName
azure-storage-queue:accountName/queueName
with the following path and query parameters:
16.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| accountName (common) | Azure account name to be used for authentication with azure queue services. | String | |
| queueName (common) | The queue resource name. | String |
16.5.2. Query Parameters (31 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| serviceClient (common) | Autowired Service client to a storage account to interact with the queue service. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. This client contains all the operations for interacting with a queue account in Azure Storage. Operations allowed by the client are creating, listing, and deleting queues, retrieving and updating properties of the account, and retrieving statistics of the account. | QueueServiceClient | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| sendEmptyMessageWhenIdle (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | 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:
| ExchangePattern | |
| pollStrategy (consumer (advanced)) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | |
| createQueue (producer) | When is set to true, the queue will be automatically created when sending messages to the queue. | 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 |
| operation (producer) | Queue service operation hint to the producer. Enum values:
| QueueOperationDefinition | |
| maxMessages (queue) | Maximum number of messages to get, if there are less messages exist in the queue than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed range is 1 to 32 messages. | 1 | Integer |
| messageId (queue) | The ID of the message to be deleted or updated. | String | |
| popReceipt (queue) | Unique identifier that must match for the message to be deleted or updated. | String | |
| timeout (queue) | An optional timeout applied to the operation. If a response is not returned before the timeout concludes a RuntimeException will be thrown. | Duration | |
| timeToLive (queue) | How long the message will stay alive in the queue. If unset the value will default to 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number. The format should be in this form: PnDTnHnMn.nS., e.g: PT20.345S — parses as 20.345 seconds, P2D — parses as 2 days However, in case you are using EndpointDsl/ComponentDsl, you can do something like Duration.ofSeconds() since these Java APIs are typesafe. | Duration | |
| visibilityTimeout (queue) | The timeout period for how long the message is invisible in the queue. The timeout must be between 1 seconds and 7 days. The format should be in this form: PnDTnHnMn.nS., e.g: PT20.345S — parses as 20.345 seconds, P2D — parses as 2 days However, in case you are using EndpointDsl/ComponentDsl, you can do something like Duration.ofSeconds() since these Java APIs are typesafe. | Duration | |
| backoffErrorThreshold (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | |
| backoffIdleThreshold (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | |
| backoffMultiplier (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | |
| delay (scheduler) | Milliseconds before the next poll. | 500 | long |
| greedy (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean |
| initialDelay (scheduler) | Milliseconds before the first poll starts. | 1000 | long |
| repeatCount (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long |
| runLoggingLevel (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel |
| scheduledExecutorService (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | |
| scheduler (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object |
| schedulerProperties (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | Map | |
| startScheduler (scheduler) | Whether the scheduler should be auto started. | true | boolean |
| timeUnit (scheduler) | Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit |
| useFixedDelay (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
| accessKey (security) | Access key for the associated azure account name to be used for authentication with azure queue services. | String | |
| credentials (security) | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information. | StorageSharedKeyCredential |
Required information options
To use this component, you have 3 options in order to provide the required Azure authentication information:
-
Provide
accountNameandaccessKeyfor your Azure account, this is the simplest way to get started. The accessKey can be generated through your Azure portal. -
Provide a StorageSharedKeyCredential instance which can be provided into
credentialsoption. -
Provide a QueueServiceClient instance which can be provided into
serviceClient. Note: You don’t need to create a specific client, e.g: QueueClient, the QueueServiceClient represents the upper level which can be used to retrieve lower level clients.
16.6. Usage 링크 복사링크가 클립보드에 복사되었습니다!
For example in order to get a message content from the queue messageQueue in the storageAccount storage account and, use the following snippet:
from("azure-storage-queue://storageAccount/messageQueue?accessKey=yourAccessKey").
to("file://queuedirectory");
from("azure-storage-queue://storageAccount/messageQueue?accessKey=yourAccessKey").
to("file://queuedirectory");
16.6.1. Message headers evaluated by the component producer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Variable Name | Type | Operations | Description |
|---|---|---|---|---|
|
|
|
|
| Options for listing queues |
|
|
|
| All | An optional timeout value beyond which a \{@link RuntimeException} will be raised. |
|
|
|
|
| Metadata to associate with the queue |
|
|
|
|
| How long the message will stay alive in the queue. If unset the value will default to 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number. |
|
|
|
|
| The timeout period for how long the message is invisible in the queue. If unset the value will default to 0 and the message will be instantly visible. The timeout must be between 0 seconds and 7 days. |
|
|
|
|
|
When is set to |
|
|
|
|
| Unique identifier that must match for the message to be deleted or updated. |
|
|
|
|
| The ID of the message to be deleted or updated. |
|
|
|
|
| Maximum number of messages to get, if there are less messages exist in the queue than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed range is 1 to 32 messages. |
|
|
|
| All | Specify the producer operation to execute, please see the doc on this page related to producer operation. |
|
|
|
| All | Override the queue name. |
16.6.2. Message headers set by either component producer or consumer 링크 복사링크가 클립보드에 복사되었습니다!
| Header | Variable Name | Type | Description |
|---|---|---|---|
|
|
|
| The ID of message that being sent to the queue. |
|
|
|
| The time the Message was inserted into the Queue. |
|
|
|
| The time that the Message will expire and be automatically deleted. |
|
|
|
| This value is required to delete/update the Message. If deletion fails using this popreceipt then the message has been dequeued by another client. |
|
|
|
| The time that the message will again become visible in the Queue. |
|
|
|
| The number of times the message has been dequeued. |
|
|
|
| Returns non-parsed httpHeaders that can be used by the user. |
16.6.3. Advanced Azure Storage Queue configuration 링크 복사링크가 클립보드에 복사되었습니다!
If your Camel Application is running behind a firewall or if you need to have more control over the QueueServiceClient instance configuration, you can create your own instance:
Then refer to this instance in your Camel azure-storage-queue component configuration:
from("azure-storage-queue://cameldev/queue1?serviceClient=#client")
.to("file://outputFolder?fileName=output.txt&fileExist=Append");
from("azure-storage-queue://cameldev/queue1?serviceClient=#client")
.to("file://outputFolder?fileName=output.txt&fileExist=Append");
16.6.4. Automatic detection of QueueServiceClient client in registry 링크 복사링크가 클립보드에 복사되었습니다!
The component is capable of detecting the presence of an QueueServiceClient bean into the registry. If it’s the only instance of that type it will be used as client and you won’t have to define it as uri parameter, like the example above. This may be really useful for smarter configuration of the endpoint.
16.6.5. Azure Storage Queue Producer operations 링크 복사링크가 클립보드에 복사되었습니다!
Camel Azure Storage Queue component provides wide range of operations on the producer side:
Operations on the service level
For these operations, accountName is required.
| Operation | Description |
|---|---|
|
| Lists the queues in the storage account that pass the filter starting at the specified marker. |
Operations on the queue level
For these operations, accountName and queueName are required.
| Operation | Description |
|---|---|
|
| Creates a new queue. |
|
| Permanently deletes the queue. |
|
| Deletes all messages in the queue.. |
|
|
Default Producer Operation Sends a message with a given time-to-live and a timeout period where the message is invisible in the queue. The message text is evaluated from the exchange message body. By default, if the queue doesn`t exist, it will create an empty queue first. If you want to disable this, set the config |
|
| Deletes the specified message in the queue. |
|
| Retrieves up to the maximum number of messages from the queue and hides them from other operations for the timeout period. However it will not dequeue the message from the queue due to reliability reasons. |
|
| Peek messages from the front of the queue up to the maximum number of messages. |
|
| Updates the specific message in the queue with a new message and resets the visibility timeout. The message text is evaluated from the exchange message body. |
Refer to the example section in this page to learn how to use these operations into your camel application.
16.6.6. Consumer Examples 링크 복사링크가 클립보드에 복사되었습니다!
To consume a queue into a file component with maximum 5 messages in one batch, this can be done like this:
from("azure-storage-queue://cameldev/queue1?serviceClient=#client&maxMessages=5")
.to("file://outputFolder?fileName=output.txt&fileExist=Append");
from("azure-storage-queue://cameldev/queue1?serviceClient=#client&maxMessages=5")
.to("file://outputFolder?fileName=output.txt&fileExist=Append");
16.6.7. Producer Operations Examples 링크 복사링크가 클립보드에 복사되었습니다!
-
listQueues:
-
createQueue:
-
deleteQueue:
-
clearQueue:
-
sendMessage:
-
deleteMessage:
-
receiveMessages:
-
peekMessages:
-
updateMessage:
16.6.8. Development Notes (Important) 링크 복사링크가 클립보드에 복사되었습니다!
When developing on this component, you will need to obtain your Azure accessKey in order to run the integration tests. In addition to the mocked unit tests you will need to run the integration tests with every change you make or even client upgrade as the Azure client can break things even on minor versions upgrade. To run the integration tests, on this component directory, run the following maven command:
mvn verify -PfullTests -DaccountName=myacc -DaccessKey=mykey
mvn verify -PfullTests -DaccountName=myacc -DaccessKey=mykey
Whereby accountName is your Azure account name and accessKey is the access key being generated from Azure portal.
16.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 16 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.azure-storage-queue.access-key | Access key for the associated azure account name to be used for authentication with azure queue services. | String | |
| camel.component.azure-storage-queue.autowired-enabled | 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 |
| camel.component.azure-storage-queue.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.azure-storage-queue.configuration | The component configurations. The option is a org.apache.camel.component.azure.storage.queue.QueueConfiguration type. | QueueConfiguration | |
| camel.component.azure-storage-queue.create-queue | When is set to true, the queue will be automatically created when sending messages to the queue. | false | Boolean |
| camel.component.azure-storage-queue.credentials | StorageSharedKeyCredential can be injected to create the azure client, this holds the important authentication information. The option is a com.azure.storage.common.StorageSharedKeyCredential type. | StorageSharedKeyCredential | |
| camel.component.azure-storage-queue.enabled | Whether to enable auto configuration of the azure-storage-queue component. This is enabled by default. | Boolean | |
| camel.component.azure-storage-queue.lazy-start-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 |
| camel.component.azure-storage-queue.max-messages | Maximum number of messages to get, if there are less messages exist in the queue than requested all the messages will be returned. If left empty only 1 message will be retrieved, the allowed range is 1 to 32 messages. | 1 | Integer |
| camel.component.azure-storage-queue.message-id | The ID of the message to be deleted or updated. | String | |
| camel.component.azure-storage-queue.operation | Queue service operation hint to the producer. | QueueOperationDefinition | |
| camel.component.azure-storage-queue.pop-receipt | Unique identifier that must match for the message to be deleted or updated. | String | |
| camel.component.azure-storage-queue.service-client | Service client to a storage account to interact with the queue service. This client does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate requests to the resource on the service. This client contains all the operations for interacting with a queue account in Azure Storage. Operations allowed by the client are creating, listing, and deleting queues, retrieving and updating properties of the account, and retrieving statistics of the account. The option is a com.azure.storage.queue.QueueServiceClient type. | QueueServiceClient | |
| camel.component.azure-storage-queue.time-to-live | How long the message will stay alive in the queue. If unset the value will default to 7 days, if -1 is passed the message will not expire. The time to live must be -1 or any positive number. The format should be in this form: PnDTnHnMn.nS., e.g: PT20.345S — parses as 20.345 seconds, P2D — parses as 2 days However, in case you are using EndpointDsl/ComponentDsl, you can do something like Duration.ofSeconds() since these Java APIs are typesafe. The option is a java.time.Duration type. | Duration | |
| camel.component.azure-storage-queue.timeout | An optional timeout applied to the operation. If a response is not returned before the timeout concludes a RuntimeException will be thrown. The option is a java.time.Duration type. | Duration | |
| camel.component.azure-storage-queue.visibility-timeout | The timeout period for how long the message is invisible in the queue. The timeout must be between 1 seconds and 7 days. The format should be in this form: PnDTnHnMn.nS., e.g: PT20.345S — parses as 20.345 seconds, P2D — parses as 2 days However, in case you are using EndpointDsl/ComponentDsl, you can do something like Duration.ofSeconds() since these Java APIs are typesafe. The option is a java.time.Duration type. | Duration |
Chapter 17. Bean 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The Bean component binds beans to Camel message exchanges.
17.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using bean with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-bean-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-bean-starter</artifactId>
</dependency>
17.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
bean:beanName[?options]
bean:beanName[?options]
Where beanID can be any string which is used to look up the bean in the Registry
17.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
17.3.1. 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.
17.3.2. 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.
17.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Bean component supports 4 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| cache (producer) | Deprecated Use singleton option instead. | true | 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 |
| scope (producer) | Scope of bean. When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same time. When using request scope the bean is created or looked up once per request (exchange). This can be used if you want to store state on a bean while processing a request and you want to call the same bean instance multiple times while processing the request. The bean does not have to be thread-safe as the instance is only called from the same request. When using delegate scope, then the bean will be looked up or created per call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in use), which depends on their configuration can act as either singleton or prototype scope. so when using prototype then this depends on the delegated registry. Enum values:
| Singleton | BeanScope |
| 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 |
17.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Bean endpoint is configured using URI syntax:
bean:beanName
bean:beanName
with the following path and query parameters:
17.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| beanName (common) | Required Sets the name of the bean to invoke. | String |
17.5.2. Query Parameters (5 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| cache (common) | Deprecated Use scope option instead. | Boolean | |
| method (common) | Sets the name of the method to invoke on the bean. | String | |
| scope (common) | Scope of bean. When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same time. When using request scope the bean is created or looked up once per request (exchange). This can be used if you want to store state on a bean while processing a request and you want to call the same bean instance multiple times while processing the request. The bean does not have to be thread-safe as the instance is only called from the same request. When using prototype scope, then the bean will be looked up or created per call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in use), which depends on their configuration can act as either singleton or prototype scope. so when using prototype then this depends on the delegated registry. Enum values:
| Singleton | BeanScope |
| 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 |
| parameters (advanced) | Used for configuring additional properties on the bean. | Map |
17.6. Examples 링크 복사링크가 클립보드에 복사되었습니다!
The object instance that is used to consume messages must be explicitly registered with the Registry. For example, if you are using Spring you must define the bean in the Spring configuration XML file.
You can also register beans manually via Camel’s Registry with the bind method.
Once an endpoint has been registered, you can build Camel routes that use it to process exchanges.
A bean: endpoint cannot be defined as the input to the route; i.e. you cannot consume from it, you can only route from some inbound message Endpoint to the bean endpoint as output. So consider using a direct: or queue: endpoint as the input.
You can use the createProxy() methods on ProxyHelper to create a proxy that will generate exchanges and send them to any endpoint:
And the same route using XML DSL:
<route> <from uri="direct:hello"/> <to uri="bean:bye"/> </route>
<route>
<from uri="direct:hello"/>
<to uri="bean:bye"/>
</route>
17.7. Bean as endpoint 링크 복사링크가 클립보드에 복사되었습니다!
Camel also supports invoking Bean as an Endpoint. What happens is that when the exchange is routed to the myBean Camel will use the Bean Binding to invoke the bean. The source for the bean is just a plain POJO.
Camel will use Bean Binding to invoke the sayHello method, by converting the Exchange’s In body to the String type and storing the output of the method on the Exchange Out body.
17.8. Java DSL bean syntax 링크 복사링크가 클립보드에 복사되었습니다!
Java DSL comes with syntactic sugar for the component. Instead of specifying the bean explicitly as the endpoint (i.e. to("bean:beanName")) you can use the following syntax:
Instead of passing name of the reference to the bean (so that Camel will lookup for it in the registry), you can specify the bean itself:
17.9. Bean Binding 링크 복사링크가 클립보드에 복사되었습니다!
How bean methods to be invoked are chosen (if they are not specified explicitly through the method parameter) and how parameter values are constructed from the Message are all defined by the Bean Binding mechanism which is used throughout all of the various Bean Integration mechanisms in Camel.
17.10. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 13 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.bean.autowired-enabled | 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 |
| camel.component.bean.enabled | Whether to enable auto configuration of the bean component. This is enabled by default. | Boolean | |
| camel.component.bean.lazy-start-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 |
| camel.component.bean.scope | Scope of bean. When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same time. When using request scope the bean is created or looked up once per request (exchange). This can be used if you want to store state on a bean while processing a request and you want to call the same bean instance multiple times while processing the request. The bean does not have to be thread-safe as the instance is only called from the same request. When using delegate scope, then the bean will be looked up or created per call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in use), which depends on their configuration can act as either singleton or prototype scope. so when using prototype then this depends on the delegated registry. | BeanScope | |
| camel.component.class.autowired-enabled | 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 |
| camel.component.class.enabled | Whether to enable auto configuration of the class component. This is enabled by default. | Boolean | |
| camel.component.class.lazy-start-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 |
| camel.component.class.scope | Scope of bean. When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same time. When using request scope the bean is created or looked up once per request (exchange). This can be used if you want to store state on a bean while processing a request and you want to call the same bean instance multiple times while processing the request. The bean does not have to be thread-safe as the instance is only called from the same request. When using delegate scope, then the bean will be looked up or created per call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in use), which depends on their configuration can act as either singleton or prototype scope. so when using prototype then this depends on the delegated registry. | BeanScope | |
| camel.language.bean.enabled | Whether to enable auto configuration of the bean language. This is enabled by default. | Boolean | |
| camel.language.bean.scope | Scope of bean. When using singleton scope (default) the bean is created or looked up only once and reused for the lifetime of the endpoint. The bean should be thread-safe in case concurrent threads is calling the bean at the same time. When using request scope the bean is created or looked up once per request (exchange). This can be used if you want to store state on a bean while processing a request and you want to call the same bean instance multiple times while processing the request. The bean does not have to be thread-safe as the instance is only called from the same request. When using prototype scope, then the bean will be looked up or created per call. However in case of lookup then this is delegated to the bean registry such as Spring or CDI (if in use), which depends on their configuration can act as either singleton or prototype scope. So when using prototype scope then this depends on the bean registry implementation. | Singleton | String |
| camel.language.bean.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.component.bean.cache | Deprecated Use singleton option instead. | true | Boolean |
| camel.component.class.cache | Deprecated Use singleton option instead. | true | Boolean |
Chapter 18. BeanIO 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 2.10
The BeanIO Data Format uses BeanIO to handle flat payloads (such as XML, CSV, delimited, or fixed length formats).
BeanIO is configured using a mapping XML file where you define the mapping from the flat format to Objects (POJOs). This mapping file is mandatory to use.
18.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using beanio with Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-beanio-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-beanio-starter</artifactId>
</dependency>
18.2. Options 링크 복사링크가 클립보드에 복사되었습니다!
The BeanIO dataformat supports 8 options, which are listed below.
| Name | Default | Java Type | Description |
|---|---|---|---|
| mapping (common) |
| Required The BeanIO mapping file. Is by default loaded from the classpath. You can prefix with file:, http:, or classpath: to denote from where to load the mapping file. | |
| streamName (common) |
| Required The name of the stream to use. | |
| ignoreUnidentifiedRecords (common) |
|
| Whether to ignore unidentified records. |
| ignoreUnexpectedRecords (common) |
|
| Whether to ignore unexpected records. |
| ignoreInvalidRecords (common) |
|
| Whether to ignore invalid records. |
| encoding (advanced) |
| The charset to use. Is by default the JVM platform default charset. | |
| beanReaderErrorHandlerType (advanced) |
| To use a custom org.apache.camel.dataformat.beanio.BeanIOErrorHandler as error handler while parsing. Configure the fully qualified class name of the error handler. Notice the options ignoreUnidentifiedRecords, ignoreUnexpectedRecords, and ignoreInvalidRecords may not be in use when you use a custom error handler. | |
| unmarshalSingleObject (advanced) |
|
| This options controls whether to unmarshal as a list of objects or as a single object only. The former is the default mode, and the latter is only intended in special use-cases where beanio maps the Camel message to a single POJO bean. |
18.3. Usage 링크 복사링크가 클립보드에 복사되었습니다!
An example of a mapping file is here.
To use the BeanIODataFormat you need to configure the data format with the mapping file, as well the name of the stream.
This can be done as shown below. The streamName is employeeFile.
Java
XML
To use the BeanIO data format in XML, you need to configure it using the <beanio> XML tag as shown below. The routes are similar to the example above.
The first route is for transforming CSV data into a List<Employee> Java objects. Which we then split, so the mock endpoint receives a message for each row.
The second route is for the reverse operation, to transform a List<Employee> into a stream of CSV data.
The CSV data could, for example, be as below:
Joe,Smith,Developer,75000,10012009 Jane,Doe,Architect,80000,01152008 Jon,Anderson,Manager,85000,03182007
Joe,Smith,Developer,75000,10012009
Jane,Doe,Architect,80000,01152008
Jon,Anderson,Manager,85000,03182007
18.4. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 9 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.dataformat.beanio.bean-reader-error-handler-type | To use a custom org.apache.camel.dataformat.beanio.BeanIOErrorHandler as error handler while parsing. Configure the fully qualified class name of the error handler. Notice the options ignoreUnidentifiedRecords, ignoreUnexpectedRecords, and ignoreInvalidRecords may not be in use when you use a custom error handler. | String | |
| camel.dataformat.beanio.enabled | Whether to enable auto configuration of the beanio data format. This is enabled by default. | Boolean | |
| camel.dataformat.beanio.encoding | The charset to use. Is by default the JVM platform default charset. | String | |
| camel.dataformat.beanio.ignore-invalid-records | Whether to ignore invalid records. | false | Boolean |
| camel.dataformat.beanio.ignore-unexpected-records | Whether to ignore unexpected records. | false | Boolean |
| camel.dataformat.beanio.ignore-unidentified-records | Whether to ignore unidentified records. | false | Boolean |
| camel.dataformat.beanio.mapping | The BeanIO mapping file. Is by default loaded from the classpath. You can prefix with file:, http:, or classpath: to denote from where to load the mapping file. | String | |
| camel.dataformat.beanio.stream-name | The name of the stream to use. | String | |
| camel.dataformat.beanio.unmarshal-single-object | This option controls whether to unmarshal as a list of objects or as a single object only. The former is the default mode, and the latter is only intended in special use-cases where beanio maps the Camel message to a single POJO bean. | false | Boolean |
Chapter 19. Bean Validator 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The Validator component performs bean validation of the message body using the Java Bean Validation API (). Camel uses the reference implementation, which is Hibernate Validator.
19.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using bean-validator with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-bean-validator-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-bean-validator-starter</artifactId>
</dependency>
19.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
bean-validator:label[?options]
bean-validator:label[?options]
Where label is an arbitrary text value describing the endpoint. You can append query options to the URI in the following format,
?option=value&option=value&…
19.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
19.3.1. 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.
19.3.2. 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.
19.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Bean Validator component supports 8 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| ignoreXmlConfiguration (producer) | Whether to ignore data from the META-INF/validation.xml file. | 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 |
| constraintValidatorFactory (advanced) | To use a custom ConstraintValidatorFactory. | ConstraintValidatorFactory | |
| messageInterpolator (advanced) | To use a custom MessageInterpolator. | MessageInterpolator | |
| traversableResolver (advanced) | To use a custom TraversableResolver. | TraversableResolver | |
| validationProviderResolver (advanced) | To use a a custom ValidationProviderResolver. | ValidationProviderResolver | |
| validatorFactory (advanced) | Autowired To use a custom ValidatorFactory. | ValidatorFactory |
19.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Bean Validator endpoint is configured using URI syntax:
bean-validator:label
bean-validator:label
with the following path and query parameters:
19.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| label (producer) | Required Where label is an arbitrary text value describing the endpoint. | String |
19.5.2. Query Parameters (8 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| group (producer) | To use a custom validation group. | javax.validation.groups.Default | String |
| ignoreXmlConfiguration (producer) | Whether to ignore data from the META-INF/validation.xml file. | 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 |
| constraintValidatorFactory (advanced) | To use a custom ConstraintValidatorFactory. | ConstraintValidatorFactory | |
| messageInterpolator (advanced) | To use a custom MessageInterpolator. | MessageInterpolator | |
| traversableResolver (advanced) | To use a custom TraversableResolver. | TraversableResolver | |
| validationProviderResolver (advanced) | To use a a custom ValidationProviderResolver. | ValidationProviderResolver | |
| validatorFactory (advanced) | To use a custom ValidatorFactory. | ValidatorFactory |
19.6. Example 링크 복사링크가 클립보드에 복사되었습니다!
Assumed we have a java bean with the following annotations
Car.java
and an interface definition for our custom validation group
OptionalChecks.java
public interface OptionalChecks {
}
public interface OptionalChecks {
}
with the following Camel route, only the @NotNull constraints on the attributes manufacturer and licensePlate will be validated (Camel uses the default group javax.validation.groups.Default).
from("direct:start")
.to("bean-validator://x")
.to("mock:end")
from("direct:start")
.to("bean-validator://x")
.to("mock:end")
If you want to check the constraints from the group OptionalChecks, you have to define the route like this
from("direct:start")
.to("bean-validator://x?group=OptionalChecks")
.to("mock:end")
from("direct:start")
.to("bean-validator://x?group=OptionalChecks")
.to("mock:end")
If you want to check the constraints from both groups, you have to define a new interface first
AllChecks.java
@GroupSequence({Default.class, OptionalChecks.class})
public interface AllChecks {
}
@GroupSequence({Default.class, OptionalChecks.class})
public interface AllChecks {
}
and then your route definition should looks like this
from("direct:start")
.to("bean-validator://x?group=AllChecks")
.to("mock:end")
from("direct:start")
.to("bean-validator://x?group=AllChecks")
.to("mock:end")
And if you have to provide your own message interpolator, traversable resolver and constraint validator factory, you have to write a route like this
<bean id="myMessageInterpolator" class="my.ConstraintValidatorFactory" /> <bean id="myTraversableResolver" class="my.TraversableResolver" /> <bean id="myConstraintValidatorFactory" class="my.ConstraintValidatorFactory" />
<bean id="myMessageInterpolator" class="my.ConstraintValidatorFactory" />
<bean id="myTraversableResolver" class="my.TraversableResolver" />
<bean id="myConstraintValidatorFactory" class="my.ConstraintValidatorFactory" />
from("direct:start")
.to("bean-validator://x?group=AllChecks&messageInterpolator=#myMessageInterpolator
&traversableResolver=#myTraversableResolver&constraintValidatorFactory=#myConstraintValidatorFactory")
.to("mock:end")
from("direct:start")
.to("bean-validator://x?group=AllChecks&messageInterpolator=#myMessageInterpolator
&traversableResolver=#myTraversableResolver&constraintValidatorFactory=#myConstraintValidatorFactory")
.to("mock:end")
It’s also possible to describe your constraints as XML and not as Java annotations. In this case, you have to provide the file META-INF/validation.xml which could looks like this
validation.xml
and the constraints-car.xml file
constraints-car.xml
Here is the XML syntax for the example route definition for OrderedChecks.
Note that the body should include an instance of a class to validate.
19.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 9 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.bean-validator.autowired-enabled | 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 |
| camel.component.bean-validator.constraint-validator-factory | To use a custom ConstraintValidatorFactory. The option is a javax.validation.ConstraintValidatorFactory type. | ConstraintValidatorFactory | |
| camel.component.bean-validator.enabled | Whether to enable auto configuration of the bean-validator component. This is enabled by default. | Boolean | |
| camel.component.bean-validator.ignore-xml-configuration | Whether to ignore data from the META-INF/validation.xml file. | false | Boolean |
| camel.component.bean-validator.lazy-start-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 |
| camel.component.bean-validator.message-interpolator | To use a custom MessageInterpolator. The option is a javax.validation.MessageInterpolator type. | MessageInterpolator | |
| camel.component.bean-validator.traversable-resolver | To use a custom TraversableResolver. The option is a javax.validation.TraversableResolver type. | TraversableResolver | |
| camel.component.bean-validator.validation-provider-resolver | To use a a custom ValidationProviderResolver. The option is a javax.validation.ValidationProviderResolver type. | ValidationProviderResolver | |
| camel.component.bean-validator.validator-factory | To use a custom ValidatorFactory. The option is a javax.validation.ValidatorFactory type. | ValidatorFactory |
Chapter 20. Bindy 링크 복사링크가 클립보드에 복사되었습니다!
The goal of this component is to allow the parsing/binding of non-structured data (or to be more precise non-XML data) to/from Java Beans that have binding mappings defined with annotations. Using Bindy, you can bind data from sources such as :
- CSV records,
- Fixed-length records,
- FIX messages,
- or almost any other non-structured data
to one or many Plain Old Java Object (POJO). Bindy converts the data according to the type of the java property. POJOs can be linked together with one-to-many relationships available in some cases. Moreover, for data type like Date, Double, Float, Integer, Short, Long and BigDecimal, you can provide the pattern to apply during the formatting of the property.
For the BigDecimal numbers, you can also define the precision and the decimal or grouping separators.
| Type | Format Type | Pattern example | Link |
|---|---|---|---|
| Date |
|
| https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/SimpleDateFormat.html |
| Decimal* |
|
| https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/text/DecimalFormat.html |
Where Decimal = Double, Integer, Float, Short, Long
Format supported
This first release only support comma separated values fields and key value pair fields (e.g. : FIX messages).
To work with camel-bindy, you must first define your model in a package (e.g. com.acme.model) and for each model class (e.g. Order, Client, Instrument, …) add the required annotations (described hereafter) to the Class or field.
Multiple models
As you configure bindy using class names instead of package names you can put multiple models in the same package.
20.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using bindy-csv with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-bindy-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-bindy-starter</artifactId>
</dependency>
20.2. Options 링크 복사링크가 클립보드에 복사되었습니다!
The Bindy dataformat supports 5 options, which are listed below.
| Name | Default | Java Type | Description |
|---|---|---|---|
| type |
| Required Whether to use Csv, Fixed, or KeyValue. Enum values:
| |
| classType |
| Name of model class to use. | |
| locale |
| To configure a default locale to use, such as us for united states. To use the JVM platform default locale then use the name default. | |
| unwrapSingleInstance |
| When unmarshalling should a single instance be unwrapped and returned instead of wrapped in a java.util.List. | |
| allowEmptyStream |
| Whether to allow empty streams in the unmarshal process. If true, no exception will be thrown when a body without records is provided. |
20.3. Annotations 링크 복사링크가 클립보드에 복사되었습니다!
The annotations created allow to map different concept of your model to the POJO like:
- Type of record (CSV, key value pair (e.g. FIX message), fixed length …),
- Link (to link object in another object),
- DataField and their properties (int, type, …),
- KeyValuePairField (for key = value format like we have in FIX financial messages),
- Section (to identify header, body and footer section),
- OneToMany,
- BindyConverter,
- FormatFactories
This section will describe them.
20.3.1. 1. CsvRecord 링크 복사링크가 클립보드에 복사되었습니다!
The CsvRecord annotation is used to identified the root class of the model. It represents a record = "a line of a CSV file" and can be linked to several children model classes.
| Annotation name | Record type | Level |
|---|---|---|
| CsvRecord | CSV | Class |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| separator | String | ✓ | Separator used to split a record in tokens (mandatory) - can be ',' or ';' or 'anything'. The only whitespace character supported is tab (\t). No other whitespace characters (spaces) are not supported. This value is interpreted as a regular expression. If you want to use a sign which has a special meaning in regular expressions, e.g. the '|' sign, then you have to mask it, like '|'. | |
| allowEmptyStream | boolean | false | The allowEmptyStream parameter will allow to prcoess the unavaiable stream for CSV file. | |
| autospanLine | boolean | false | Last record spans rest of line (optional) - if enabled then the last column is auto spanned to end of line, for example if its a comment, etc this allows the line to contain all characters, also the delimiter char. | |
| crlf | String | WINDOWS | Character to be used to add a carriage return after each record (optional) - allow to define the carriage return character to use. If you specify a value other than the three listed before, the value you enter (custom) will be used as the CRLF character(s). Three values can be used : WINDOWS, UNIX, MAC, or custom. | |
| endWithLineBreak | boolean | true | The endWithLineBreak parameter flags if the CSV file should end with a line break or not (optional) | |
| generateHeaderColumns | boolean | false | The generateHeaderColumns parameter allow to add in the CSV generated the header containing names of the columns | |
| isOrdered | boolean | false | Indicates if the message must be ordered in output | |
| name | String | Name describing the record (optional) | ||
| quote | String | " | Whether to marshal columns with the given quote character (optional) - allow to specify a quote character of the fields when CSV is generated. This annotation is associated to the root class of the model and must be declared one time. | |
| quoting | boolean | false | Indicate if the values (and headers) must be quoted when marshaling (optional) | |
| quotingEscaped | boolean | false | Indicate if the values must be escaped when quoting (optional) | |
| removeQuotes | boolean | true | The remove quotes parameter flags if unmarshalling should try to remove quotes for each field | |
| skipField | boolean | false | The skipField parameter will allow to skip fields of a CSV file. If some fields are not necessary, they can be skipped. | |
| skipFirstLine | boolean | false | The skipFirstLine parameter will allow to skip or not the first line of a CSV file. This line often contains columns definition | |
| trimLine | boolean | true | Whether to trim each line (stand and end) before parsing the line into data fields. |
case 1 : separator = ','
The separator used to segregate the fields in the CSV record is , :
10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD, 08-01-2009
10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD, 08-01-2009
@CsvRecord( separator = "," )
public Class Order {
}
@CsvRecord( separator = "," )
public Class Order {
}
case 2 : separator = ';'
Compare to the previous case, the separator here is ; instead of , :
10; J; Pauline; M; XD12345678; Fortis Dynamic 15/15; 2500; USD; 08-01-2009
10; J; Pauline; M; XD12345678; Fortis Dynamic 15/15; 2500; USD; 08-01-2009
@CsvRecord( separator = ";" )
public Class Order {
}
@CsvRecord( separator = ";" )
public Class Order {
}
case 3 : separator = '|'
Compare to the previous case, the separator here is | instead of ; :
10| J| Pauline| M| XD12345678| Fortis Dynamic 15/15| 2500| USD| 08-01-2009
10| J| Pauline| M| XD12345678| Fortis Dynamic 15/15| 2500| USD| 08-01-2009
@CsvRecord( separator = "\\|" )
public Class Order {
}
@CsvRecord( separator = "\\|" )
public Class Order {
}
case 4 : separator = '\",\"'
Applies for Camel 2.8.2 or older
When the field to be parsed of the CSV record contains , or ; which is also used as separator, we should find another strategy to tell camel bindy how to handle this case. To define the field containing the data with a comma, you will use single or double quotes as delimiter (e.g : '10', 'Street 10, NY', 'USA' or "10", "Street 10, NY", "USA").
In this case, the first and last character of the line which are a single or double quotes will be removed by bindy.
"10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15","2500","USD","08-01-2009"
"10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15","2500","USD","08-01-2009"
@CsvRecord( separator = "\",\"" )
public Class Order {
}
@CsvRecord( separator = "\",\"" )
public Class Order {
}
Bindy automatically detects if the record is enclosed with either single or double quotes and automatic remove those quotes when unmarshalling from CSV to Object. Therefore do not include the quotes in the separator, but simply do as below:
"10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15","2500","USD","08-01-2009"
"10","J","Pauline"," M","XD12345678","Fortis Dynamic 15,15","2500","USD","08-01-2009"
@CsvRecord( separator = "," )
public Class Order {
}
@CsvRecord( separator = "," )
public Class Order {
}
Note that if you want to marshal from Object to CSV and use quotes, then you need to specify which quote character to use, using the quote attribute on the @CsvRecord as shown below:
@CsvRecord( separator = ",", quote = "\"" )
public Class Order {
}
@CsvRecord( separator = ",", quote = "\"" )
public Class Order {
}
case 5 : separator & skipFirstLine
The feature is interesting when the client wants to have in the first line of the file, the name of the data fields :
order id, client id, first name, last name, isin code, instrument name, quantity, currency, date
order id, client id, first name, last name, isin code, instrument name, quantity, currency, date
To inform bindy that this first line must be skipped during the parsing process, then we use the attribute :
@CsvRecord(separator = ",", skipFirstLine = true)
public Class Order {
}
@CsvRecord(separator = ",", skipFirstLine = true)
public Class Order {
}
case 6 : generateHeaderColumns
To add at the first line of the CSV generated, the attribute generateHeaderColumns must be set to true in the annotation like this :
@CsvRecord( generateHeaderColumns = true )
public Class Order {
}
@CsvRecord( generateHeaderColumns = true )
public Class Order {
}
As a result, Bindy during the unmarshaling process will generate CSV like this :
order id, client id, first name, last name, isin code, instrument name, quantity, currency, date 10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD, 08-01-2009
order id, client id, first name, last name, isin code, instrument name, quantity, currency, date
10, J, Pauline, M, XD12345678, Fortis Dynamic 15/15, 2500, USD, 08-01-2009
case 7 : carriage return
If the platform where camel-bindy will run is not Windows but Macintosh or Unix, then you can change the crlf property like this. Three values are available : WINDOWS, UNIX or MAC
@CsvRecord(separator = ",", crlf="MAC")
public Class Order {
}
@CsvRecord(separator = ",", crlf="MAC")
public Class Order {
}
Additionally, if for some reason you need to add a different line ending character, you can opt to specify it using the crlf parameter. In the following example, we can end the line with a comma followed by the newline character:
@CsvRecord(separator = ",", crlf=",\n")
public Class Order {
}
@CsvRecord(separator = ",", crlf=",\n")
public Class Order {
}
case 8 : isOrdered
Sometimes, the order to follow during the creation of the CSV record from the model is different from the order used during the parsing. Then, in this case, we can use the attribute isOrdered = true to indicate this in combination with attribute position of the DataField annotation.
pos is used to parse the file stream, while position is used to generate the CSV.
20.3.2. 2. Link 링크 복사링크가 클립보드에 복사되었습니다!
The link annotation will allow to link objects together.
| Annotation name | Record type | Level |
|---|---|---|
| Link | all | Class & Property |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| linkType | LinkType | OneToOne | Type of link identifying the relation between the classes |
Only one-to-one relation is allowed as of the current version.
E.g : If the model class Client is linked to the Order class, then use annotation Link in the Order class like this :
Property Link
And for the class Client :
Class Link
@Link
public class Client {
}
@Link
public class Client {
}
20.3.3. 3. DataField 링크 복사링크가 클립보드에 복사되었습니다!
The DataField annotation defines the property of the field. Each datafield is identified by its position in the record, a type (string, int, date, …) and optionally of a pattern.
| Annotation name | Record type | Level |
|---|---|---|
| DataField | all | Property |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| pos | int | ✓ | Position of the data in the input record, must start from 1 (mandatory). See the position parameter. | |
| align | String | R | Align the text to the right or left. Use values <tt>R</tt> or <tt>L</tt>. | |
| clip | boolean | false | Indicates to clip data in the field if it exceeds the allowed length when using fixed length. | |
| columnName | String |
Name of the header column (optional). Uses the name of the property as default. Only applicable when | ||
| decimalSeparator | String | Decimal Separator to be used with BigDecimal number | ||
| defaultValue | String | Field’s default value in case no value is set | ||
| delimiter | String | Optional delimiter to be used if the field has a variable length | ||
| groupingSeparator | String | Grouping Separator to be used with BigDecimal number when we would like to format/parse to number with grouping e.g. 123,456.789 | ||
| impliedDecimalSeparator | boolean | false | Indicates if there is a decimal point implied at a specified location | |
| length | int | 0 | Length of the data block (number of characters) if the record is set to a fixed length | |
| lengthPos | int | 0 | Identifies a data field in the record that defines the expected fixed length for this field | |
| method | String | Method name to call to apply such customization on DataField. This must be the method on the datafield itself or you must provide static fully qualified name of the class’s method e.g: see unit test org.apache.camel.dataformat.bindy.csv.BindySimpleCsvFunctionWithExternalMethodTest.replaceToBar | ||
| name | String | Name of the field (optional) | ||
| paddingChar | char | The char to pad with if the record is set to a fixed length | ||
| pattern | String | Pattern that the Java formatter (SimpleDateFormat by example) will use to transform the data (optional). If using pattern, then setting locale on bindy data format is recommended. Either set to a known locale such as "us" or use "default" to use platform default locale. | ||
| position | int | 0 | Position of the field in the output message generated (should start from 1). Must be used when the position of the field in the CSV generated (output message) must be different compare to input position (pos). See the pos parameter. | |
| precision | int | 0 | precision of the \{@link java.math.BigDecimal} number to be created | |
| required | boolean | false | Indicates if the field is mandatory | |
| rounding | String | CEILING | Round mode to be used to round/scale a BigDecimal Values : UP, DOWN, CEILING, FLOOR, HALF_UP, HALF_DOWN,HALF_EVEN, UNNECESSARY e.g : Number = 123456.789, Precision = 2, Rounding = CEILING Result : 123456.79 | |
| timezone | String | Timezone to be used. | ||
| trim | boolean | false | Indicates if the value should be trimmed |
case 1 : pos
This parameter/attribute represents the position of the field in the CSV record.
Position
As you can see in this example the position starts at 1 but continues at 5 in the class Order. The numbers from 2 to 4 are defined in the class Client (see here after).
Position continues in another model class
case 2 : pattern
The pattern allows to enrich or validates the format of your data
Pattern
case 3 : precision
The precision is helpful when you want to define the decimal part of your number.
Precision
case 4 : Position is different in output
The position attribute will inform bindy how to place the field in the CSV record generated. By default, the position used corresponds to the position defined with the attribute pos. If the position is different (that means that we have an asymetric processus comparing marshaling from unmarshaling) then we can use position to indicate this.
Here is an example:
Position is different in output
This attribute of the annotation @DataField must be used in combination with attribute isOrdered = true of the annotation @CsvRecord.
case 5 : required
If a field is mandatory, simply use the attribute required set to true.
Required
If this field is not present in the record, then an error will be raised by the parser with the following information :
Some fields are missing (optional or mandatory), line :
Some fields are missing (optional or mandatory), line :
case 6 : trim
If a field has leading and/or trailing spaces which should be removed before they are processed, simply use the attribute trim set to true.
Trim
case 7 : defaultValue
If a field is not defined then uses the value indicated by the defaultValue attribute.
Default value
case 8 : columnName
Specifies the column name for the property only if @CsvRecord has annotation generateHeaderColumns = true.
Column Name
This attribute is only applicable to optional fields.
20.3.4. 4. FixedLengthRecord 링크 복사링크가 클립보드에 복사되었습니다!
The FixedLengthRecord annotation is used to identified the root class of the model. It represents a record = "a line of a file/message containing data fixed length (number of characters) formatted" and can be linked to several children model classes. This format is a bit particular because data of a field can be aligned to the right or to the left.
When the size of the data does not fill completely the length of the field, we can then add 'pad' characters.
| Annotation name | Record type | Level |
|---|---|---|
| FixedLengthRecord | fixed | Class |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| countGrapheme | boolean | false | Indicates how chars are counted | |
| crlf | String | WINDOWS | Character to be used to add a carriage return after each record (optional). Possible values: WINDOWS, UNIX, MAC, or custom. This option is used only during marshalling, whereas unmarshalling uses system default JDK provided line delimiter unless eol is customized. | |
| eol | String | Character to be used to process considering end of line after each record while unmarshalling (optional - default: "", which help default JDK provided line delimiter to be used unless any other line delimiter provided) This option is used only during unmarshalling, where marshalling uses system default provided line delimiter as "WINDOWS" unless any other value is provided. | ||
| footer | Class | void | Indicates that the record(s) of this type may be followed by a single footer record at the end of the file | |
| header | Class | void | Indicates that the record(s) of this type may be preceded by a single header record at the beginning of in the file | |
| ignoreMissingChars | boolean | false | Indicates whether too short lines will be ignored | |
| ignoreTrailingChars | boolean | false | Indicates that characters beyond the last mapped filed can be ignored when unmarshalling / parsing. This annotation is associated to the root class of the model and must be declared one time. | |
| length | int | 0 | The fixed length of the record (number of characters). It means that the record will always be that long padded with \{#paddingChar()}'s | |
| name | String | Name describing the record (optional) | ||
| paddingChar | char | The char to pad with. | ||
| skipFooter | boolean | false | Configures the data format to skip marshalling / unmarshalling of the footer record. Configure this parameter on the primary record (e.g., not the header or footer). | |
| skipHeader | boolean | false | Configures the data format to skip marshalling / unmarshalling of the header record. Configure this parameter on the primary record (e.g., not the header or footer). |
A record may not be both a header/footer and a primary fixed-length record.
case 1 : Simple fixed length record
This simple example shows how to design the model to parse/format a fixed message
10A9PaulineMISINXD12345678BUYShare2500.45USD01-08-2009
10A9PaulineMISINXD12345678BUYShare2500.45USD01-08-2009
Fixed-simple
case 2 : Fixed length record with alignment and padding
This more elaborated example show how to define the alignment for a field and how to assign a padding character which is ' ' here:
10A9 PaulineM ISINXD12345678BUYShare2500.45USD01-08-2009
10A9 PaulineM ISINXD12345678BUYShare2500.45USD01-08-2009
Fixed-padding-align
case 3 : Field padding
Sometimes, the default padding defined for record cannnot be applied to the field as we have a number format where we would like to pad with '0' instead of ' '. In this case, you can use in the model the attribute paddingChar on @DataField to set this value.
10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009
10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009
Fixed-padding-field
case 4: Fixed length record with delimiter
Fixed-length records sometimes have delimited content within the record. The firstName and lastName fields are delimited with the ^ character in the following example:
10A9Pauline^M^ISINXD12345678BUYShare000002500.45USD01-08-2009
10A9Pauline^M^ISINXD12345678BUYShare000002500.45USD01-08-2009
Fixed-delimited
The pos value(s) in a fixed-length record may optionally be defined using ordinal, sequential values instead of precise column numbers.
case 5 : Fixed length record with record-defined field length
Occasionally a fixed-length record may contain a field that define the expected length of another field within the same record. In the following example the length of the instrumentNumber field value is defined by the value of instrumentNumberLen field in the record.
10A9Pauline^M^ISIN10XD12345678BUYShare000002500.45USD01-08-2009
10A9Pauline^M^ISIN10XD12345678BUYShare000002500.45USD01-08-2009
Fixed-delimited
case 6 : Fixed length record with header and footer
Bindy will discover fixed-length header and footer records that are configured as part of the model – provided that the annotated classes exist either in the same package as the primary @FixedLengthRecord class, or within one of the configured scan packages. The following text illustrates two fixed-length records that are bracketed by a header record and footer record.
101-08-2009 10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009 10A9 RichN ISINXD12345678BUYShare000002700.45USD01-08-2009 9000000002
101-08-2009
10A9 PaulineM ISINXD12345678BUYShare000002500.45USD01-08-2009
10A9 RichN ISINXD12345678BUYShare000002700.45USD01-08-2009
9000000002
Fixed-header-and-footer-main-class
case 7 : Skipping content when parsing a fixed length record
It is common to integrate with systems that provide fixed-length records containing more information than needed for the target use case. It is useful in this situation to skip the declaration and parsing of those fields that we do not need. To accomodate this, Bindy will skip forward to the next mapped field within a record if the pos value of the next declared field is beyond the cursor position of the last parsed field. Using absolute pos locations for the fields of interest (instead of ordinal values) causes Bindy to skip content between two fields.
Similarly, it is possible that none of the content beyond some field is of interest. In this case, you can tell Bindy to skip parsing of everything beyond the last mapped field by setting the ignoreTrailingChars property on the @FixedLengthRecord declaration.
20.3.5. 5. Message 링크 복사링크가 클립보드에 복사되었습니다!
The Message annotation is used to identified the class of your model who will contain key value pairs fields. This kind of format is used mainly in Financial Exchange Protocol Messages (FIX). Nevertheless, this annotation can be used for any other format where data are identified by keys. The key pair values are separated each other by a separator which can be a special character like a tab delimitor (unicode representation : \u0009) or a start of heading (unicode representation : \u0001)
To work with FIX messages, the model must contain a Header and Trailer classes linked to the root message class which could be a Order class. This is not mandatory but will be very helpful when you will use camel-bindy in combination with camel-fix which is a Fix gateway based on quickFix project .
| Annotation name | Record type | Level |
|---|---|---|
| Message | key value pair | Class |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| keyValuePairSeparator | String | ✓ | Key value pair separator is used to split the values from their keys (mandatory). Can be '\u0001', '\u0009', '#', or 'anything'. | |
| pairSeparator | String | ✓ | Pair separator used to split the key value pairs in tokens (mandatory). Can be '=', ';', or 'anything'. | |
| crlf | String | WINDOWS | Character to be used to add a carriage return after each record (optional). Possible values = WINDOWS, UNIX, MAC, or custom. If you specify a value other than the three listed before, the value you enter (custom) will be used as the CRLF character(s). | |
| isOrdered | boolean | false | Indicates if the message must be ordered in output. This annotation is associated to the message class of the model and must be declared one time. | |
| name | String | Name describing the message (optional) | ||
| type | String | FIX | type is used to define the type of the message (e.g. FIX, EMX, …) (optional) | |
| version | String | 4.1 | version defines the version of the message (e.g. 4.1, …) (optional) |
case 1 : separator = 'u0001'
The separator used to segregate the key value pair fields in a FIX message is the ASCII 01 character or in unicode format \u0001. This character must be escaped a second time to avoid a java runtime error. Here is an example :
8=FIX.4.1 9=20 34=1 35=0 49=INVMGR 56=BRKR 1=BE.CHM.001 11=CHM0001-01 22=4 ...
8=FIX.4.1 9=20 34=1 35=0 49=INVMGR 56=BRKR 1=BE.CHM.001 11=CHM0001-01 22=4 ...
and how to use the annotation:
FIX - message
@Message(keyValuePairSeparator = "=", pairSeparator = "\u0001", type="FIX", version="4.1")
public class Order {
}
@Message(keyValuePairSeparator = "=", pairSeparator = "\u0001", type="FIX", version="4.1")
public class Order {
}
Look at test cases
The ASCII character like tab, … cannot be displayed in WIKI page. So, have a look to the test case of camel-bindy to see exactly how the FIX message looks like (https://github.com/apache/camel/blob/main/components/camel-bindy/src/test/data/fix/fix.txt) and the Order, Trailer, Header classes (https://github.com/apache/camel/blob/main/components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/model/fix/simple/Order.java).
20.3.6. 6. KeyValuePairField 링크 복사링크가 클립보드에 복사되었습니다!
The KeyValuePairField annotation defines the property of a key value pair field. Each KeyValuePairField is identified by a tag (= key) and its value associated, a type (string, int, date, …), optionaly a pattern and if the field is required.
| Annotation name | Record type | Level |
|---|---|---|
| KeyValuePairField | Key Value Pair - FIX | Property |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| tag | int | ✓ | tag identifying the field in the message (mandatory) - must be unique | |
| impliedDecimalSeparator | boolean | false | <b>Camel 2.11:</b> Indicates if there is a decimal point implied at a specified location | |
| name | String | name of the field (optional) | ||
| pattern | String | pattern that the formater will use to transform the data (optional) | ||
| position | int | 0 | Position of the field in the message generated - must be used when the position of the key/tag in the FIX message must be different | |
| precision | int | 0 | precision of the BigDecimal number to be created | |
| required | boolean | false | Indicates if the field is mandatory | |
| timezone | String | Timezone to be used. |
case 1 : tag
This parameter represents the key of the field in the message:
FIX message - Tag
case 2 : Different position in output
If the tags/keys that we will put in the FIX message must be sorted according to a predefine order, then use the attribute position of the annotation @KeyValuePairField.
FIX message - Tag - sort
20.3.7. 7. Section 링크 복사링크가 클립보드에 복사되었습니다!
In FIX message of fixed length records, it is common to have different sections in the representation of the information : header, body and section. The purpose of the annotation @Section is to inform bindy about which class of the model represents the header (= section 1), body (= section 2) and footer (= section 3)
Only one attribute/parameter exists for this annotation.
| Annotation name | Record type | Level |
|---|---|---|
| Section | FIX | Class |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| number | int | ✓ | Number of the section |
case 1 : Section
Definition of the header section:
FIX message - Section - Header
Definition of the body section:
FIX message - Section - Body
Definition of the footer section:
FIX message - Section - Footer
20.3.8. 8. OneToMany 링크 복사링크가 클립보드에 복사되었습니다!
The purpose of the annotation @OneToMany is to allow to work with a List<?> field defined a POJO class or from a record containing repetitive groups.
Restrictions for OneToMany
Be careful, the one to many of bindy does not allow to handle repetitions defined on several levels of the hierarchy.
The relation OneToMany ONLY WORKS in the following cases :
- Reading a FIX message containing repetitive groups (= group of tags/keys)
- Generating a CSV with repetitive data
| Annotation name | Record type | Level |
|---|---|---|
| OneToMany | all | Property |
| Parameter name | Type | Required | Default value | Info |
|---|---|---|---|---|
| mappedTo | String | Class name associated to the type of the List<Type of the Class> |
case 1 : Generating CSV with repetitive data
Here is the CSV output that we want :
Claus,Ibsen,Camel in Action 1,2010,35 Claus,Ibsen,Camel in Action 2,2012,35 Claus,Ibsen,Camel in Action 3,2013,35 Claus,Ibsen,Camel in Action 4,2014,35
Claus,Ibsen,Camel in Action 1,2010,35
Claus,Ibsen,Camel in Action 2,2012,35
Claus,Ibsen,Camel in Action 3,2013,35
Claus,Ibsen,Camel in Action 4,2014,35
The repetitive data concern the title of the book and its publication date while first, last name and age are common and the classes used to modeling this. The Author class contains a List of Book.
Generate CSV with repetitive data
case 2 : Reading FIX message containing group of tags/keys
Here is the message that we would like to process in our model :
Tags 22, 48 and 54 are repeated.
And the code:
Reading FIX message containing group of tags/keys
20.3.9. 9. BindyConverter 링크 복사링크가 클립보드에 복사되었습니다!
The purpose of the annotation @BindyConverter is define a converter to be used on field level. The provided class must implement the Format interface.
20.3.10. 10. FormatFactories 링크 복사링크가 클립보드에 복사되었습니다!
The purpose of the annotation @FormatFactories is to define a set of converters at record-level. The provided classes must implement the FormatFactoryInterface interface.
20.4. Supported Datatypes 링크 복사링크가 클립보드에 복사되었습니다!
The DefaultFormatFactory makes formatting of the following datatype available by returning an instance of the interface FormatFactoryInterface based on the provided FormattingOptions:
- BigDecimal
- BigInteger
- Boolean
- Byte
- Character
- Date
- Double
- Enums
- Float
- Integer
- LocalDate
- LocalDateTime
- LocalTime
- Long
- Short
- String
The DefaultFormatFactory can be overridden by providing an instance of FactoryRegistry in the registry in use (e.g. spring or JNDI).
20.5. Using the Java DSL 링크 복사링크가 클립보드에 복사되었습니다!
The next step instantiates the DataFormat bindy class associated with this record type and providing a class as a parameter.
For example the following uses the class BindyCsvDataFormat (which corresponds to the class associated with the CSV record type) which is configured with com.acme.model.MyModel.class to initialize the model objects configured in this package.
DataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
DataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
20.5.1. Setting locale 링크 복사링크가 클립보드에 복사되었습니다!
Bindy supports configuring the locale on the dataformat, such as
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
bindy.setLocale("us");
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
bindy.setLocale("us");
Or to use the platform default locale then use "default" as the locale name.
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
bindy.setLocale("default");
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
bindy.setLocale("default");
20.5.2. Unmarshaling 링크 복사링크가 클립보드에 복사되었습니다!
from("file://inbox")
.unmarshal(bindy)
.to("direct:handleOrders");
from("file://inbox")
.unmarshal(bindy)
.to("direct:handleOrders");
Alternatively, you can use a named reference to a data format which can then be defined in your Registry e.g. your Spring XML file:
from("file://inbox")
.unmarshal("myBindyDataFormat")
.to("direct:handleOrders");
from("file://inbox")
.unmarshal("myBindyDataFormat")
.to("direct:handleOrders");
The Camel route will pick-up files in the inbox directory, unmarshall CSV records into a collection of model objects and send the collection
to the route referenced by handleOrders.
The collection returned is a List of Map objects. Each Map within the list contains the model objects that were marshalled out of each line of the CSV. The reason behind this is that each line can correspond to more than one object. This can be confusing when you simply expect one object to be returned per line.
Each object can be retrieve using its class name.
Assuming that you want to extract a single Order object from this map for processing in a route, you could use a combination of a Splitter and a Processor as per the following:
Take care of the fact that Bindy uses CHARSET_NAME property or the CHARSET_NAME header as define in the Exchange interface to do a characterset conversion of the inputstream received for unmarshalling. In some producers (e.g. file-endpoint) you can define a characterset. The characterset conversion can already been done by this producer. Sometimes you need to remove this property or header from the exchange before sending it to the unmarshal. If you don’t remove it the conversion might be done twice which might lead to unwanted results.
from("file://inbox?charset=Cp922")
.removeProperty(Exchange.CHARSET_NAME)
.unmarshal("myBindyDataFormat")
.to("direct:handleOrders");
from("file://inbox?charset=Cp922")
.removeProperty(Exchange.CHARSET_NAME)
.unmarshal("myBindyDataFormat")
.to("direct:handleOrders");
20.5.3. Marshaling 링크 복사링크가 클립보드에 복사되었습니다!
To generate CSV records from a collection of model objects, you create the following route :
from("direct:handleOrders")
.marshal(bindy)
.to("file://outbox")
from("direct:handleOrders")
.marshal(bindy)
.to("file://outbox")
20.6. Using Spring XML 링크 복사링크가 클립보드에 복사되었습니다!
This is really easy to use Spring as your favorite DSL language to declare the routes to be used for camel-bindy. The following example shows two routes where the first will pick-up records from files, unmarshal the content and bind it to their model. The result is then send to a pojo (doing nothing special) and place them into a queue.
The second route will extract the pojos from the queue and marshal the content to generate a file containing the CSV record.
Spring DSL
Please verify that your model classes implements serializable otherwise the queue manager will raise an error.
20.7. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
To use Bindy in your camel routes you need to add the a dependency on camel-bindy which implements this data format.
If you use maven you could just add the following to your pom.xml, substituting the version number for the latest & greatest release (see the download page for the latest versions).
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-bindy</artifactId>
<version>{CamelSBVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-bindy</artifactId>
<version>{CamelSBVersion}</version>
</dependency>
20.8. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 18 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.dataformat.bindy-csv.allow-empty-stream | Whether to allow empty streams in the unmarshal process. If true, no exception will be thrown when a body without records is provided. | false | Boolean |
| camel.dataformat.bindy-csv.class-type | Name of model class to use. | String | |
| camel.dataformat.bindy-csv.enabled | Whether to enable auto configuration of the bindy-csv data format. This is enabled by default. | Boolean | |
| camel.dataformat.bindy-csv.locale | To configure a default locale to use, such as us for united states. To use the JVM platform default locale then use the name default. | String | |
| camel.dataformat.bindy-csv.type | Whether to use Csv, Fixed, or KeyValue. | String | |
| camel.dataformat.bindy-csv.unwrap-single-instance | When unmarshalling should a single instance be unwrapped and returned instead of wrapped in a java.util.List. | true | Boolean |
| camel.dataformat.bindy-fixed.allow-empty-stream | Whether to allow empty streams in the unmarshal process. If true, no exception will be thrown when a body without records is provided. | false | Boolean |
| camel.dataformat.bindy-fixed.class-type | Name of model class to use. | String | |
| camel.dataformat.bindy-fixed.enabled | Whether to enable auto configuration of the bindy-fixed data format. This is enabled by default. | Boolean | |
| camel.dataformat.bindy-fixed.locale | To configure a default locale to use, such as us for united states. To use the JVM platform default locale then use the name default. | String | |
| camel.dataformat.bindy-fixed.type | Whether to use Csv, Fixed, or KeyValue. | String | |
| camel.dataformat.bindy-fixed.unwrap-single-instance | When unmarshalling should a single instance be unwrapped and returned instead of wrapped in a java.util.List. | true | Boolean |
| camel.dataformat.bindy-kvp.allow-empty-stream | Whether to allow empty streams in the unmarshal process. If true, no exception will be thrown when a body without records is provided. | false | Boolean |
| camel.dataformat.bindy-kvp.class-type | Name of model class to use. | String | |
| camel.dataformat.bindy-kvp.enabled | Whether to enable auto configuration of the bindy-kvp data format. This is enabled by default. | Boolean | |
| camel.dataformat.bindy-kvp.locale | To configure a default locale to use, such as us for united states. To use the JVM platform default locale then use the name default. | String | |
| camel.dataformat.bindy-kvp.type | Whether to use Csv, Fixed, or KeyValue. | String | |
| camel.dataformat.bindy-kvp.unwrap-single-instance | When unmarshalling should a single instance be unwrapped and returned instead of wrapped in a java.util.List. | true | Boolean |
Chapter 21. Browse 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The Browse component provides a simple BrowsableEndpoint which can be useful for testing, visualisation tools or debugging. The exchanges sent to the endpoint are all available to be browsed.
21.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using browse with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-browse-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-browse-starter</artifactId>
</dependency>
21.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
browse:someName[?options]
browse:someName[?options]
Where someName can be any string to uniquely identify the endpoint.
21.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
21.3.1. 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.
21.3.2. 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.
21.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Browse component supports 3 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| 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 |
21.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Browse endpoint is configured using URI syntax:
browse:name
browse:name
with the following path and query parameters:
21.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| name (common) | Required A name which can be any string to uniquely identify the endpoint. | String |
21.5.2. Query Parameters (4 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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:
| ExchangePattern | |
| 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 |
21.6. Sample 링크 복사링크가 클립보드에 복사되었습니다!
In the route below, we insert a browse: component to be able to browse the Exchanges that are passing through:
from("activemq:order.in").to("browse:orderReceived").to("bean:processOrder");
from("activemq:order.in").to("browse:orderReceived").to("bean:processOrder");
We can now inspect the received exchanges from within the Java code:
21.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 4 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.browse.autowired-enabled | 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 |
| camel.component.browse.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.browse.enabled | Whether to enable auto configuration of the browse component. This is enabled by default. | Boolean | |
| camel.component.browse.lazy-start-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 |
Chapter 22. Cassandra CQL 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
Apache Cassandra is an open source NoSQL database designed to handle large amounts on commodity hardware. Like Amazon’s DynamoDB, Cassandra has a peer-to-peer and master-less architecture to avoid single point of failure and garanty high availability. Like Google’s BigTable, Cassandra data is structured using column families which can be accessed through the Thrift RPC API or a SQL-like API called CQL.
This component aims at integrating Cassandra 2.0+ using the CQL3 API (not the Thrift API). It’s based on Cassandra Java Driver provided by DataStax.
22.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using cql with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cassandraql-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-cassandraql-starter</artifactId>
</dependency>
22.2. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
22.2.1. 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.
22.2.2. 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.
22.3. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Cassandra CQL component supports 3 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| 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 |
22.4. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Cassandra CQL endpoint is configured using URI syntax:
cql:beanRef:hosts:port/keyspace
cql:beanRef:hosts:port/keyspace
with the following path and query parameters:
22.4.1. Path Parameters (4 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| beanRef (common) | beanRef is defined using bean:id. | String | |
| hosts (common) | Hostname(s) Cassandra server(s). Multiple hosts can be separated by comma. | String | |
| port (common) | Port number of Cassandra server(s). | Integer | |
| keyspace (common) | Keyspace to use. | String |
22.4.2. Query Parameters (30 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| clusterName (common) | Cluster name. | String | |
| consistencyLevel (common) | Consistency level to use. Enum values:
| DefaultConsistencyLevel | |
| cql (common) | CQL query to perform. Can be overridden with the message header with key CamelCqlQuery. | String | |
| datacenter (common) | Datacenter to use. | datacenter1 | String |
| loadBalancingPolicyClass (common) | To use a specific LoadBalancingPolicyClass. | String | |
| password (common) | Password for session authentication. | String | |
| prepareStatements (common) | Whether to use PreparedStatements or regular Statements. | true | boolean |
| resultSetConversionStrategy (common) | To use a custom class that implements logic for converting ResultSet into message body ALL, ONE, LIMIT_10, LIMIT_100… | ResultSetConversionStrategy | |
| session (common) | To use the Session instance (you would normally not use this option). | CqlSession | |
| username (common) | Username for session authentication. | String | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| sendEmptyMessageWhenIdle (consumer) | If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead. | 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:
| ExchangePattern | |
| pollStrategy (consumer (advanced)) | A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel. | PollingConsumerPollStrategy | |
| 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 |
| backoffErrorThreshold (scheduler) | The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in. | int | |
| backoffIdleThreshold (scheduler) | The number of subsequent idle polls that should happen before the backoffMultipler should kick-in. | int | |
| backoffMultiplier (scheduler) | To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured. | int | |
| delay (scheduler) | Milliseconds before the next poll. | 500 | long |
| greedy (scheduler) | If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages. | false | boolean |
| initialDelay (scheduler) | Milliseconds before the first poll starts. | 1000 | long |
| repeatCount (scheduler) | Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. | 0 | long |
| runLoggingLevel (scheduler) | The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that. Enum values:
| TRACE | LoggingLevel |
| scheduledExecutorService (scheduler) | Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool. | ScheduledExecutorService | |
| scheduler (scheduler) | To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler. | none | Object |
| schedulerProperties (scheduler) | To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. | Map | |
| startScheduler (scheduler) | Whether the scheduler should be auto started. | true | boolean |
| timeUnit (scheduler) | Time unit for initialDelay and delay options. Enum values:
| MILLISECONDS | TimeUnit |
| useFixedDelay (scheduler) | Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details. | true | boolean |
22.5. Endpoint Connection Syntax 링크 복사링크가 클립보드에 복사되었습니다!
The endpoint can initiate the Cassandra connection or use an existing one.
| URI | Description |
|---|---|
|
| Single host, default port, usual for testing |
|
| Multi host, default port |
|
| Multi host, custom port |
|
| Default port and keyspace |
|
| Provided Session reference |
|
| Provided Cluster reference |
To fine tune the Cassandra connection (SSL options, pooling options, load balancing policy, retry policy, reconnection policy…), create your own Cluster instance and give it to the Camel endpoint.
22.6. Messages 링크 복사링크가 클립보드에 복사되었습니다!
22.6.1. Incoming Message 링크 복사링크가 클립보드에 복사되었습니다!
The Camel Cassandra endpoint expects a bunch of simple objects (Object or Object[] or Collection<Object>) which will be bound to the CQL statement as query parameters. If message body is null or empty, then CQL query will be executed without binding parameters.
Headers
CamelCqlQuery(optional,StringorRegularStatement)CQL query either as a plain String or built using the
QueryBuilder.
22.6.2. Outgoing Message 링크 복사링크가 클립보드에 복사되었습니다!
The Camel Cassandra endpoint produces one or many a Cassandra Row objects depending on the resultSetConversionStrategy:
-
List<Row>ifresultSetConversionStrategyisALLorLIMIT_[0-9]+ -
Single` Row` if
resultSetConversionStrategyisONE -
Anything else, if
resultSetConversionStrategyis a custom implementation of theResultSetConversionStrategy
22.7. Repositories 링크 복사링크가 클립보드에 복사되었습니다!
Cassandra can be used to store message keys or messages for the idempotent and aggregation EIP.
Cassandra might not be the best tool for queuing use cases yet, read Cassandra anti-patterns queues and queue like datasets. It’s advised to use LeveledCompaction and a small GC grace setting for these tables to allow tombstoned rows to be removed quickly.
22.8. Idempotent repository 링크 복사링크가 클립보드에 복사되었습니다!
The NamedCassandraIdempotentRepository stores messages keys in a Cassandra table like this:
CAMEL_IDEMPOTENT.cql
This repository implementation uses lightweight transactions (also known as Compare and Set) and requires Cassandra 2.0.7+.
Alternatively, the CassandraIdempotentRepository does not have a NAME column and can be extended to use a different data model.
| Option | Default | Description |
|---|---|---|
|
|
| Table name |
|
|
| Primary key columns |
|
|
Repository name, value used for | |
|
| Key time to live | |
|
|
Consistency level used to insert/delete key: | |
|
|
Consistency level used to read/check key: |
22.9. Aggregation repository 링크 복사링크가 클립보드에 복사되었습니다!
The NamedCassandraAggregationRepository stores exchanges by correlation key in a Cassandra table like this:
CAMEL_AGGREGATION.cql
Alternatively, the CassandraAggregationRepository does not have a NAME column and can be extended to use a different data model.
| Option | Default | Description |
|---|---|---|
|
|
| Table name |
|
|
| Primary key columns |
|
|
| Exchange Id column |
|
|
| Exchange content column |
|
|
Repository name, value used for | |
|
| Exchange time to live | |
|
|
Consistency level used to insert/delete exchange: | |
|
|
Consistency level used to read/check exchange: |
22.10. Examples 링크 복사링크가 클립보드에 복사되었습니다!
To insert something on a table you can use the following code:
String CQL = "insert into camel_user(login, first_name, last_name) values (?, ?, ?)";
from("direct:input")
.to("cql://localhost/camel_ks?cql=" + CQL);
String CQL = "insert into camel_user(login, first_name, last_name) values (?, ?, ?)";
from("direct:input")
.to("cql://localhost/camel_ks?cql=" + CQL);
At this point you should be able to insert data by using a list as body
Arrays.asList("davsclaus", "Claus", "Ibsen")
Arrays.asList("davsclaus", "Claus", "Ibsen")
The same approach can be used for updating or querying the table.
22.11. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 4 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.cql.autowired-enabled | 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 |
| camel.component.cql.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.cql.enabled | Whether to enable auto configuration of the cql component. This is enabled by default. | Boolean | |
| camel.component.cql.lazy-start-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 |
Chapter 23. CICS 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 4.4-redhat
Only producer is supported.
This component allows you to interact with the IBM CICS® general-purpose transaction processing subsystem.
Only synchronous mode call are supported.
23.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using camel-cics with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-cics-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-cics-starter</artifactId>
</dependency>
You must also declare the ctgclient.jar dependency when working with camel-cics starer.
This JAR is provided by IBM and is included in the cics system.
23.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
cics://[interfaceType]/[dataExchangeType][?options]
cics://[interfaceType]/[dataExchangeType][?options]
Where interfaceType is the CICS set of the external API that the camel-cics invokes. At the moment, only ECI (External Call Interface) is supported. This component communicates with the CICS server using two kinds of dataExchangeType.
-
commareais a block of storage, limited to 32763 bytes, allocated by the program. -
channelis the new mechanism for exchanging data, analogous to a parameter list.
By default, if dataExchangeType is not specified, this component uses commarea:
cics://eci?host=xxx&port=xxx...
cics://eci?host=xxx&port=xxx...
To use the channel and the container you must specify it explicitly in the URI
cics://eci/channel?host=xxx&port=xxx...
cics://eci/channel?host=xxx&port=xxx...
23.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
23.3.1. 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.
23.3.2. 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.
23.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The CICS component supports 17 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| ctgDebug | Enable debug mode on the underlying IBM CGT client. | false | java.lang.Boolean |
| eciBinding | The Binding instance to transform a Camel Exchange to EciRequest and vice versa | com.redhat.camel.component.cics.CICSEciBinding | |
| eciTimeout | The ECI timeout value associated with this ECIRequest object. An ECI timeout value of zero indicates that this ECIRequest will not be timed out by CICS Transaction Gateway. An ECI timeout value greater than zero indicates that the ECIRequest may be timed out by CICS Transaction Gateway. ECI timeout can expire before a response is received from CICS. This means that the client does not receive the confirmation from CICS that a unit of work has been backed out or committed. | 0 | short |
| encoding | The transfer encoding of the message. | Cp1145 | java.lang.String |
| gatewayFactory | The connection factory to be used | com.redhat.camel.component.cics.pool.CICSGatewayFactory | |
| host | The address of the CICS Transaction Gateway that this instance connects to | java.lang.String | |
| lazyStartProducer | 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. | boolean | |
| port | The port of the CICS Transaction Gateway that this instance connects to. | 2006 | int |
| protocol | the protocol that this component will use to connect to the CICS Transaction Gateway. | tcp | java.lang.String |
| server | The address of the CICS server that this instance connects to. | java.lang.String | |
| sslKeyring | The full classname of the SSL key ring class or keystore file to be used for the client encrypted connection. | java.lang.String | |
| sslPassword | The password for the encrypted key ring class or keystore | java.lang.String | |
| configuration | To use a shared CICS configuration | com.redhat.camel.component.cics.CICSConfiguration | |
| socketConnectionTimeout | The socket connection timeout | int | |
| password | Password to use for authentication | java.lang.String | |
| userId | User ID to use for authentication | java.lang.String |
23.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The CICS endpoint is configured using URI syntax:
cics://[interfaceType]/[dataExchangeType][?options]
cics://[interfaceType]/[dataExchangeType][?options]
With the following path and query parameters:
23.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| interfaceType | The interface type, can be eci, esi or epi. at the moment only eci is supported. | eci | java.lang.String |
| dataExchangeType | The kind of data exchange to use Enum value:
| commarea | com.redhat.camel.component.cics.support.CICSDataExchangeType |
23.5.2. Query Parameters (15 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| ctgDebug | Enable debug mode on the underlying IBM CGT client. | false | java.lang.Boolean |
| eciBinding | The Binding instance to transform a Camel Exchange to EciRequest and vice versa | com.redhat.camel.component.cics.CICSEciBinding | |
| eciTimeout | The ECI timeout value associated with this ECIRequest object. An ECI timeout value of zero indicates that this ECIRequest will not be timed out by CICS Transaction Gateway. An ECI timeout value greater than zero indicates that the ECIRequest may be timed out by CICS Transaction Gateway. ECI timeout can expire before a response is received from CICS. This means that the client does not receive the confirmation from CICS that a unit of work has been backed out or committed. | 0 | short |
| encoding | Encoding to convert COMMAREA data to before sending. | Cp1145 | java.lang.String |
| gatewayFactory | The connection factory to use | com.redhat.camel.component.cics.pool.CICSGatewayFactory | |
| host | The address of the CICS Transaction Gateway that this instance connects to | localhost | java.lang.String |
| port | The port of the CICS Transaction Gateway that this instance connects to. | 2006 | int |
| protocol | the protocol that this component will use to connect to the CICS Transaction Gateway. | tcp | java.lang.String |
| server | The address of the CICS server that this instance connects to | java.lang.String | |
| lazyStartProducer | 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. | boolean | |
| sslKeyring | The full class name of the SSL key ring class or keystore file to be used for the client encrypted connection | java.lang.String | |
| sslPassword | The password for the encrypted key ring class or keystore | java.lang.String | |
| socketConnectionTimeout | The socket connection timeout | int | |
| password | Password to use for authentication | java.lang.String | |
| userId | User ID to use for authentication | java.lang.String |
23.6. Message Headers 링크 복사링크가 클립보드에 복사되었습니다!
The CICS component supports 15 message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
|
CICS_RETURN_CODE | Return code from this flow operation. | int | |
|
CICS_RETURN_CODE_STRING | The CICS return code as a String. The String is the name of the appropriate Java constant, for example, if this header is ECI_NO_ERROR, then the String returned will be ECI_NO_ERROR. If this header is unknown then the String returned will be ECI_UNKNOWN_CICS_RC. Note For CICS return codes that may have more than one meaning the String returned is a concatenation of the return codes. The only concatenated String is: ECI_ERR_REQUEST_TIMEOUT_OR_ERR_NO_REPLY. | java.ang.String | |
|
CICS_EXTEND_MODE | Extend mode of request. The default value is ECI_NO_EXTEND. | int | |
|
CICS_LUW_TOKEN | Extended Logical Unit of Work token. The default value is ECI_LUW_NEW. | int | |
|
CICS_PROGRAM_NAME | Program to invoke on CICS server. | java.lang.String | |
|
CICS_TRANSACTION_ID | Transaction ID to run CICS program under. | java.lang.String | |
|
CICS_COMM_AREA_SIZE | Length of COMMAREA. The default value is 0. | int | |
|
CICS_CHANNEL_NAME | The name of the channel to create com.redhat.camel.component.cics.CICSConstants#CICS_CHANNEL_NAME_HEADER | java.lang.String | |
|
CICS_CONTAINER_NAME | The name of the container to create. | java.lang.String | |
|
CICS_CHANNEL_CCSID | The CCSID the channel should set as its default. | int | |
|
CICS_SERVER | CICS server to direct request to. This header overrides the value configured in the endpoint. | java.lang.String | |
|
CICS_USER_ID | User ID for CICS server. This header overrides the value configured in the endpoint. | java.lang.String | |
|
CICS_PASSWORD | Password or password phrase for CICS server. This header overrides the value configured in the endpoint. | java.lang.String | |
|
CICS_ABEND_CODE | CICS transaction abend code. | java.lang.String | |
|
CICS_ECI_REQUEST_TIMEOUT | The value, in seconds, of the ECI timeout for the current ECIRequest. A value of zero indicates that this ECIRequest will not be timed out by CICS Transaction Gateway | 0 | short |
|
CICS_ENCODING | Encoding to convert COMMAREA data to before sending. | String |
23.7. Samples 링크 복사링크가 클립보드에 복사되었습니다!
23.7.1. Using Commarea 링크 복사링크가 클립보드에 복사되었습니다!
Following sample show how to configure a route that runs a program on a CICS server using COMMAREA. The COMMAREA size has to be defined in CICS_COMM_AREA_SIZE header, while the COMMAREA input data is defined in the Camel Exchange body.
You must create a COMMAREA that is large enough to contain all the information to be sent to the server and large enough to contain all the information that can be returned from the server.
The Outcome of the CICS program invocation is mapped to Camel Exchange in this way:
-
The numeric value of return code is stored in the
CICS_RETURN_CODEheader - The COMMAREA output data is stored in the Camel Exchange Body.
23.7.2. Using Channel with a single input container 링크 복사링크가 클립보드에 복사되었습니다!
Following sample shows how to use a channel with a single container to run a CICS program. The channel name and the container name are taken from headers, and the container value from the body:
The container(s) returned is stored in an java.util.Map<String,Object>, the key is the container name and the value is the output data of the container.
23.7.3. Using Channel with multiple input container 링크 복사링크가 클립보드에 복사되었습니다!
If you need to run a CICS program that takes multiple container as input, you can create a java.util.Map<String,Object> where the keys are the container names and the values are the input data. In this case the CICS_CONTAINER_NAME header is ignored.
23.8. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 17 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.cics.binding | The Binding instance to transform a Camel Exchange to EciRequest and vice versa. | com.redhat.camel.component.cics.CICSEciBinding | |
| camel.component.cics.configuration | Configuration. | com.redhat.camel.component.cics.CICSConfiguration | |
| camel.component.cics.ctg-debug | Enable debug mode on the underlying IBM CGT client. | java.lang.Boolean | |
| camel.component.cics.eci-timeout | The ECI timeout value associated with this ECIRequest object. An ECI timeout value of zero indicates that this ECIRequest will not be timed out by CICS Transaction Gateway. An ECI timeout value greater than zero indicates that the ECIRequest may be timed out by CICS Transaction Gateway. ECI timeout can expire before a response is received from CICS. This means that the client does not receive the confirmation from CICS that a unit of work has been backed out or committed. | java.lang.Short | |
| camel.component.cics.enabled | Whether to enable auto configuration of the cics component. This is enabled by default. | java.lang.Boolean | |
| camel.component.cics.encoding | The transfer encoding of the message. | Cp1145 | java.lang.String |
| camel.component.cics.gateway-factory | The connection factory to be use. The option is a com.redhat.camel.component.cics.pool.CICSGatewayFactory type. | com.redhat.camel.component.cics.pool.CICSGatewayFactory | |
| camel.component.cics.host | The address of the CICS Transaction Gateway that this instance connects to | java.lang.String | |
| camel.component.cics.lazy-start-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. | java.lang.Boolean | |
| camel.component.cics.password | Password to use for authentication | java.lang.String | |
| camel.component.cics.port | The port of the CICS Transaction Gateway that this instance connects to. | 2006 | java.lang.Integer |
| camel.component.cics.protocol | the protocol that this component will use to connect to the CICS Transaction Gateway. | tcp | java.lang.String |
| camel.component.cics.server | The address of the CICS server that this instance connects to | java.lang.String | |
| camel.component.cics.socket-connection-timeout | The socket connection timeout | java.lang.Integer | |
| camel.component.cics.ssl-keyring | The full classname of the SSL key ring class or keystore file to be used for the client encrypted connection | java.lang.String | |
| camel.component.cics.ssl-password | The password for the encrypted key ring class or keystore | java.lang.String | |
| camel.component.cics.user-id | User ID to use for authentication | java.lang.String |
Chapter 24. Constant 링크 복사링크가 클립보드에 복사되었습니다!
The Constant Expression Language is really just a way to use a constant value or object.
This is a fixed constant value (or object) that is only set once during starting up the route, do not use this if you want dynamic values during routing.
24.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using constant with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-core-starter</artifactId>
</dependency>
24.2. Constant Options 링크 복사링크가 클립보드에 복사되었습니다!
The Constant language supports 2 options, which are listed below.
| Name | Default | Java Type | Description |
|---|---|---|---|
| resultType |
| Sets the class name of the constant type. | |
| trim |
| Whether to trim the value to remove leading and trailing whitespaces and line breaks. |
24.3. Example 링크 복사링크가 클립보드에 복사되었습니다!
The setHeader EIP can utilize a constant expression like:
in this case, the message coming from the seda:a endpoint will have the header with key theHeader set its value as the value (string type).
And the same example using Java DSL:
from("seda:a")
.setHeader("theHeader", constant("the value"))
.to("mock:b");
from("seda:a")
.setHeader("theHeader", constant("the value"))
.to("mock:b");
24.3.1. Specifying type of value 링크 복사링크가 클립보드에 복사되었습니다!
The option resultType can be used to specify the type of the value, when the value is given as a String value, which happens when using XML or YAML DSL:
For example to set a header with int type you can do:
24.4. Loading constant from external resource 링크 복사링크가 클립보드에 복사되었습니다!
You can externalize the constant and have Camel load it from a resource such as "classpath:", "file:", or "http:".
This is done using the following syntax: "resource:scheme:location", eg to refer to a file on the classpath you can do:
.setHeader("myHeader").constant("resource:classpath:constant.txt")
.setHeader("myHeader").constant("resource:classpath:constant.txt")
24.5. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
The Constant language is part of camel-core.
24.6. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 147 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.cloud.consul.service-discovery.acl-token | Sets the ACL token to be used with Consul. | String | |
| camel.cloud.consul.service-discovery.block-seconds | The seconds to wait for a watch event, default 10 seconds. | 10 | Integer |
| camel.cloud.consul.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.consul.service-discovery.connect-timeout-millis | Connect timeout for OkHttpClient. | Long | |
| camel.cloud.consul.service-discovery.datacenter | The data center. | String | |
| camel.cloud.consul.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.consul.service-discovery.password | Sets the password to be used for basic authentication. | String | |
| camel.cloud.consul.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.consul.service-discovery.read-timeout-millis | Read timeout for OkHttpClient. | Long | |
| camel.cloud.consul.service-discovery.url | The Consul agent URL. | String | |
| camel.cloud.consul.service-discovery.user-name | Sets the username to be used for basic authentication. | String | |
| camel.cloud.consul.service-discovery.write-timeout-millis | Write timeout for OkHttpClient. | Long | |
| camel.cloud.dns.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.dns.service-discovery.domain | The domain name;. | String | |
| camel.cloud.dns.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.dns.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.dns.service-discovery.proto | The transport protocol of the desired service. | _tcp | String |
| camel.cloud.etcd.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.etcd.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.etcd.service-discovery.password | The password to use for basic authentication. | String | |
| camel.cloud.etcd.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.etcd.service-discovery.service-path | The path to look for for service discovery. | /services/ | String |
| camel.cloud.etcd.service-discovery.timeout | To set the maximum time an action could take to complete. | Long | |
| camel.cloud.etcd.service-discovery.type | To set the discovery type, valid values are on-demand and watch. | on-demand | String |
| camel.cloud.etcd.service-discovery.uris | The URIs the client can connect to. | String | |
| camel.cloud.etcd.service-discovery.user-name | The user name to use for basic authentication. | String | |
| camel.cloud.kubernetes.service-discovery.api-version | Sets the API version when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.ca-cert-data | Sets the Certificate Authority data when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.ca-cert-file | Sets the Certificate Authority data that are loaded from the file when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-cert-data | Sets the Client Certificate data when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-cert-file | Sets the Client Certificate data that are loaded from the file when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-algo | Sets the Client Keystore algorithm, such as RSA when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-data | Sets the Client Keystore data when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-file | Sets the Client Keystore data that are loaded from the file when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-passphrase | Sets the Client Keystore passphrase when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.kubernetes.service-discovery.dns-domain | Sets the DNS domain to use for DNS lookup. | String | |
| camel.cloud.kubernetes.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.kubernetes.service-discovery.lookup | How to perform service lookup. Possible values: client, dns, environment. When using client, then the client queries the kubernetes master to obtain a list of active pods that provides the service, and then random (or round robin) select a pod. When using dns the service name is resolved as name.namespace.svc.dnsDomain. When using dnssrv the service name is resolved with SRV query for .…svc… When using environment then environment variables are used to lookup the service. By default environment is used. | environment | String |
| camel.cloud.kubernetes.service-discovery.master-url | Sets the URL to the master when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.namespace | Sets the namespace to use. Will by default use namespace from the ENV variable KUBERNETES_MASTER. | String | |
| camel.cloud.kubernetes.service-discovery.oauth-token | Sets the OAUTH token for authentication (instead of username/password) when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.password | Sets the password for authentication when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.port-name | Sets the Port Name to use for DNS/DNSSRV lookup. | String | |
| camel.cloud.kubernetes.service-discovery.port-protocol | Sets the Port Protocol to use for DNS/DNSSRV lookup. | String | |
| camel.cloud.kubernetes.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.kubernetes.service-discovery.trust-certs | Sets whether to turn on trust certificate check when using client lookup. | false | Boolean |
| camel.cloud.kubernetes.service-discovery.username | Sets the username for authentication when using client lookup. | String | |
| camel.cloud.ribbon.load-balancer.client-name | Sets the Ribbon client name. | String | |
| camel.cloud.ribbon.load-balancer.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.ribbon.load-balancer.enabled | Enable the component. | true | Boolean |
| camel.cloud.ribbon.load-balancer.namespace | The namespace. | String | |
| camel.cloud.ribbon.load-balancer.password | The password. | String | |
| camel.cloud.ribbon.load-balancer.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.ribbon.load-balancer.username | The username. | String | |
| camel.hystrix.allow-maximum-size-to-diverge-from-core-size | Allows the configuration for maximumSize to take effect. That value can then be equal to, or higher, than coreSize. | false | Boolean |
| camel.hystrix.circuit-breaker-enabled | Whether to use a HystrixCircuitBreaker or not. If false no circuit-breaker logic will be used and all requests permitted. This is similar in effect to circuitBreakerForceClosed() except that continues tracking metrics and knowing whether it should be open/closed, this property results in not even instantiating a circuit-breaker. | true | Boolean |
| camel.hystrix.circuit-breaker-error-threshold-percentage | Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. It will stay tripped for the duration defined in circuitBreakerSleepWindowInMilliseconds; The error percentage this is compared against comes from HystrixCommandMetrics.getHealthCounts(). | 50 | Integer |
| camel.hystrix.circuit-breaker-force-closed | If true the HystrixCircuitBreaker#allowRequest() will always return true to allow requests regardless of the error percentage from HystrixCommandMetrics.getHealthCounts(). The circuitBreakerForceOpen() property takes precedence so if it set to true this property does nothing. | false | Boolean |
| camel.hystrix.circuit-breaker-force-open | If true the HystrixCircuitBreaker.allowRequest() will always return false, causing the circuit to be open (tripped) and reject all requests. This property takes precedence over circuitBreakerForceClosed();. | false | Boolean |
| camel.hystrix.circuit-breaker-request-volume-threshold | Minimum number of requests in the metricsRollingStatisticalWindowInMilliseconds() that must exist before the HystrixCircuitBreaker will trip. If below this number the circuit will not trip regardless of error percentage. | 20 | Integer |
| camel.hystrix.circuit-breaker-sleep-window-in-milliseconds | The time in milliseconds after a HystrixCircuitBreaker trips open that it should wait before trying requests again. | 5000 | Integer |
| camel.hystrix.configurations | Define additional configuration definitions. | Map | |
| camel.hystrix.core-pool-size | Core thread-pool size that gets passed to java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int). | 10 | Integer |
| camel.hystrix.enabled | Enable the component. | true | Boolean |
| camel.hystrix.execution-isolation-semaphore-max-concurrent-requests | Number of concurrent requests permitted to HystrixCommand.run(). Requests beyond the concurrent limit will be rejected. Applicable only when executionIsolationStrategy == SEMAPHORE. | 20 | Integer |
| camel.hystrix.execution-isolation-strategy | What isolation strategy HystrixCommand.run() will be executed with. If THREAD then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. If SEMAPHORE then it will be executed on the calling thread and concurrent requests limited by the semaphore count. | THREAD | String |
| camel.hystrix.execution-isolation-thread-interrupt-on-timeout | Whether the execution thread should attempt an interrupt (using Future#cancel ) when a thread times out. Applicable only when executionIsolationStrategy() == THREAD. | true | Boolean |
| camel.hystrix.execution-timeout-enabled | Whether the timeout mechanism is enabled for this command. | true | Boolean |
| camel.hystrix.execution-timeout-in-milliseconds | Time in milliseconds at which point the command will timeout and halt execution. If executionIsolationThreadInterruptOnTimeout == true and the command is thread-isolated, the executing thread will be interrupted. If the command is semaphore-isolated and a HystrixObservableCommand, that command will get unsubscribed. | 1000 | Integer |
| camel.hystrix.fallback-enabled | Whether HystrixCommand.getFallback() should be attempted when failure occurs. | true | Boolean |
| camel.hystrix.fallback-isolation-semaphore-max-concurrent-requests | Number of concurrent requests permitted to HystrixCommand.getFallback(). Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. | 10 | Integer |
| camel.hystrix.group-key | Sets the group key to use. The default value is CamelHystrix. | CamelHystrix | String |
| camel.hystrix.keep-alive-time | Keep-alive time in minutes that gets passed to ThreadPoolExecutor#setKeepAliveTime(long,TimeUnit). | 1 | Integer |
| camel.hystrix.max-queue-size | Max queue size that gets passed to BlockingQueue in HystrixConcurrencyStrategy.getBlockingQueue(int) This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. For that, use queueSizeRejectionThreshold(). | -1 | Integer |
| camel.hystrix.maximum-size | Maximum thread-pool size that gets passed to ThreadPoolExecutor#setMaximumPoolSize(int) . This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize. | 10 | Integer |
| camel.hystrix.metrics-health-snapshot-interval-in-milliseconds | Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect HystrixCircuitBreaker.isOpen() status. On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. | 500 | Integer |
| camel.hystrix.metrics-rolling-percentile-bucket-size | Maximum number of values stored in each bucket of the rolling percentile. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | 10 | Integer |
| camel.hystrix.metrics-rolling-percentile-enabled | Whether percentile metrics should be captured using HystrixRollingPercentile inside HystrixCommandMetrics. | true | Boolean |
| camel.hystrix.metrics-rolling-percentile-window-buckets | Number of buckets the rolling percentile window is broken into. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | 6 | Integer |
| camel.hystrix.metrics-rolling-percentile-window-in-milliseconds | Duration of percentile rolling window in milliseconds. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | 10000 | Integer |
| camel.hystrix.metrics-rolling-statistical-window-buckets | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside HystrixCommandMetrics. | 10 | Integer |
| camel.hystrix.metrics-rolling-statistical-window-in-milliseconds | This property sets the duration of the statistical rolling window, in milliseconds. This is how long metrics are kept for the thread pool. The window is divided into buckets and rolls by those increments. | 10000 | Integer |
| camel.hystrix.queue-size-rejection-threshold | Queue size rejection threshold is an artificial max size at which rejections will occur even if maxQueueSize has not been reached. This is done because the maxQueueSize of a BlockingQueue can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. This is used by HystrixCommand when queuing a thread for execution. | 5 | Integer |
| camel.hystrix.request-log-enabled | Whether HystrixCommand execution and events should be logged to HystrixRequestLog. | true | Boolean |
| camel.hystrix.thread-pool-key | Sets the thread pool key to use. Will by default use the same value as groupKey has been configured to use. | CamelHystrix | String |
| camel.hystrix.thread-pool-rolling-number-statistical-window-buckets | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | 10 | Integer |
| camel.hystrix.thread-pool-rolling-number-statistical-window-in-milliseconds | Duration of statistical rolling window in milliseconds. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | 10000 | Integer |
| camel.language.constant.enabled | Whether to enable auto configuration of the constant language. This is enabled by default. | Boolean | |
| camel.language.constant.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.csimple.enabled | Whether to enable auto configuration of the csimple language. This is enabled by default. | Boolean | |
| camel.language.csimple.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.exchangeproperty.enabled | Whether to enable auto configuration of the exchangeProperty language. This is enabled by default. | Boolean | |
| camel.language.exchangeproperty.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.file.enabled | Whether to enable auto configuration of the file language. This is enabled by default. | Boolean | |
| camel.language.file.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.header.enabled | Whether to enable auto configuration of the header language. This is enabled by default. | Boolean | |
| camel.language.header.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.ref.enabled | Whether to enable auto configuration of the ref language. This is enabled by default. | Boolean | |
| camel.language.ref.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.simple.enabled | Whether to enable auto configuration of the simple language. This is enabled by default. | Boolean | |
| camel.language.simple.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.tokenize.enabled | Whether to enable auto configuration of the tokenize language. This is enabled by default. | Boolean | |
| camel.language.tokenize.group-delimiter | Sets the delimiter to use when grouping. If this has not been set then token will be used as the delimiter. | String | |
| camel.language.tokenize.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.resilience4j.automatic-transition-from-open-to-half-open-enabled | Enables automatic transition from OPEN to HALF_OPEN state once the waitDurationInOpenState has passed. | false | Boolean |
| camel.resilience4j.circuit-breaker-ref | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | String | |
| camel.resilience4j.config-ref | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreakerConfig instance to lookup and use from the registry. | String | |
| camel.resilience4j.configurations | Define additional configuration definitions. | Map | |
| camel.resilience4j.enabled | Enable the component. | true | Boolean |
| camel.resilience4j.failure-rate-threshold | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | Float | |
| camel.resilience4j.minimum-number-of-calls | Configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate. For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed. Default minimumNumberOfCalls is 100. | 100 | Integer |
| camel.resilience4j.permitted-number-of-calls-in-half-open-state | Configures the number of permitted calls when the CircuitBreaker is half open. The size must be greater than 0. Default size is 10. | 10 | Integer |
| camel.resilience4j.sliding-window-size | Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. slidingWindowSize configures the size of the sliding window. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. The slidingWindowSize must be greater than 0. The minimumNumberOfCalls must be greater than 0. If the slidingWindowType is COUNT_BASED, the minimumNumberOfCalls cannot be greater than slidingWindowSize . If the slidingWindowType is TIME_BASED, you can pick whatever you want. Default slidingWindowSize is 100. | 100 | Integer |
| camel.resilience4j.sliding-window-type | Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. Default slidingWindowType is COUNT_BASED. | COUNT_BASED | String |
| camel.resilience4j.slow-call-duration-threshold | Configures the duration threshold (seconds) above which calls are considered as slow and increase the slow calls percentage. Default value is 60 seconds. | 60 | Integer |
| camel.resilience4j.slow-call-rate-threshold | Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold Duration. When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 100 percentage which means that all recorded calls must be slower than slowCallDurationThreshold. | Float | |
| camel.resilience4j.wait-duration-in-open-state | Configures the wait duration (in seconds) which specifies how long the CircuitBreaker should stay open, before it switches to half open. Default value is 60 seconds. | 60 | Integer |
| camel.resilience4j.writable-stack-trace-enabled | Enables writable stack traces. When set to false, Exception.getStackTrace returns a zero length array. This may be used to reduce log spam when the circuit breaker is open as the cause of the exceptions is already known (the circuit breaker is short-circuiting calls). | true | Boolean |
| camel.rest.api-component | The name of the Camel component to use as the REST API (such as swagger) If no API Component has been explicit configured, then Camel will lookup if there is a Camel component responsible for servicing and generating the REST API documentation, or if a org.apache.camel.spi.RestApiProcessorFactory is registered in the registry. If either one is found, then that is being used. | String | |
| camel.rest.api-context-path | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | String | |
| camel.rest.api-context-route-id | Sets the route id to use for the route that services the REST API. The route will by default use an auto assigned route id. | String | |
| camel.rest.api-host | To use an specific hostname for the API documentation (eg swagger) This can be used to override the generated host with this configured hostname. | String | |
| camel.rest.api-property | Allows to configure as many additional properties for the api documentation (swagger). For example set property api.title to my cool stuff. | Map | |
| camel.rest.api-vendor-extension | Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids, class names etc. Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. | false | Boolean |
| camel.rest.binding-mode | Sets the binding mode to use. The default value is off. | RestBindingMode | |
| camel.rest.client-request-validation | Whether to enable validation of the client request to check whether the Content-Type and Accept headers from the client is supported by the Rest-DSL configuration of its consumes/produces settings. This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. The default value is false. | false | Boolean |
| camel.rest.component | The Camel Rest component to use for the REST transport (consumer), such as netty-http, jetty, servlet, undertow. If no component has been explicit configured, then Camel will lookup if there is a Camel component that integrates with the Rest DSL, or if a org.apache.camel.spi.RestConsumerFactory is registered in the registry. If either one is found, then that is being used. | String | |
| camel.rest.component-property | Allows to configure as many additional properties for the rest component in use. | Map | |
| camel.rest.consumer-property | Allows to configure as many additional properties for the rest consumer in use. | Map | |
| camel.rest.context-path | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | String | |
| camel.rest.cors-headers | Allows to configure custom CORS headers. | Map | |
| camel.rest.data-format-property | Allows to configure as many additional properties for the data formats in use. For example set property prettyPrint to true to have json outputted in pretty mode. The properties can be prefixed to denote the option is only for either JSON or XML and for either the IN or the OUT. The prefixes are: json.in. json.out. xml.in. xml.out. For example a key with value xml.out.mustBeJAXBElement is only for the XML data format for the outgoing. A key without a prefix is a common key for all situations. | Map | |
| camel.rest.enable-cors | Whether to enable CORS headers in the HTTP response. The default value is false. | false | Boolean |
| camel.rest.endpoint-property | Allows to configure as many additional properties for the rest endpoint in use. | Map | |
| camel.rest.host | The hostname to use for exposing the REST service. | String | |
| camel.rest.host-name-resolver | If no hostname has been explicit configured, then this resolver is used to compute the hostname the REST service will be using. | RestHostNameResolver | |
| camel.rest.json-data-format | Name of specific json data format to use. By default json-jackson will be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | String | |
| camel.rest.port | The port number to use for exposing the REST service. Notice if you use servlet component then the port number configured here does not apply, as the port number in use is the actual port number the servlet component is using. eg if using Apache Tomcat its the tomcat http port, if using Apache Karaf its the HTTP service in Karaf that uses port 8181 by default etc. Though in those situations setting the port number here, allows tooling and JMX to know the port number, so its recommended to set the port number to the number that the servlet engine uses. | String | |
| camel.rest.producer-api-doc | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-swagger-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | String | |
| camel.rest.producer-component | Sets the name of the Camel component to use as the REST producer. | String | |
| camel.rest.scheme | The scheme to use for exposing the REST service. Usually http or https is supported. The default value is http. | String | |
| camel.rest.skip-binding-on-error-code | Whether to skip binding on output if there is a custom HTTP error code header. This allows to build custom error messages that do not bind to json / xml etc, as success messages otherwise will do. | false | Boolean |
| camel.rest.use-x-forward-headers | Whether to use X-Forward headers for Host and related setting. The default value is true. | true | Boolean |
| camel.rest.xml-data-format | Name of specific XML data format to use. By default jaxb will be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | String | |
| camel.rest.api-context-id-pattern | Deprecated Sets an CamelContext id pattern to only allow Rest APIs from rest services within CamelContext’s which name matches the pattern. The pattern name refers to the CamelContext name, to match on the current CamelContext only. For any other value, the pattern uses the rules from PatternHelper#matchPattern(String,String). | String | |
| camel.rest.api-context-listing | Deprecated Sets whether listing of all available CamelContext’s with REST services in the JVM is enabled. If enabled it allows to discover these contexts, if false then only the current CamelContext is in use. | false | Boolean |
Chapter 25. Control Bus 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The Control Bus from the EIP patterns allows for the integration system to be monitored and managed from within the framework.
Use a Control Bus to manage an enterprise integration system. The Control Bus uses the same messaging mechanism used by the application data, but uses separate channels to transmit data that is relevant to the management of components involved in the message flow.
In Camel you can manage and monitor using JMX, or by using a Java API from the CamelContext, or from the org.apache.camel.api.management package, or use the event notifier which has an example here.
The ControlBus component provides easy management of Camel applications based on the Control Bus EIP pattern. For example, by sending a message to an Endpoint you can control the lifecycle of routes, or gather performance statistics.
controlbus:command[?options]
controlbus:command[?options]
Where command can be any string to identify which type of command to use.
25.1. Commands 링크 복사링크가 클립보드에 복사되었습니다!
| Command | Description |
|---|---|
|
|
To control routes using the |
|
| Allows you to specify a to use for evaluating the message body. If there is any result from the evaluation, then the result is put in the message body. |
25.2. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using controlbus with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-controlbus-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-controlbus-starter</artifactId>
</dependency>
25.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
25.3.1. 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.
25.3.2. 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.
25.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Control Bus component supports 2 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| 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 |
25.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Control Bus endpoint is configured using URI syntax:
controlbus:command:language
controlbus:command:language
with the following path and query parameters:
25.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| command (producer) | Required Command can be either route or language. Enum values:
| String | |
| language (producer) | Allows you to specify the name of a Language to use for evaluating the message body. If there is any result from the evaluation, then the result is put in the message body. Enum values:
| Language |
25.5.1.1. Query Parameters (6 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| action (producer) | To denote an action that can be either: start, stop, or status. To either start or stop a route, or to get the status of the route as output in the message body. You can use suspend and resume from Camel 2.11.1 onwards to either suspend or resume a route. And from Camel 2.11.1 onwards you can use stats to get performance statics returned in XML format; the routeId option can be used to define which route to get the performance stats for, if routeId is not defined, then you get statistics for the entire CamelContext. The restart action will restart the route. Enum values:
| String | |
| async (producer) | Whether to execute the control bus task asynchronously. Important: If this option is enabled, then any result from the task is not set on the Exchange. This is only possible if executing tasks synchronously. | 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 |
| loggingLevel (producer) | Logging level used for logging when task is done, or if any exceptions occurred during processing the task. Enum values:
| INFO | LoggingLevel |
| restartDelay (producer) | The delay in millis to use when restarting a route. | 1000 | int |
| routeId (producer) | To specify a route by its id. The special keyword current indicates the current route. | String |
25.6. Using route command 링크 복사링크가 클립보드에 복사되었습니다!
The route command allows you to do common tasks on a given route very easily, for example to start a route, you can send an empty message to this endpoint:
template.sendBody("controlbus:route?routeId=foo&action=start", null);
template.sendBody("controlbus:route?routeId=foo&action=start", null);
To get the status of the route, you can do:
String status = template.requestBody("controlbus:route?routeId=foo&action=status", null, String.class);
String status = template.requestBody("controlbus:route?routeId=foo&action=status", null, String.class);
25.7. Getting performance statistics 링크 복사링크가 클립보드에 복사되었습니다!
This requires JMX to be enabled (is by default) then you can get the performance statistics per route, or for the CamelContext. For example to get the statistics for a route named foo, we can do:
String xml = template.requestBody("controlbus:route?routeId=foo&action=stats", null, String.class);
String xml = template.requestBody("controlbus:route?routeId=foo&action=stats", null, String.class);
The returned statistics is in XML format. Its the same data you can get from JMX with the dumpRouteStatsAsXml operation on the ManagedRouteMBean.
To get statistics for the entire CamelContext you just omit the routeId parameter as shown below:
String xml = template.requestBody("controlbus:route?action=stats", null, String.class);
String xml = template.requestBody("controlbus:route?action=stats", null, String.class);
25.8. Using Simple language 링크 복사링크가 클립보드에 복사되었습니다!
You can use the Simple language with the control bus, for example to stop a specific route, you can send a message to the "controlbus:language:simple" endpoint containing the following message:
template.sendBody("controlbus:language:simple", "${camelContext.getRouteController().stopRoute('myRoute')}");
template.sendBody("controlbus:language:simple", "${camelContext.getRouteController().stopRoute('myRoute')}");
As this is a void operation, no result is returned. However, if you want the route status you can do:
String status = template.requestBody("controlbus:language:simple", "${camelContext.getRouteStatus('myRoute')}", String.class);
String status = template.requestBody("controlbus:language:simple", "${camelContext.getRouteStatus('myRoute')}", String.class);
It’s easier to use the route command to control lifecycle of routes. The language command allows you to execute a language script that has stronger powers such as Groovy or to some extend the Simple language.
For example to shutdown Camel itself you can do:
template.sendBody("controlbus:language:simple?async=true", "${camelContext.stop()}");
template.sendBody("controlbus:language:simple?async=true", "${camelContext.stop()}");
We use async=true to stop Camel asynchronously as otherwise we would be trying to stop Camel while it was in-flight processing the message we sent to the control bus component.
You can also use other languages such as Groovy, etc.
25.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 3 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.controlbus.autowired-enabled | 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 |
| camel.component.controlbus.enabled | Whether to enable auto configuration of the controlbus component. This is enabled by default. | Boolean | |
| camel.component.controlbus.lazy-start-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 |
Chapter 26. Cron 링크 복사링크가 클립보드에 복사되었습니다!
Only consumer is supported
The Cron component is a generic interface component that allows triggering events at specific time interval specified using the Unix cron syntax (e.g. 0/2 * * * * ? to trigger an event every two seconds).
Being an interface component, the Cron component does not contain a default implementation, instead it requires that the users plug the implementation of their choice.
The following standard Camel components support the Cron endpoints:
- Camel-quartz
- Camel-spring
The Cron component is also supported in Camel K, which can use the Kubernetes scheduler to trigger the routes when required by the cron expression. Camel K does not require additional libraries to be plugged when using cron expressions compatible with Kubernetes cron syntax.
26.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using cron with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cron-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-cron-starter</artifactId>
</dependency>
Additional libraries may be needed in order to plug a specific implementation.
26.2. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
26.2.1. 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.
26.2.2. 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.
26.3. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Cron component supports 3 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| 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 |
| cronService (advanced) | The id of the CamelCronService to use when multiple implementations are provided. | String |
26.4. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Cron endpoint is configured using URI syntax:
cron:name
cron:name
with the following path and query parameters:
26.4.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| name (consumer) | Required The name of the cron trigger. | String |
26.4.2. Query Parameters (4 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| schedule (consumer) | Required A cron expression that will be used to generate events. | String | |
| 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:
| ExchangePattern |
26.5. Usage 링크 복사링크가 클립보드에 복사되었습니다!
The component can be used to trigger events at specified times, as in the following example:
from("cron:tab?schedule=0/1+*+*+*+*+?")
.setBody().constant("event")
.log("${body}");
from("cron:tab?schedule=0/1+*+*+*+*+?")
.setBody().constant("event")
.log("${body}");
The schedule expression 0/3+10+*+? can be also written as 0/3 10 * * * ? and triggers an event every three seconds only in the tenth minute of each hour.
Parts in the schedule expression means (in order):
- Seconds (optional)
- Minutes
- Hours
- Day of month
- Month
- Day of week
- Year (optional)
Schedule expressions can be made of 5 to 7 parts. When expressions are composed of 6 parts, the first items is the "seconds" part (and year is considered missing).
Other valid examples of schedule expressions are:
-
0/2 * * * ?(5 parts, an event every two minutes) -
0 0/2 * * * MON-FRI 2030(7 parts, an event every two minutes only in year 2030)
Routes can also be written using the XML DSL.
26.6. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 4 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.cron.autowired-enabled | 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 |
| camel.component.cron.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.cron.cron-service | The id of the CamelCronService to use when multiple implementations are provided. | String | |
| camel.component.cron.enabled | Whether to enable auto configuration of the cron component. This is enabled by default. | Boolean |
Chapter 27. Crypto (JCE) 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 2.3
Only producer is supported
With Camel cryptographic endpoints and Java Cryptographic extension, it is easy to create Digital Signatures for Exchanges. Camel provides a pair of flexible endpoints which get used in concert to create a signature for an exchange in one part of the exchange workflow and then verify the signature in a later part of the workflow.
27.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using crypto with Red Hat build of Camel Spring Boot ensure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-crypto-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-crypto-starter</artifactId>
</dependency>
27.2. Introduction 링크 복사링크가 클립보드에 복사되었습니다!
Digital signatures make use of Asymmetric Cryptographic techniques to sign messages. From a high level, the algorithms use pairs of complimentary keys with the special property that data encrypted with one key can only be decrypted with the other. The private key, is closely guarded and used to 'sign' the message while the other, public key, is shared around to anyone interested in verifying the signed messages. Messages are signed by using the private key to encrypting a digest of the message. This encrypted digest is transmitted along with the message. On the other side the verifier recalculates the message digest and uses the public key to decrypt the digest in the signature. If both digests match, the verifier knows only the holder of the private key could have created the signature.
Camel uses the Signature service from the Java Cryptographic Extension to do all the heavy cryptographic lifting required to create exchange signatures. The following are the resources for explaining the mechanics of Cryptography, Message digests and Digital Signatures and how to leverage them with the JCE.
- Bruce Schneier’s Applied Cryptography
- Beginning Cryptography with Java by David Hook
- The ever insightful Wikipedia Digital_signatures
27.3. URI format 링크 복사링크가 클립보드에 복사되었습니다!
Camel provides a pair of crypto endpoints to create and verify signatures
crypto:sign:name[?options] crypto:verify:name[?options]
crypto:sign:name[?options]
crypto:verify:name[?options]
-
crypto:signcreates the signature and stores it in the Header keyed by the constantorg.apache.camel.component.crypto.DigitalSignatureConstants.SIGNATURE, that is,"CamelDigitalSignature". -
crypto:verifyreads in the contents of this header and do the verification calculation.
To function, the sign and verify process needs a pair of keys to be shared, signing requiring a PrivateKey and verifying a PublicKey (or a Certificate containing one). Using the JCE, it is very simple to generate these key pairs but it is usually most secure to use a KeyStore to house and share your keys. The DSL is very flexible about how keys are supplied and provides a number of mechanisms.
A crypto:sign endpoint is typically defined in one route and the complimentary crypto:verify in another, though for simplicity in the examples they appear one after the other. Both signing and verifying should be configured identically.
27.4. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
27.4.1. Configuring Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The component level is the highest level which holds general and common configurations that are inherited by the endpoints. 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.
Configuring components can be done with the Component DSL, in a configuration file (application.properties|yaml), or directly with Java code.
27.4.2. Configuring Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
Endpoints have many options, which allows you to configure what you need the endpoint to do. The options are also categorized into whether the endpoint is used as consumer (from) or as a producer (to), or used for both.
Configuring endpoints is 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.
Use Property Placeholders to configure options that allows to not hardcode urls, port numbers, sensitive information, and other settings. In other words placeholders allows to externalize the configuration from your code, and gives more flexibility and reuse.
The following two sections lists all the options, firstly for the component followed by the endpoint.
27.5. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Crypto (JCE) component supports 21 options that are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| algorithm (producer) | Sets the JCE name of the Algorithm that should be used for the signer. | SHA256withRSA | String |
| alias (producer) | Sets the alias used to query the KeyStore for keys and \\{link java.security.cert.Certificate Certificates} to be used in signing and verifying exchanges. This value can be provided at runtime via the message header org.apache.camel.component.crypto.DigitalSignatureConstants#KEYSTORE_ALIAS. | String | |
| certificateName (producer) | Sets the reference name for a PrivateKey that can be found in the registry. | String | |
| keystore (producer) | Sets the KeyStore that can contain keys and Certificates for use in signing and verifying exchanges. A KeyStore is typically used with an alias, either one supplied in the Route definition or dynamically via the message header CamelSignatureKeyStoreAlias. If no alias is supplied and there is only a single entry in the Keystore, then this single entry will be used. | KeyStore | |
| keystoreName (producer) | Sets the reference name for a Keystore that can be found in the registry. | String | |
| 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 |
| privateKey* (producer) | Set the PrivateKey that should be used to sign the exchange. | PrivateKey | |
| privateKeyName (producer) | Sets the reference name for a PrivateKey that can be found in the registry. | String | |
| provider (producer) | Set the id of the security provider that provides the configured Signature algorithm. | String | |
| publicKeyName (producer) | references that should be resolved when the context changes. | String | |
| secureRandomName (producer) | Sets the reference name for a SecureRandom that can be found in the registry. | String | |
| signatureHeaderName (producer) | Set the name of the message header that should be used to store the base64 encoded signature. This defaults to 'CamelDigitalSignature'. | String | |
| 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 |
| bufferSize (advanced) | Set the size of the buffer used to read in the Exchange payload data. | 2048 | Integer |
| certificate (advanced) | Set the Certificate that should be used to verify the signature in the exchange based on its payload. | Certificate | |
| clearHeaders (advanced) | Determines if the Signature specific headers be cleared after signing and verification. Defaults to true, and should only be made otherwise at your extreme peril as vital private information such as Keys and passwords may escape if unset. | true | boolean |
| configuration (advanced) | To use the shared DigitalSignatureConfiguration as configuration. | DigitalSignatureConfiguration | |
| keyStoreParameters (advanced) | Sets the KeyStore that can contain keys and Certficates for use in signing and verifying exchanges based on the given KeyStoreParameters. A KeyStore is typically used with an alias, either one supplied in the Route definition or dynamically via the message header CamelSignatureKeyStoreAlias. If no alias is supplied and there is only a single entry in the Keystore, then this single entry will be used. | KeyStoreParameters | |
| publicKey (advanced) | Set the PublicKey that should be used to verify the signature in the exchange. | PublicKey | |
| secureRandom (advanced) | Set the SecureRandom used to initialize the Signature service. | SecureRandom | |
| password (security) | Sets the password used to access an aliased PrivateKey in the KeyStore. | String |
27.6. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Crypto (JCE) endpoint is configured using URI syntax:
crypto:cryptoOperation:name
crypto:cryptoOperation:name
The following are the path and query parameters:
27.6.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| cryptoOperation (producer) | Required Set the Crypto operation from that supplied after the crypto scheme in the endpoint uri e.g. crypto:sign sets sign as the operation. Enum values: * sign * verify | CryptoOperation | |
| name (producer) | Required The logical name of this operation. | String |
27.6.2. Query Parameters (19 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| algorithm (producer) | Sets the JCE name of the Algorithm that should be used for the signer. | SHA256withRSA | String |
| alias (producer) | Sets the alias used to query the KeyStore for keys and \\{link java.security.cert.Certificate Certificates} to be used in signing and verifying exchanges. This value can be provided at runtime via the message header org.apache.camel.component.crypto.DigitalSignatureConstants#KEYSTORE_ALIAS. | String | |
| certificateName (producer) | Sets the reference name for a PrivateKey that can be found in the registry. | String | |
| keystore (producer) | Sets the KeyStore that can contain keys and Certficates for use in signing and verifying exchanges. A KeyStore is typically used with an alias, either one supplied in the Route definition or dynamically via the message header CamelSignatureKeyStoreAlias. If no alias is supplied and there is only a single entry in the Keystore, then this single entry will be used. | KeyStore | |
| keystoreName (producer) | Sets the reference name for a Keystore that can be found in the registry. | String | |
| privateKey (producer) | Set the PrivateKey that should be used to sign the exchange. | PrivateKey | |
| privateKeyName (producer) | Sets the reference name for a PrivateKey that can be found in the registry. | String | |
| provider (producer) | Set the id of the security provider that provides the configured Signature algorithm. | String | |
| publicKeyName (producer) | references that should be resolved when the context changes. | String | |
| secureRandomName (producer) | Sets the reference name for a SecureRandom that can be found in the registry. | String | |
| signatureHeaderName (producer) | Set the name of the message header that should be used to store the base64 encoded signature. This defaults to 'CamelDigitalSignature'. | String | |
| 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 using Camel 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. | false | boolean |
| bufferSize (advanced) | Set the size of the buffer used to read in the Exchange payload data. | 2048 | Integer |
| certificate (advanced) | Set the Certificate that should be used to verify the signature in the exchange based on its payload. | Certificate | |
| clearHeaders (advanced) | Determines if the Signature specific headers be cleared after signing and verification. Defaults to true, and should only be made otherwise at your extreme peril as vital private information such as Keys and passwords may escape if unset. | true | boolean |
| keyStoreParameters (advanced) | Sets the KeyStore that can contain keys and Certficates for use in signing and verifying exchanges based on the given KeyStoreParameters. A KeyStore is typically used with an alias, either one supplied in the Route definition or dynamically via the message header CamelSignatureKeyStoreAlias. If no alias is supplied and there is only a single entry in the Keystore, then this single entry will be used. | KeyStoreParameters | |
| publicKey (advanced) | Set the PublicKey that should be used to verify the signature in the exchange. | PublicKey | |
| secureRandom (advanced) | Set the SecureRandom used to initialize the Signature service. | SecureRandom | |
| password (security) | Sets the password used to access an aliased PrivateKey in the KeyStore. | String |
27.7. Message Headers 링크 복사링크가 클립보드에 복사되었습니다!
The Crypto (JCE) component supports 4 message headers that are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| [CamelSignaturePrivateKey (producer)
Constant: | The PrivateKey that should be used to sign the message. | PrivateKey | |
| [CamelSignaturePublicKeyOrCert (producer)
Constant: | The Certificate or PublicKey that should be used to verify the signature. | Certificate or PublicKey | |
| CamelSignatureKeyStoreAlias (producer)
Constant: | The alias used to query the KeyStore for keys and Certificates to be used in signing and verifying exchanges. | String | |
| CamelSignatureKeyStorePassword (producer)
Constant: | The password used to access an aliased PrivateKey in the KeyStore. | char[] |
27.8. Using 링크 복사링크가 클립보드에 복사되었습니다!
27.8.1. Raw keys 링크 복사링크가 클립보드에 복사되었습니다!
The most basic way to sign and verify an exchange is with a KeyPair as follows.
The same can be achieved with the Spring XML Extensions using references to keys.
27.8.2. KeyStores and Aliases. 링크 복사링크가 클립보드에 복사되었습니다!
The JCE provides a very versatile keystore concept for housing pairs of private keys and certificates, keeping them encrypted and password protected. They can be retrieved by applying an alias to the retrieval APIs. There are a number of ways to get keys and Certificates into a keystore, most often this is done with the external 'keytool' application.
The following command will create a keystore containing a key and certificate aliased by bob, which can be used in the following examples. The password for the keystore and the key is letmein.
keytool -genkey -keyalg RSA -keysize 2048 -keystore keystore.jks -storepass letmein -alias bob -dname "CN=Bob,OU=IT,O=Camel" -noprompt
keytool -genkey -keyalg RSA -keysize 2048 -keystore keystore.jks -storepass letmein -alias bob -dname "CN=Bob,OU=IT,O=Camel" -noprompt
The following route first signs an exchange using Bob’s alias from the KeyStore bound into the Camel Registry, and then verifies it using the same alias.
from("direct:sign")
.to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein")
.log("Signature: ${header.CamelDigitalSignature}")
.to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein")
.log("Verified: ${body}");
from("direct:sign")
.to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein")
.log("Signature: ${header.CamelDigitalSignature}")
.to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein")
.log("Verified: ${body}");
The following code shows how to load the keystore created using the above keytool command and bind it into the registry with the name myKeystore for use in the above route. The example makes use of the @Configuration and @BindToRegistry annotations introduced in Camel 3 to instantiate the KeyStore and register it with the name myKeyStore.
Again in Spring a ref is used to lookup an actual keystore instance.
27.8.3. Changing JCE Provider and Algorithm 링크 복사링크가 클립보드에 복사되었습니다!
Changing the Signature algorithm or the Security provider is a simple matter of specifying their names. You will need to also use Keys that are compatible with the algorithm you choose.
27.8.4. Changing the Signature Message Header 링크 복사링크가 클립보드에 복사되었습니다!
It may be desirable to change the message header used to store the signature. A different header name can be specified in the route definition as follows
from("direct:sign")
.to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature")
.log("Signature: ${header.mySignature}")
.to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature");
from("direct:sign")
.to("crypto:sign:keystoreSign?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature")
.log("Signature: ${header.mySignature}")
.to("crypto:verify:keystoreVerify?alias=bob&keystoreName=myKeystore&password=letmein&signatureHeaderName=mySignature");
===Changing the bufferSize
In case you need to update the size of the buffer.
27.8.5. Supplying Keys dynamically. 링크 복사링크가 클립보드에 복사되었습니다!
When using a Recipient list or similar EIP, the recipient of an exchange can vary dynamically. Using the same key across all recipients may be neither feasible nor desirable. It would be useful to be able to specify signature keys dynamically on a per-exchange basis. The exchange could then be dynamically enriched with the key of its target recipient prior to signing. To facilitate this the signature mechanisms allow for keys to be supplied dynamically via the message headers below.
-
DigitalSignatureConstants.SIGNATURE_PRIVATE_KEY,"CamelSignaturePrivateKey" -
DigitalSignatureConstants.SIGNATURE_PUBLIC_KEY_OR_CERT,"CamelSignaturePublicKeyOrCert"
Even better would be to dynamically supply a keystore alias. Again the alias can be supplied in a message header
-
DigitalSignatureConstants.KEYSTORE_ALIAS,"CamelSignatureKeyStoreAlias"
The header would be set as follows:
27.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 47 options that are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.crypto.algorithm | Sets the JCE name of the Algorithm that should be used for the signer. | SHA256withRSA | String |
| camel.component.crypto.alias | Sets the alias used to query the KeyStore for keys and {link java.security.cert.Certificate Certificates} to be used in signing and verifying exchanges. This value can be provided at runtime via the message header org.apache.camel.component.crypto.DigitalSignatureConstants#KEYSTORE_ALIAS. | String | |
| camel.component.crypto.autowired-enabled | Whether auto-wiring is enabled. This is used for automatic auto-wiring options (the option must be marked as auto-wired) 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 |
| camel.component.crypto.buffer-size | Set the size of the buffer used to read in the Exchange payload data. | 2048 | Integer |
| camel.component.crypto.certificate | Set the Certificate that should be used to verify the signature in the exchange based on its payload. The option is a java.security.cert.Certificate type. | Certificate | |
| camel.component.crypto.certificate-name | Sets the reference name for a PrivateKey that can be found in the registry. | String | |
| camel.component.crypto.clear-headers | Determines if the Signature specific headers be cleared after signing and verification. Defaults to true, and should only be made otherwise at your extreme peril as vital private information such as Keys and passwords may escape if unset. | true | Boolean |
| camel.component.crypto.configuration | To use the shared DigitalSignatureConfiguration as configuration. The option is a org.apache.camel.component.crypto.DigitalSignatureConfiguration type. | DigitalSignatureConfiguration | |
| camel.component.crypto.enabled | Whether to enable auto configuration of the crypto component. This is enabled by default. | Boolean | |
| camel.component.crypto.key-store-parameters | Sets the KeyStore that can contain keys and Certficates for use in signing and verifying exchanges based on the given KeyStoreParameters. A KeyStore is typically used with an alias, either one supplied in the Route definition or dynamically via the message header CamelSignatureKeyStoreAlias. If no alias is supplied and there is only a single entry in the Keystore, then this single entry will be used. The option is a org.apache.camel.support.jsse.KeyStoreParameters type. | KeyStoreParameters | |
| camel.component.crypto.keystore | Sets the KeyStore that can contain keys and Certficates for use in signing and verifying exchanges. A KeyStore is typically used with an alias, either one supplied in the Route definition or dynamically via the message header CamelSignatureKeyStoreAlias. If no alias is supplied and there is only a single entry in the Keystore, then this single entry will be used. The option is a java.security.KeyStore type. | KeyStore | |
| camel.component.crypto.keystore-name | Sets the reference name for a Keystore that can be found in the registry. | String | |
| camel.component.crypto.lazy-start-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 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 |
| camel.component.crypto.password | Sets the password used to access an aliased PrivateKey in the KeyStore. | String | |
| camel.component.crypto.private-key | Set the PrivateKey that should be used to sign the exchange. The option is a java.security.PrivateKey type. | PrivateKey | |
| camel.component.crypto.private-key-name | Sets the reference name for a PrivateKey that can be found in the registry. | String | |
| camel.component.crypto.provider | Set the id of the security provider that provides the configured Signature algorithm. | String | |
| camel.component.crypto.public-key | Set the PublicKey that should be used to verify the signature in the exchange. The option is a java.security.PublicKey type. | PublicKey | |
| camel.component.crypto.public-key-name | references that should be resolved when the context changes. | String | |
| camel.component.crypto.secure-random | Set the SecureRandom used to initialize the Signature service. The option is a java.security.SecureRandom type. | SecureRandom | |
| camel.component.crypto.secure-random-name | Sets the reference name for a SecureRandom that can be found in the registry. | String | |
| camel.component.crypto.signature-header-name | Set the name of the message header that should be used to store the base64 encoded signature. This defaults to 'CamelDigitalSignature'. | String | |
| camel.dataformat.crypto.algorithm | The JCE algorithm name indicating the cryptographic algorithm that will be used. | String | |
| camel.dataformat.crypto.algorithm-parameter-ref | A JCE AlgorithmParameterSpec used to initialize the Cipher. Will lookup the type using the given name as a java.security.spec.AlgorithmParameterSpec type. | String | |
| camel.dataformat.crypto.buffer-size | The size of the buffer used in the signature process. | 4096 | Integer |
| camel.dataformat.crypto.crypto-provider | The name of the JCE Security Provider that should be used. | String | |
| camel.dataformat.crypto.enabled | Whether to enable auto configuration of the crypto data format. This is enabled by default. | Boolean | |
| camel.dataformat.crypto.init-vector-ref | Refers to a byte array containing the Initialization Vector that will be used to initialize the Cipher. | String | |
| camel.dataformat.crypto.inline | Flag indicating that the configured IV should be inlined into the encrypted data stream. Is by default false. | false | Boolean |
| camel.dataformat.crypto.key-ref | Refers to the secret key to lookup from the register to use. | String | |
| camel.dataformat.crypto.mac-algorithm | The JCE algorithm name indicating the Message Authentication algorithm. | HmacSHA1 | String |
| camel.dataformat.crypto.should-append-h-m-a-c | Flag indicating that a Message Authentication Code should be calculated and appended to the encrypted data. | true | Boolean |
| camel.dataformat.pgp.algorithm | Symmetric key encryption algorithm; possible values are defined in org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags; for example 2 (= TRIPLE DES), 3 (= CAST5), 4 (= BLOWFISH), 6 (= DES), 7 (= AES_128). Only relevant for encrypting. | Integer | |
| camel.dataformat.pgp.armored | This option will cause PGP to base64 encode the encrypted text, making it available for copy/paste, etc. | false | Boolean |
| camel.dataformat.pgp.compression-algorithm | Compression algorithm; possible values are defined in org.bouncycastle.bcpg.CompressionAlgorithmTags; for example 0 (= UNCOMPRESSED), 1 (= ZIP), 2 (= ZLIB), 3 (= BZIP2). Only relevant for encrypting. | Integer | |
| camel.dataformat.pgp.enabled | Whether to enable auto configuration of the pgp data format. This is enabled by default. | Boolean | |
| camel.dataformat.pgp.hash-algorithm | Signature hash algorithm; possible values are defined in org.bouncycastle.bcpg.HashAlgorithmTags; for example 2 (= SHA1), 8 (= SHA256), 9 (= SHA384), 10 (= SHA512), 11 (=SHA224). Only relevant for signing. | Integer | |
| camel.dataformat.pgp.integrity | Adds an integrity check/sign into the encryption file. The default value is true. | true | Boolean |
| camel.dataformat.pgp.key-file-name | Filename of the keyring; must be accessible as a classpath resource (but you can specify a location in the file system by using the file: prefix). | String | |
| camel.dataformat.pgp.key-userid | The user ID of the key in the PGP keyring used during encryption. Can also be only a part of a user ID. For example, if the user ID is Test User then you can use the part Test User or to address the user ID. | String | |
| camel.dataformat.pgp.password | Password used when opening the private key (not used for encryption). | String | |
| camel.dataformat.pgp.provider | Java Cryptography Extension (JCE) provider, default is Bouncy Castle (BC). Alternatively you can use, for example, the IAIK JCE provider; in this case the provider must be registered beforehand and the Bouncy Castle provider must not be registered beforehand. The Sun JCE provider does not work. | String | |
| camel.dataformat.pgp.signature-key-file-name | Filename of the keyring to use for signing (during encryption) or for signature verification (during decryption); must be accessible as a classpath resource (but you can specify a location in the file system by using the file: prefix). | String | |
| camel.dataformat.pgp.signature-key-ring | Keyring used for signing/verifying as byte array. You can not set the signatureKeyFileName and signatureKeyRing at the same time. | String | |
| camel.dataformat.pgp.signature-key-userid | User ID of the key in the PGP keyring used for signing (during encryption) or signature verification (during decryption). During the signature verification process the specified User ID restricts the public keys from the public keyring which can be used for the verification. If no User ID is specified for the signature verification then any public key in the public keyring can be used for the verification. Can also be only a part of a user ID. For example, if the user ID is Test User then you can use the part Test User or to address the User ID. | String | |
| camel.dataformat.pgp.signature-password | Password used when opening the private key used for signing (during encryption). | String | |
| camel.dataformat.pgp.signature-verification-option | Controls the behavior for verifying the signature during un-marshaling. There are 4 values possible: optional: The PGP message may or may not contain signatures; if it does contain signatures, then a signature verification is executed. required: The PGP message must contain at least one signature; if this is not the case an exception (PGPException) is thrown. A signature verification is executed. ignore: Contained signatures in the PGP message are ignored; no signature verification is executed. no_signature_allowed: The PGP message must not contain a signature; otherwise an exception (PGPException) is thrown. | String |
Chapter 28. CSimple 링크 복사링크가 클립보드에 복사되었습니다!
The CSimple language is compiled Simple language.
28.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using csimple with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-core-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-core-starter</artifactId>
</dependency>
28.2. Different between CSimple and Simple 링크 복사링크가 클립보드에 복사되었습니다!
The simple language is a dynamic expression language which is runtime parsed into a set of Camel Expressions or Predicates.
The csimple language is parsed into regular Java source code and compiled together with all the other source code, or compiled once during bootstrap via the camel-csimple-joor module.
The simple language is generally very lightweight and fast, however for some use-cases with dynamic method calls via OGNL paths, then the simple language does runtime introspection and reflection calls. This has an overhead on performance, and was one of the reasons why csimple was created.
The csimple language requires to be typesafe and method calls via OGNL paths requires to know the type during parsing. This means for csimple languages expressions you would need to provide the class type in the script, whereas simple introspects this at runtime.
In other words the simple language is using duck typing (if it looks like a duck, and quacks like a duck, then it is a duck) and csimple is using Java type (typesafety). If there is a type error then simple will report this at runtime, and with csimple there will be a Java compilation error.
28.2.1. Additional CSimple functions 링크 복사링크가 클립보드에 복사되었습니다!
The csimple language includes some additional functions to support common use-cases working with Collection, Map or array types. The following functions bodyAsIndex, headerAsIndex, and exchangePropertyAsIndex is used for these use-cases as they are typed.
| Function | Type | Description |
|---|---|---|
| bodyAsIndex(type, index) | Type |
To be used for collecting the body from an existing |
| mandatoryBodyAsIndex(type, index) | Type |
To be used for collecting the body from an existing |
| headerAsIndex(key, type, index) | Type |
To be used for collecting a header from an existing |
| mandatoryHeaderAsIndex(key, type, index) | Type |
To be used for collecting a header from an existing |
| exchangePropertyAsIndex(key, type, index) | Type |
To be used for collecting an exchange property from an existing |
| mandatoryExchangePropertyAsIndex(key, type, index) | Type |
To be used for collecting an exchange property from an existing |
For example given the following simple expression:
Hello $\{body[0].name}
Hello $\{body[0].name}
This script has no type information, and the simple language will resolve this at runtime, by introspecting the message body and if it’s a collection based then lookup the first element, and then invoke a method named getName via reflection.
In csimple (compiled) we want to pre compile this and therefore the end user must provide type information with the bodyAsIndex function:
Hello $\{bodyAsIndex(com.foo.MyUser, 0).name}
Hello $\{bodyAsIndex(com.foo.MyUser, 0).name}
28.3. Compilation 링크 복사링크가 클립보드에 복사되었습니다!
The csimple language is parsed into regular Java source code and compiled together with all the other source code, or it can be compiled once during bootstrap via the camel-csimple-joor module.
There are two ways to compile csimple
-
using the
camel-csimple-maven-plugingenerating source code at built time. -
using
camel-csimple-joorwhich does runtime in-memory compilation during bootstrap of Camel.
28.3.1. Using camel-csimple-maven-plugin 링크 복사링크가 클립보드에 복사되었습니다!
The camel-csimple-maven-plugin Maven plugin is used for discovering all the csimple scripts from the source code, and then automatic generate source code in the src/generated/java folder, which then gets compiled together with all the other sources.
The maven plugin will do source code scanning of .java and .xml files (Java and XML DSL). The scanner limits to detect certain code patterns, and it may miss discovering some csimple scripts if they are being used in unusual/rare ways.
The runtime compilation using camel-csimple-joor does not have this limitation.
The benefit is all the csimple scripts will be compiled using the regular Java compiler and therefore everything is included out of the box as .class files in the application JAR file, and no additional dependencies is required at runtime.
To use camel-csimple-maven-plugin you need to add it to your pom.xml file as shown:
And then you must also add the build-helper-maven-plugin Maven plugin to include src/generated to the list of source folders for the Java compiler, to ensure the generated source code is compiled and included in the application JAR file.
See the camel-example-csimple example at Camel Examples which uses the maven plugin.
28.3.2. Using camel-csimple-joor 링크 복사링크가 클립보드에 복사되었습니다!
The jOOR library integrates with the Java compiler and performs runtime compilation of Java code.
The supported runtime when using camel-simple-joor is intended for Java standalone, Spring Boot, Camel Quarkus and other microservices runtimes. It is not supported in OSGi, Camel Karaf or any kind of Java Application Server runtime.
jOOR does not support runtime compilation with Spring Boot using fat jar packaging (https://github.com/jOOQ/jOOR/issues/69), it works with exploded classpath.
To use camel-simple-joor you simply just add it as dependency to the classpath:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-csimple-joor</artifactId>
<version>{CamelSBProjectVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-csimple-joor</artifactId>
<version>{CamelSBProjectVersion}</version>
</dependency>
There is no need for adding Maven plugins to the pom.xml file.
See the camel-example-csimple-joor example at Camel Examples which uses the jOOR compiler.
28.4. CSimple Language options 링크 복사링크가 클립보드에 복사되었습니다!
The CSimple language supports 2 options, which are listed below.
| Name | Default | Java Type | Description |
|---|---|---|---|
| resultType |
| Sets the class name of the result type (type from output). | |
| trim |
| Whether to trim the value to remove leading and trailing whitespaces and line breaks. |
28.5. Limitations 링크 복사링크가 클립보드에 복사되었습니다!
Currently, the csimple language does not support:
- nested functions (aka functions inside functions)
-
the null safe operator (
?).
For example the following scripts cannot compile:
Hello ${bean:greeter(${body}, ${header.counter})}
Hello ${bean:greeter(${body}, ${header.counter})}
${bodyAs(MyUser)?.address?.zip} > 10000
${bodyAs(MyUser)?.address?.zip} > 10000
28.6. Auto imports 링크 복사링크가 클립보드에 복사되었습니다!
The csimple language will automatically import from:
import java.util.*; import java.util.concurrent.*; import java.util.stream.*; import org.apache.camel.*; import org.apache.camel.util.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.*;
import org.apache.camel.*;
import org.apache.camel.util.*;
28.7. Configuration file 링크 복사링크가 클립보드에 복사되었습니다!
You can configure the csimple language in the camel-csimple.properties file which is loaded from the root classpath.
For example you can add additional imports in the camel-csimple.properties file by adding:
import com.foo.MyUser; import com.bar.*; import static com.foo.MyHelper.*;
import com.foo.MyUser;
import com.bar.*;
import static com.foo.MyHelper.*;
You can also add aliases (key=value) where an alias will be used as a shorthand replacement in the code.
echo()=${bodyAs(String)} ${bodyAs(String)}
echo()=${bodyAs(String)} ${bodyAs(String)}
Which allows to use echo() in the csimple language script such as:
from("direct:hello")
.transform(csimple("Hello echo()"))
.log("You said ${body}");
from("direct:hello")
.transform(csimple("Hello echo()"))
.log("You said ${body}");
The echo() alias will be replaced with its value resulting in a script as:
.transform(csimple("Hello ${bodyAs(String)} ${bodyAs(String)}"))
.transform(csimple("Hello ${bodyAs(String)} ${bodyAs(String)}"))
28.8. See Also 링크 복사링크가 클립보드에 복사되었습니다!
See the Simple language as csimple has the same set of functions as simple language.
28.9. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 147 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.cloud.consul.service-discovery.acl-token | Sets the ACL token to be used with Consul. | String | |
| camel.cloud.consul.service-discovery.block-seconds | The seconds to wait for a watch event, default 10 seconds. | 10 | Integer |
| camel.cloud.consul.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.consul.service-discovery.connect-timeout-millis | Connect timeout for OkHttpClient. | Long | |
| camel.cloud.consul.service-discovery.datacenter | The data center. | String | |
| camel.cloud.consul.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.consul.service-discovery.password | Sets the password to be used for basic authentication. | String | |
| camel.cloud.consul.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.consul.service-discovery.read-timeout-millis | Read timeout for OkHttpClient. | Long | |
| camel.cloud.consul.service-discovery.url | The Consul agent URL. | String | |
| camel.cloud.consul.service-discovery.user-name | Sets the username to be used for basic authentication. | String | |
| camel.cloud.consul.service-discovery.write-timeout-millis | Write timeout for OkHttpClient. | Long | |
| camel.cloud.dns.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.dns.service-discovery.domain | The domain name;. | String | |
| camel.cloud.dns.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.dns.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.dns.service-discovery.proto | The transport protocol of the desired service. | _tcp | String |
| camel.cloud.etcd.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.etcd.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.etcd.service-discovery.password | The password to use for basic authentication. | String | |
| camel.cloud.etcd.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.etcd.service-discovery.service-path | The path to look for for service discovery. | /services/ | String |
| camel.cloud.etcd.service-discovery.timeout | To set the maximum time an action could take to complete. | Long | |
| camel.cloud.etcd.service-discovery.type | To set the discovery type, valid values are on-demand and watch. | on-demand | String |
| camel.cloud.etcd.service-discovery.uris | The URIs the client can connect to. | String | |
| camel.cloud.etcd.service-discovery.user-name | The user name to use for basic authentication. | String | |
| camel.cloud.kubernetes.service-discovery.api-version | Sets the API version when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.ca-cert-data | Sets the Certificate Authority data when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.ca-cert-file | Sets the Certificate Authority data that are loaded from the file when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-cert-data | Sets the Client Certificate data when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-cert-file | Sets the Client Certificate data that are loaded from the file when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-algo | Sets the Client Keystore algorithm, such as RSA when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-data | Sets the Client Keystore data when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-file | Sets the Client Keystore data that are loaded from the file when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.client-key-passphrase | Sets the Client Keystore passphrase when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.kubernetes.service-discovery.dns-domain | Sets the DNS domain to use for DNS lookup. | String | |
| camel.cloud.kubernetes.service-discovery.enabled | Enable the component. | true | Boolean |
| camel.cloud.kubernetes.service-discovery.lookup | How to perform service lookup. Possible values: client, dns, environment. When using client, then the client queries the kubernetes master to obtain a list of active pods that provides the service, and then random (or round robin) select a pod. When using dns the service name is resolved as name.namespace.svc.dnsDomain. When using dnssrv the service name is resolved with SRV query for .…svc… When using environment then environment variables are used to lookup the service. By default environment is used. | environment | String |
| camel.cloud.kubernetes.service-discovery.master-url | Sets the URL to the master when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.namespace | Sets the namespace to use. Will by default use namespace from the ENV variable KUBERNETES_MASTER. | String | |
| camel.cloud.kubernetes.service-discovery.oauth-token | Sets the OAUTH token for authentication (instead of username/password) when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.password | Sets the password for authentication when using client lookup. | String | |
| camel.cloud.kubernetes.service-discovery.port-name | Sets the Port Name to use for DNS/DNSSRV lookup. | String | |
| camel.cloud.kubernetes.service-discovery.port-protocol | Sets the Port Protocol to use for DNS/DNSSRV lookup. | String | |
| camel.cloud.kubernetes.service-discovery.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.kubernetes.service-discovery.trust-certs | Sets whether to turn on trust certificate check when using client lookup. | false | Boolean |
| camel.cloud.kubernetes.service-discovery.username | Sets the username for authentication when using client lookup. | String | |
| camel.cloud.ribbon.load-balancer.client-name | Sets the Ribbon client name. | String | |
| camel.cloud.ribbon.load-balancer.configurations | Define additional configuration definitions. | Map | |
| camel.cloud.ribbon.load-balancer.enabled | Enable the component. | true | Boolean |
| camel.cloud.ribbon.load-balancer.namespace | The namespace. | String | |
| camel.cloud.ribbon.load-balancer.password | The password. | String | |
| camel.cloud.ribbon.load-balancer.properties | Set client properties to use. These properties are specific to what service call implementation are in use. For example if using ribbon, then the client properties are define in com.netflix.client.config.CommonClientConfigKey. | Map | |
| camel.cloud.ribbon.load-balancer.username | The username. | String | |
| camel.hystrix.allow-maximum-size-to-diverge-from-core-size | Allows the configuration for maximumSize to take effect. That value can then be equal to, or higher, than coreSize. | false | Boolean |
| camel.hystrix.circuit-breaker-enabled | Whether to use a HystrixCircuitBreaker or not. If false no circuit-breaker logic will be used and all requests permitted. This is similar in effect to circuitBreakerForceClosed() except that continues tracking metrics and knowing whether it should be open/closed, this property results in not even instantiating a circuit-breaker. | true | Boolean |
| camel.hystrix.circuit-breaker-error-threshold-percentage | Error percentage threshold (as whole number such as 50) at which point the circuit breaker will trip open and reject requests. It will stay tripped for the duration defined in circuitBreakerSleepWindowInMilliseconds; The error percentage this is compared against comes from HystrixCommandMetrics.getHealthCounts(). | 50 | Integer |
| camel.hystrix.circuit-breaker-force-closed | If true the HystrixCircuitBreaker#allowRequest() will always return true to allow requests regardless of the error percentage from HystrixCommandMetrics.getHealthCounts(). The circuitBreakerForceOpen() property takes precedence so if it set to true this property does nothing. | false | Boolean |
| camel.hystrix.circuit-breaker-force-open | If true the HystrixCircuitBreaker.allowRequest() will always return false, causing the circuit to be open (tripped) and reject all requests. This property takes precedence over circuitBreakerForceClosed();. | false | Boolean |
| camel.hystrix.circuit-breaker-request-volume-threshold | Minimum number of requests in the metricsRollingStatisticalWindowInMilliseconds() that must exist before the HystrixCircuitBreaker will trip. If below this number the circuit will not trip regardless of error percentage. | 20 | Integer |
| camel.hystrix.circuit-breaker-sleep-window-in-milliseconds | The time in milliseconds after a HystrixCircuitBreaker trips open that it should wait before trying requests again. | 5000 | Integer |
| camel.hystrix.configurations | Define additional configuration definitions. | Map | |
| camel.hystrix.core-pool-size | Core thread-pool size that gets passed to java.util.concurrent.ThreadPoolExecutor#setCorePoolSize(int). | 10 | Integer |
| camel.hystrix.enabled | Enable the component. | true | Boolean |
| camel.hystrix.execution-isolation-semaphore-max-concurrent-requests | Number of concurrent requests permitted to HystrixCommand.run(). Requests beyond the concurrent limit will be rejected. Applicable only when executionIsolationStrategy == SEMAPHORE. | 20 | Integer |
| camel.hystrix.execution-isolation-strategy | What isolation strategy HystrixCommand.run() will be executed with. If THREAD then it will be executed on a separate thread and concurrent requests limited by the number of threads in the thread-pool. If SEMAPHORE then it will be executed on the calling thread and concurrent requests limited by the semaphore count. | THREAD | String |
| camel.hystrix.execution-isolation-thread-interrupt-on-timeout | Whether the execution thread should attempt an interrupt (using Future#cancel ) when a thread times out. Applicable only when executionIsolationStrategy() == THREAD. | true | Boolean |
| camel.hystrix.execution-timeout-enabled | Whether the timeout mechanism is enabled for this command. | true | Boolean |
| camel.hystrix.execution-timeout-in-milliseconds | Time in milliseconds at which point the command will timeout and halt execution. If executionIsolationThreadInterruptOnTimeout == true and the command is thread-isolated, the executing thread will be interrupted. If the command is semaphore-isolated and a HystrixObservableCommand, that command will get unsubscribed. | 1000 | Integer |
| camel.hystrix.fallback-enabled | Whether HystrixCommand.getFallback() should be attempted when failure occurs. | true | Boolean |
| camel.hystrix.fallback-isolation-semaphore-max-concurrent-requests | Number of concurrent requests permitted to HystrixCommand.getFallback(). Requests beyond the concurrent limit will fail-fast and not attempt retrieving a fallback. | 10 | Integer |
| camel.hystrix.group-key | Sets the group key to use. The default value is CamelHystrix. | CamelHystrix | String |
| camel.hystrix.keep-alive-time | Keep-alive time in minutes that gets passed to ThreadPoolExecutor#setKeepAliveTime(long,TimeUnit). | 1 | Integer |
| camel.hystrix.max-queue-size | Max queue size that gets passed to BlockingQueue in HystrixConcurrencyStrategy.getBlockingQueue(int) This should only affect the instantiation of a threadpool - it is not eliglible to change a queue size on the fly. For that, use queueSizeRejectionThreshold(). | -1 | Integer |
| camel.hystrix.maximum-size | Maximum thread-pool size that gets passed to ThreadPoolExecutor#setMaximumPoolSize(int) . This is the maximum amount of concurrency that can be supported without starting to reject HystrixCommands. Please note that this setting only takes effect if you also set allowMaximumSizeToDivergeFromCoreSize. | 10 | Integer |
| camel.hystrix.metrics-health-snapshot-interval-in-milliseconds | Time in milliseconds to wait between allowing health snapshots to be taken that calculate success and error percentages and affect HystrixCircuitBreaker.isOpen() status. On high-volume circuits the continual calculation of error percentage can become CPU intensive thus this controls how often it is calculated. | 500 | Integer |
| camel.hystrix.metrics-rolling-percentile-bucket-size | Maximum number of values stored in each bucket of the rolling percentile. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | 10 | Integer |
| camel.hystrix.metrics-rolling-percentile-enabled | Whether percentile metrics should be captured using HystrixRollingPercentile inside HystrixCommandMetrics. | true | Boolean |
| camel.hystrix.metrics-rolling-percentile-window-buckets | Number of buckets the rolling percentile window is broken into. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | 6 | Integer |
| camel.hystrix.metrics-rolling-percentile-window-in-milliseconds | Duration of percentile rolling window in milliseconds. This is passed into HystrixRollingPercentile inside HystrixCommandMetrics. | 10000 | Integer |
| camel.hystrix.metrics-rolling-statistical-window-buckets | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside HystrixCommandMetrics. | 10 | Integer |
| camel.hystrix.metrics-rolling-statistical-window-in-milliseconds | This property sets the duration of the statistical rolling window, in milliseconds. This is how long metrics are kept for the thread pool. The window is divided into buckets and rolls by those increments. | 10000 | Integer |
| camel.hystrix.queue-size-rejection-threshold | Queue size rejection threshold is an artificial max size at which rejections will occur even if maxQueueSize has not been reached. This is done because the maxQueueSize of a BlockingQueue can not be dynamically changed and we want to support dynamically changing the queue size that affects rejections. This is used by HystrixCommand when queuing a thread for execution. | 5 | Integer |
| camel.hystrix.request-log-enabled | Whether HystrixCommand execution and events should be logged to HystrixRequestLog. | true | Boolean |
| camel.hystrix.thread-pool-key | Sets the thread pool key to use. Will by default use the same value as groupKey has been configured to use. | CamelHystrix | String |
| camel.hystrix.thread-pool-rolling-number-statistical-window-buckets | Number of buckets the rolling statistical window is broken into. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | 10 | Integer |
| camel.hystrix.thread-pool-rolling-number-statistical-window-in-milliseconds | Duration of statistical rolling window in milliseconds. This is passed into HystrixRollingNumber inside each HystrixThreadPoolMetrics instance. | 10000 | Integer |
| camel.language.constant.enabled | Whether to enable auto configuration of the constant language. This is enabled by default. | Boolean | |
| camel.language.constant.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.csimple.enabled | Whether to enable auto configuration of the csimple language. This is enabled by default. | Boolean | |
| camel.language.csimple.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.exchangeproperty.enabled | Whether to enable auto configuration of the exchangeProperty language. This is enabled by default. | Boolean | |
| camel.language.exchangeproperty.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.file.enabled | Whether to enable auto configuration of the file language. This is enabled by default. | Boolean | |
| camel.language.file.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.header.enabled | Whether to enable auto configuration of the header language. This is enabled by default. | Boolean | |
| camel.language.header.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.ref.enabled | Whether to enable auto configuration of the ref language. This is enabled by default. | Boolean | |
| camel.language.ref.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.simple.enabled | Whether to enable auto configuration of the simple language. This is enabled by default. | Boolean | |
| camel.language.simple.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.language.tokenize.enabled | Whether to enable auto configuration of the tokenize language. This is enabled by default. | Boolean | |
| camel.language.tokenize.group-delimiter | Sets the delimiter to use when grouping. If this has not been set then token will be used as the delimiter. | String | |
| camel.language.tokenize.trim | Whether to trim the value to remove leading and trailing whitespaces and line breaks. | true | Boolean |
| camel.resilience4j.automatic-transition-from-open-to-half-open-enabled | Enables automatic transition from OPEN to HALF_OPEN state once the waitDurationInOpenState has passed. | false | Boolean |
| camel.resilience4j.circuit-breaker-ref | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreaker instance to lookup and use from the registry. When using this, then any other circuit breaker options are not in use. | String | |
| camel.resilience4j.config-ref | Refers to an existing io.github.resilience4j.circuitbreaker.CircuitBreakerConfig instance to lookup and use from the registry. | String | |
| camel.resilience4j.configurations | Define additional configuration definitions. | Map | |
| camel.resilience4j.enabled | Enable the component. | true | Boolean |
| camel.resilience4j.failure-rate-threshold | Configures the failure rate threshold in percentage. If the failure rate is equal or greater than the threshold the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 50 percentage. | Float | |
| camel.resilience4j.minimum-number-of-calls | Configures the minimum number of calls which are required (per sliding window period) before the CircuitBreaker can calculate the error rate. For example, if minimumNumberOfCalls is 10, then at least 10 calls must be recorded, before the failure rate can be calculated. If only 9 calls have been recorded the CircuitBreaker will not transition to open even if all 9 calls have failed. Default minimumNumberOfCalls is 100. | 100 | Integer |
| camel.resilience4j.permitted-number-of-calls-in-half-open-state | Configures the number of permitted calls when the CircuitBreaker is half open. The size must be greater than 0. Default size is 10. | 10 | Integer |
| camel.resilience4j.sliding-window-size | Configures the size of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. slidingWindowSize configures the size of the sliding window. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. The slidingWindowSize must be greater than 0. The minimumNumberOfCalls must be greater than 0. If the slidingWindowType is COUNT_BASED, the minimumNumberOfCalls cannot be greater than slidingWindowSize . If the slidingWindowType is TIME_BASED, you can pick whatever you want. Default slidingWindowSize is 100. | 100 | Integer |
| camel.resilience4j.sliding-window-type | Configures the type of the sliding window which is used to record the outcome of calls when the CircuitBreaker is closed. Sliding window can either be count-based or time-based. If slidingWindowType is COUNT_BASED, the last slidingWindowSize calls are recorded and aggregated. If slidingWindowType is TIME_BASED, the calls of the last slidingWindowSize seconds are recorded and aggregated. Default slidingWindowType is COUNT_BASED. | COUNT_BASED | String |
| camel.resilience4j.slow-call-duration-threshold | Configures the duration threshold (seconds) above which calls are considered as slow and increase the slow calls percentage. Default value is 60 seconds. | 60 | Integer |
| camel.resilience4j.slow-call-rate-threshold | Configures a threshold in percentage. The CircuitBreaker considers a call as slow when the call duration is greater than slowCallDurationThreshold Duration. When the percentage of slow calls is equal or greater the threshold, the CircuitBreaker transitions to open and starts short-circuiting calls. The threshold must be greater than 0 and not greater than 100. Default value is 100 percentage which means that all recorded calls must be slower than slowCallDurationThreshold. | Float | |
| camel.resilience4j.wait-duration-in-open-state | Configures the wait duration (in seconds) which specifies how long the CircuitBreaker should stay open, before it switches to half open. Default value is 60 seconds. | 60 | Integer |
| camel.resilience4j.writable-stack-trace-enabled | Enables writable stack traces. When set to false, Exception.getStackTrace returns a zero length array. This may be used to reduce log spam when the circuit breaker is open as the cause of the exceptions is already known (the circuit breaker is short-circuiting calls). | true | Boolean |
| camel.rest.api-component | The name of the Camel component to use as the REST API (such as swagger) If no API Component has been explicit configured, then Camel will lookup if there is a Camel component responsible for servicing and generating the REST API documentation, or if a org.apache.camel.spi.RestApiProcessorFactory is registered in the registry. If either one is found, then that is being used. | String | |
| camel.rest.api-context-path | Sets a leading API context-path the REST API services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. | String | |
| camel.rest.api-context-route-id | Sets the route id to use for the route that services the REST API. The route will by default use an auto assigned route id. | String | |
| camel.rest.api-host | To use an specific hostname for the API documentation (eg swagger) This can be used to override the generated host with this configured hostname. | String | |
| camel.rest.api-property | Allows to configure as many additional properties for the api documentation (swagger). For example set property api.title to my cool stuff. | Map | |
| camel.rest.api-vendor-extension | Whether vendor extension is enabled in the Rest APIs. If enabled then Camel will include additional information as vendor extension (eg keys starting with x-) such as route ids, class names etc. Not all 3rd party API gateways and tools supports vendor-extensions when importing your API docs. | false | Boolean |
| camel.rest.binding-mode | Sets the binding mode to use. The default value is off. | RestBindingMode | |
| camel.rest.client-request-validation | Whether to enable validation of the client request to check whether the Content-Type and Accept headers from the client is supported by the Rest-DSL configuration of its consumes/produces settings. This can be turned on, to enable this check. In case of validation error, then HTTP Status codes 415 or 406 is returned. The default value is false. | false | Boolean |
| camel.rest.component | The Camel Rest component to use for the REST transport (consumer), such as netty-http, jetty, servlet, undertow. If no component has been explicit configured, then Camel will lookup if there is a Camel component that integrates with the Rest DSL, or if a org.apache.camel.spi.RestConsumerFactory is registered in the registry. If either one is found, then that is being used. | String | |
| camel.rest.component-property | Allows to configure as many additional properties for the rest component in use. | Map | |
| camel.rest.consumer-property | Allows to configure as many additional properties for the rest consumer in use. | Map | |
| camel.rest.context-path | Sets a leading context-path the REST services will be using. This can be used when using components such as camel-servlet where the deployed web application is deployed using a context-path. Or for components such as camel-jetty or camel-netty-http that includes a HTTP server. | String | |
| camel.rest.cors-headers | Allows to configure custom CORS headers. | Map | |
| camel.rest.data-format-property | Allows to configure as many additional properties for the data formats in use. For example set property prettyPrint to true to have json outputted in pretty mode. The properties can be prefixed to denote the option is only for either JSON or XML and for either the IN or the OUT. The prefixes are: json.in. json.out. xml.in. xml.out. For example a key with value xml.out.mustBeJAXBElement is only for the XML data format for the outgoing. A key without a prefix is a common key for all situations. | Map | |
| camel.rest.enable-cors | Whether to enable CORS headers in the HTTP response. The default value is false. | false | Boolean |
| camel.rest.endpoint-property | Allows to configure as many additional properties for the rest endpoint in use. | Map | |
| camel.rest.host | The hostname to use for exposing the REST service. | String | |
| camel.rest.host-name-resolver | If no hostname has been explicit configured, then this resolver is used to compute the hostname the REST service will be using. | RestHostNameResolver | |
| camel.rest.json-data-format | Name of specific json data format to use. By default json-jackson will be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | String | |
| camel.rest.port | The port number to use for exposing the REST service. Notice if you use servlet component then the port number configured here does not apply, as the port number in use is the actual port number the servlet component is using. eg if using Apache Tomcat its the tomcat http port, if using Apache Karaf its the HTTP service in Karaf that uses port 8181 by default etc. Though in those situations setting the port number here, allows tooling and JMX to know the port number, so its recommended to set the port number to the number that the servlet engine uses. | String | |
| camel.rest.producer-api-doc | Sets the location of the api document (swagger api) the REST producer will use to validate the REST uri and query parameters are valid accordingly to the api document. This requires adding camel-swagger-java to the classpath, and any miss configuration will let Camel fail on startup and report the error(s). The location of the api document is loaded from classpath by default, but you can use file: or http: to refer to resources to load from file or http url. | String | |
| camel.rest.producer-component | Sets the name of the Camel component to use as the REST producer. | String | |
| camel.rest.scheme | The scheme to use for exposing the REST service. Usually http or https is supported. The default value is http. | String | |
| camel.rest.skip-binding-on-error-code | Whether to skip binding on output if there is a custom HTTP error code header. This allows to build custom error messages that do not bind to json / xml etc, as success messages otherwise will do. | false | Boolean |
| camel.rest.use-x-forward-headers | Whether to use X-Forward headers for Host and related setting. The default value is true. | true | Boolean |
| camel.rest.xml-data-format | Name of specific XML data format to use. By default jaxb will be used. Important: This option is only for setting a custom name of the data format, not to refer to an existing data format instance. | String | |
| camel.rest.api-context-id-pattern | Deprecated Sets an CamelContext id pattern to only allow Rest APIs from rest services within CamelContext’s which name matches the pattern. The pattern name refers to the CamelContext name, to match on the current CamelContext only. For any other value, the pattern uses the rules from PatternHelper#matchPattern(String,String). | String | |
| camel.rest.api-context-listing | Deprecated Sets whether listing of all available CamelContext’s with REST services in the JVM is enabled. If enabled it allows to discover these contexts, if false then only the current CamelContext is in use. | false | Boolean |
Chapter 29. CXF 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The CXF component provides integration with Apache CXF for connecting to JAX-WS services hosted in CXF.
When using CXF in streaming modes (see DataFormat option), then also read about Stream caching.
29.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using cxf with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cxf-soap-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-cxf-soap-starter</artifactId>
</dependency>
29.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
There are two URI formats for this endpoint: cxfEndpoint and someAddress.
cxf:bean:cxfEndpoint[?options]
cxf:bean:cxfEndpoint[?options]
Where cxfEndpoint represents a bean ID that references a bean in the Spring bean registry. With this URI format, most of the endpoint details are specified in the bean definition.
cxf://someAddress[?options]
cxf://someAddress[?options]
Where someAddress specifies the CXF endpoint’s address. With this URI format, most of the endpoint details are specified using options.
For either style above, you can append options to the URI as follows:
cxf:bean:cxfEndpoint?wsdlURL=wsdl/hello_world.wsdl&dataFormat=PAYLOAD
cxf:bean:cxfEndpoint?wsdlURL=wsdl/hello_world.wsdl&dataFormat=PAYLOAD
29.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
29.3.1. 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.
29.3.2. 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.
29.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The CXF component supports 6 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| 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 |
| allowStreaming (advanced) | This option controls whether the CXF component, when running in PAYLOAD mode, will DOM parse the incoming messages into DOM Elements or keep the payload as a javax.xml.transform.Source object that would allow streaming in some cases. | 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 |
| headerFilterStrategy (filter) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | |
| useGlobalSslContextParameters (security) | Enable usage of global SSL context parameters. | false | boolean |
29.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The CXF endpoint is configured using URI syntax:
cxf:beanId:address
cxf:beanId:address
with the following path and query parameters:
29.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| beanId (common) | To lookup an existing configured CxfEndpoint. Must used bean: as prefix. | String | |
| address (service) | The service publish address. | String |
29.5.2. Query Parameters (35 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| dataFormat (common) | The data type messages supported by the CXF endpoint. Enum values:
| POJO | DataFormat |
| wrappedStyle (common) | The WSDL style that describes how parameters are represented in the SOAP body. If the value is false, CXF will chose the document-literal unwrapped style, If the value is true, CXF will chose the document-literal wrapped style. | Boolean | |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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:
| ExchangePattern | |
| cookieHandler (producer) | Configure a cookie handler to maintain a HTTP session. | CookieHandler | |
| defaultOperationName (producer) | This option will set the default operationName that will be used by the CxfProducer which invokes the remote service. | String | |
| defaultOperationNamespace (producer) | This option will set the default operationNamespace that will be used by the CxfProducer which invokes the remote service. | String | |
| hostnameVerifier (producer) | The hostname verifier to be used. Use the # notation to reference a HostnameVerifier from the registry. | HostnameVerifier | |
| 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 |
| sslContextParameters (producer) | The Camel SSL setting reference. Use the # notation to reference the SSL Context. | SSLContextParameters | |
| wrapped (producer) | Which kind of operation that CXF endpoint producer will invoke. | false | boolean |
| synchronous (producer (advanced)) | Sets whether synchronous processing should be strictly used. | false | boolean |
| allowStreaming (advanced) | This option controls whether the CXF component, when running in PAYLOAD mode, will DOM parse the incoming messages into DOM Elements or keep the payload as a javax.xml.transform.Source object that would allow streaming in some cases. | Boolean | |
| bus (advanced) | To use a custom configured CXF Bus. | Bus | |
| continuationTimeout (advanced) | This option is used to set the CXF continuation timeout which could be used in CxfConsumer by default when the CXF server is using Jetty or Servlet transport. | 30000 | long |
| cxfBinding (advanced) | To use a custom CxfBinding to control the binding between Camel Message and CXF Message. | CxfBinding | |
| cxfConfigurer (advanced) | This option could apply the implementation of org.apache.camel.component.cxf.CxfEndpointConfigurer which supports to configure the CXF endpoint in programmatic way. User can configure the CXF server and client by implementing configure{ServerClient} method of CxfEndpointConfigurer. | CxfConfigurer | |
| defaultBus (advanced) | Will set the default bus when CXF endpoint create a bus by itself. | false | boolean |
| headerFilterStrategy (advanced) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | |
| mergeProtocolHeaders (advanced) | Whether to merge protocol headers. If enabled then propagating headers between Camel and CXF becomes more consistent and similar. For more details see CAMEL-6393. | false | boolean |
| mtomEnabled (advanced) | To enable MTOM (attachments). This requires to use POJO or PAYLOAD data format mode. | false | boolean |
| properties (advanced) | To set additional CXF options using the key/value pairs from the Map. For example to turn on stacktraces in SOAP faults, properties.faultStackTraceEnabled=true. | Map | |
| skipPayloadMessagePartCheck (advanced) | Sets whether SOAP message validation should be disabled. | false | boolean |
| loggingFeatureEnabled (logging) | This option enables CXF Logging Feature which writes inbound and outbound SOAP messages to log. | false | boolean |
| loggingSizeLimit (logging) | To limit the total size of number of bytes the logger will output when logging feature has been enabled and -1 for no limit. | 49152 | int |
| skipFaultLogging (logging) | This option controls whether the PhaseInterceptorChain skips logging the Fault that it catches. | false | boolean |
| password (security) | This option is used to set the basic authentication information of password for the CXF client. | String | |
| username (security) | This option is used to set the basic authentication information of username for the CXF client. | String | |
| bindingId (service) | The bindingId for the service model to use. | String | |
| portName (service) | The endpoint name this service is implementing, it maps to the wsdl:portname. In the format of ns:PORT_NAME where ns is a namespace prefix valid at this scope. | String | |
| publishedEndpointUrl (service) | This option can override the endpointUrl that published from the WSDL which can be accessed with service address url plus wsd. | String | |
| serviceClass (service) | The class name of the SEI (Service Endpoint Interface) class which could have JSR181 annotation or not. | Class | |
| serviceName (service) | The service name this service is implementing, it maps to the wsdl:servicename. | String | |
| wsdlURL (service) | The location of the WSDL. Can be on the classpath, file system, or be hosted remotely. | String |
The serviceName and portName are QNames, so if you provide them be sure to prefix them with their {namespace} as shown in the examples above.
29.5.3. Descriptions of the dataformats 링크 복사링크가 클립보드에 복사되었습니다!
In Apache Camel, the Camel CXF component is the key to integrating routes with Web services. You can use the Camel CXF component to create a CXF endpoint, which can be used in either of the following ways:
- Consumer — (at the start of a route) represents a Web service instance, which integrates with the route. The type of payload injected into the route depends on the value of the endpoint’s dataFormat option.
- Producer — (at other points in the route) represents a WS client proxy, which converts the current exchange object into an operation invocation on a remote Web service. The format of the current exchange must match the endpoint’s dataFormat setting.
| DataFormat | Description |
|---|---|
|
| POJOs (Plain old Java objects) are the Java parameters to the method being invoked on the target server. Both Protocol and Logical JAX-WS handlers are supported. |
|
|
|
|
|
|
|
|
|
You can determine the data format mode of an exchange by retrieving the exchange property, CamelCXFDataFormat. The exchange key constant is defined in org.apache.camel.component.cxf.common.message.CxfConstants.DATA_FORMAT_PROPERTY.
29.5.4. How to enable CXF’s LoggingOutInterceptor in RAW mode 링크 복사링크가 클립보드에 복사되었습니다!
CXF’s LoggingOutInterceptor outputs outbound message that goes on the wire to logging system (Java Util Logging). Since the LoggingOutInterceptor is in PRE_STREAM phase (but PRE_STREAM phase is removed in RAW mode), you have to configure LoggingOutInterceptor to be run during the WRITE phase. The following is an example.
29.5.5. Description of relayHeaders option 링크 복사링크가 클립보드에 복사되었습니다!
There are in-band and out-of-band on-the-wire headers from the perspective of a JAXWS WSDL-first developer.
The in-band headers are headers that are explicitly defined as part of the WSDL binding contract for an endpoint such as SOAP headers.
The out-of-band headers are headers that are serialized over the wire, but are not explicitly part of the WSDL binding contract.
Headers relaying/filtering is bi-directional.
When a route has a CXF endpoint and the developer needs to have on-the-wire headers, such as SOAP headers, be relayed along the route to be consumed say by another JAXWS endpoint, then relayHeaders should be set to true, which is the default value.
29.5.6. Available only in POJO mode 링크 복사링크가 클립보드에 복사되었습니다!
The relayHeaders=true expresses an intent to relay the headers. The actual decision on whether a given header is relayed is delegated to a pluggable instance that implements the MessageHeadersRelay interface. A concrete implementation of MessageHeadersRelay will be consulted to decide if a header needs to be relayed or not. There is already an implementation of SoapMessageHeadersRelay which binds itself to well-known SOAP name spaces. Currently only out-of-band headers are filtered, and in-band headers will always be relayed when relayHeaders=true. If there is a header on the wire whose name space is unknown to the runtime, then a fall back DefaultMessageHeadersRelay will be used, which simply allows all headers to be relayed.
The relayHeaders=false setting specifies that all headers in-band and out-of-band should be dropped.
You can plugin your own MessageHeadersRelay implementations overriding or adding additional ones to the list of relays. In order to override a preloaded relay instance just make sure that your MessageHeadersRelay implementation services the same name spaces as the one you looking to override. Also note, that the overriding relay has to service all of the name spaces as the one you looking to override, or else a runtime exception on route start up will be thrown as this would introduce an ambiguity in name spaces to relay instance mappings.
Take a look at the tests that show how you’d be able to relay/drop headers here:
-
POJOandPAYLOADmodes are supported. InPOJOmode, only out-of-band message headers are available for filtering as the in-band headers have been processed and removed from header list by CXF. The in-band headers are incorporated into theMessageContentListin POJO mode. Thecamel-cxfcomponent does make any attempt to remove the in-band headers from theMessageContentList. If filtering of in-band headers is required, please usePAYLOADmode or plug in a (pretty straightforward) CXF interceptor/JAXWS Handler to the CXF endpoint. -
The Message Header Relay mechanism has been merged into
CxfHeaderFilterStrategy. TherelayHeadersoption, its semantics, and default value remain the same, but it is a property ofCxfHeaderFilterStrategy. Here is an example of configuring it.
Then, your endpoint can reference the CxfHeaderFilterStrategy.
Then configure the route as follows:
rom("cxf:bean:routerNoRelayEndpoint")
.to("cxf:bean:serviceNoRelayEndpoint");
rom("cxf:bean:routerNoRelayEndpoint")
.to("cxf:bean:serviceNoRelayEndpoint");
-
The
MessageHeadersRelayinterface has changed slightly and has been renamed toMessageHeaderFilter. It is a property ofCxfHeaderFilterStrategy. Here is an example of configuring user defined Message Header Filters:
-
In addition to
relayHeaders, the following properties can be configured inCxfHeaderFilterStrategy.
| Name | Required | Description |
|---|---|---|
|
| No |
All message headers will be processed by Message Header Filters Type: |
|
| No |
All message headers will be propagated (without processing by Message Header Filters) Type: |
|
| No |
If two filters overlap in activation namespace, the property control how it should be handled. If the value is |
29.6. Configure the CXF endpoints with Spring 링크 복사링크가 클립보드에 복사되었습니다!
You can configure the CXF endpoint with the Spring configuration file shown below, and you can also embed the endpoint into the camelContext tags. When you are invoking the service endpoint, you can set the operationName and operationNamespace headers to explicitly state which operation you are calling.
Be sure to include the JAX-WS schemaLocation attribute specified on the root beans element. This allows CXF to validate the file and is required. Also note the namespace declarations at the end of the <cxf:cxfEndpoint/> tag. These declarations are required because the combined {namespace}localName syntax is presently not supported for this tag’s attribute values.
The cxf:cxfEndpoint element supports many additional attributes:
| Name | Value |
|---|---|
|
|
The endpoint name this service is implementing, it maps to the |
|
|
The service name this service is implementing, it maps to the |
|
| The location of the WSDL. Can be on the classpath, file system, or be hosted remotely. |
|
|
The |
|
| The service publish address. |
|
| The bus name that will be used in the JAX-WS endpoint. |
|
| The class name of the SEI (Service Endpoint Interface) class which could have JSR181 annotation or not. |
It also supports many child elements:
| Name | Value |
|---|---|
|
|
The incoming interceptors for this endpoint. A list of |
|
|
The incoming fault interceptors for this endpoint. A list of |
|
|
The outgoing interceptors for this endpoint. A list of |
|
|
The outgoing fault interceptors for this endpoint. A list of |
|
| A properties map which should be supplied to the JAX-WS endpoint. See below. |
|
| A JAX-WS handler list which should be supplied to the JAX-WS endpoint. See below. |
|
|
You can specify the which |
|
|
You can specify the |
|
| The features that hold the interceptors for this endpoint. A list of beans or refs |
|
| The schema locations for endpoint to use. A list of schemaLocations |
|
|
The service factory for this endpoint to use. This can be supplied using the Spring |
You can find more advanced examples that show how to provide interceptors, properties and handlers on the CXF JAX-WS Configuration page.
You can use cxf:properties to set the camel-cxf endpoint’s dataFormat and setDefaultBus properties from spring configuration file.
In SpringBoot, you can use Spring XML files to configure camel-cxf and use code similar to the following example to create XML configured beans:
@ImportResource({
"classpath:spring-configuration.xml"
})
@ImportResource({
"classpath:spring-configuration.xml"
})
However, the use of Java code configured beans (as shown in other examples) is best practice in SpringBoot.
29.7. How to make the camel-cxf component use log4j instead of java.util.logging 링크 복사링크가 클립보드에 복사되었습니다!
CXF’s default logger is java.util.logging. If you want to change it to log4j, proceed as follows. Create a file, in the classpath, named META-INF/cxf/org.apache.cxf.logger. This file should contain the fully-qualified name of the class, org.apache.cxf.common.logging.Log4jLogger, with no comments, on a single line.
29.8. How to let camel-cxf response start with xml processing instruction 링크 복사링크가 클립보드에 복사되었습니다!
If you are using some SOAP client such as PHP, you will get this kind of error, because CXF doesn’t add the XML processing instruction <?xml version="1.0" encoding="utf-8"?>:
Error:sendSms: SoapFault exception: [Client] looks like we got no XML document in [...]
Error:sendSms: SoapFault exception: [Client] looks like we got no XML document in [...]
To resolve this issue, you just need to tell StaxOutInterceptor to write the XML start document for you, as in the WriteXmlDeclarationInterceptor below:
As an alternative you can add a message header for it as demonstrated in CxfConsumerTest:
// set up the response context which force start document
Map<String, Object> map = new HashMap<String, Object>();
map.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE);
exchange.getOut().setHeader(Client.RESPONSE_CONTEXT, map);
// set up the response context which force start document
Map<String, Object> map = new HashMap<String, Object>();
map.put("org.apache.cxf.stax.force-start-document", Boolean.TRUE);
exchange.getOut().setHeader(Client.RESPONSE_CONTEXT, map);
29.9. How to override the CXF producer address from message header 링크 복사링크가 클립보드에 복사되었습니다!
The camel-cxf producer supports to override the target service address by setting a message header CamelDestinationOverrideUrl.
// set up the service address from the message header to override the setting of CXF endpoint exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, constant(getServiceAddress()));
// set up the service address from the message header to override the setting of CXF endpoint
exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, constant(getServiceAddress()));
29.10. How to consume a message from a camel-cxf endpoint in POJO data format 링크 복사링크가 클립보드에 복사되었습니다!
The camel-cxf endpoint consumer POJO data format is based on the CXF invoker, so the message header has a property with the name of CxfConstants.OPERATION_NAME and the message body is a list of the SEI method parameters.
Consider the PersonProcessor example code:
29.11. How to prepare the message for the camel-cxf endpoint in POJO data format 링크 복사링크가 클립보드에 복사되었습니다!
The camel-cxf endpoint producer is based on the CXF client API. First you need to specify the operation name in the message header, then add the method parameters to a list, and initialize the message with this parameter list. The response message’s body is a messageContentsList, you can get the result from that list.
If you don’t specify the operation name in the message header, CxfProducer will try to use the defaultOperationName from CxfEndpoint, if there is no defaultOperationName set on CxfEndpoint, it will pick up the first operationName from the Operation list.
If you want to get the object array from the message body, you can get the body using message.getBody(Object[].class), as shown in CxfProducerRouterTest.testInvokingSimpleServerWithParams:
29.12. How to deal with the message for a camel-cxf endpoint in PAYLOAD data format 링크 복사링크가 클립보드에 복사되었습니다!
PAYLOAD means that you process the payload from the SOAP envelope as a native CxfPayload. Message.getBody() will return a org.apache.camel.component.cxf.CxfPayload object, with getters for SOAP message headers and the SOAP body.
29.13. How to get and set SOAP headers in POJO mode 링크 복사링크가 클립보드에 복사되었습니다!
POJO means that the data format is a "list of Java objects" when the camel-cxf endpoint produces or consumes Camel exchanges. Even though Camel exposes the message body as POJOs in this mode, camel-cxf still provides access to read and write SOAP headers. However, since CXF interceptors remove in-band SOAP headers from the header list after they have been processed, only out-of-band SOAP headers are available to camel-cxf in POJO mode.
The following example illustrates how to get/set SOAP headers. Suppose we have a route that forwards from one Camel-cxf endpoint to another. That is, SOAP Client → Camel → CXF service. We can attach two processors to obtain/insert SOAP headers at (1) before a request goes out to the CXF service and (2) before the response comes back to the SOAP Client. Processor (1) and (2) in this example are InsertRequestOutHeaderProcessor and InsertResponseOutHeaderProcessor. Our route looks like this:
from("cxf:bean:routerRelayEndpointWithInsertion")
.process(new InsertRequestOutHeaderProcessor())
.to("cxf:bean:serviceRelayEndpointWithInsertion")
.process(new InsertResponseOutHeaderProcessor());
from("cxf:bean:routerRelayEndpointWithInsertion")
.process(new InsertRequestOutHeaderProcessor())
.to("cxf:bean:serviceRelayEndpointWithInsertion")
.process(new InsertResponseOutHeaderProcessor());
The Bean routerRelayEndpointWithInsertion and serviceRelayEndpointWithInsertion are defined as follows:
SOAP headers are propagated to and from Camel Message headers. The Camel message header name is "org.apache.cxf.headers.Header.list" which is a constant defined in CXF (org.apache.cxf.headers.Header.HEADER_LIST). The header value is a List of CXF SoapHeader objects (org.apache.cxf.binding.soap.SoapHeader). The following snippet is the InsertResponseOutHeaderProcessor (that insert a new SOAP header in the response message). The way to access SOAP headers in both InsertResponseOutHeaderProcessor and InsertRequestOutHeaderProcessor are actually the same. The only difference between the two processors is setting the direction of the inserted SOAP header.
You can find the InsertResponseOutHeaderProcessor example in CxfMessageHeadersRelayTest:
29.14. How to get and set SOAP headers in PAYLOAD mode 링크 복사링크가 클립보드에 복사되었습니다!
We’ve already shown how to access the SOAP message as CxfPayload object in PAYLOAD mode inm the section How to deal with the message for a camel-cxf endpoint in PAYLOAD data format.
Once you obtain a CxfPayload object, you can invoke the CxfPayload.getHeaders() method that returns a List of DOM Elements (SOAP headers).
For an example see CxfPayLoadSoapHeaderTest:
You can also use the same way as described in sub-chapter "How to get and set SOAP headers in POJO mode" to set or get the SOAP headers. So, you can use the header "org.apache.cxf.headers.Header.list" to get and set a list of SOAP headers.This does also mean that if you have a route that forwards from one Camel-cxf endpoint to another (SOAP Client → Camel → CXF service), now also the SOAP headers sent by the SOAP client are forwarded to the CXF service. If you do not want that these headers are forwarded you have to remove them in the Camel header "org.apache.cxf.headers.Header.list".
29.15. SOAP headers are not available in RAW mode 링크 복사링크가 클립보드에 복사되었습니다!
SOAP headers are not available in RAW mode as SOAP processing is skipped.
29.16. How to throw a SOAP Fault from Camel 링크 복사링크가 클립보드에 복사되었습니다!
If you are using a camel-cxf endpoint to consume the SOAP request, you may need to throw the SOAP Fault from the camel context.
Basically, you can use the throwFault DSL to do that; it works for POJO, PAYLOAD and MESSAGE data format.
You can define the soap fault as shown in CxfCustomizedExceptionTest:
SOAP_FAULT = new SoapFault(EXCEPTION_MESSAGE, SoapFault.FAULT_CODE_CLIENT); Element detail = SOAP_FAULT.getOrCreateDetail(); Document doc = detail.getOwnerDocument(); Text tn = doc.createTextNode(DETAIL_TEXT); detail.appendChild(tn);
SOAP_FAULT = new SoapFault(EXCEPTION_MESSAGE, SoapFault.FAULT_CODE_CLIENT);
Element detail = SOAP_FAULT.getOrCreateDetail();
Document doc = detail.getOwnerDocument();
Text tn = doc.createTextNode(DETAIL_TEXT);
detail.appendChild(tn);
Then throw it as you like
from(routerEndpointURI).setFaultBody(constant(SOAP_FAULT));
from(routerEndpointURI).setFaultBody(constant(SOAP_FAULT));
If your CXF endpoint is working in the MESSAGE data format, you could set the SOAP Fault message in the message body and set the response code in the message header as demonstrated by CxfMessageStreamExceptionTest
Same for using POJO data format. You can set the SOAPFault on the out body.
29.17. How to propagate a camel-cxf endpoint’s request and response context 링크 복사링크가 클립보드에 복사되었습니다!
CXF client API provides a way to invoke the operation with request and response context. If you are using a camel-cxf endpoint producer to invoke the outside web service, you can set the request context and get response context with the following code:
29.18. Attachment Support 링크 복사링크가 클립보드에 복사되었습니다!
POJO Mode: Both SOAP with Attachment and MTOM are supported (see example in Payload Mode for enabling MTOM). However, SOAP with Attachment is not tested. Since attachments are marshalled and unmarshalled into POJOs, users typically do not need to deal with the attachment themself. Attachments are propagated to Camel message’s attachments if the MTOM is not enabled. So, it is possible to retrieve attachments by Camel Message API
DataHandler Message.getAttachment(String id)
DataHandler Message.getAttachment(String id)
Payload Mode: MTOM is supported by the component. Attachments can be retrieved by Camel Message APIs mentioned above. SOAP with Attachment (SwA) is supported and attachments can be retrieved. SwA is the default (same as setting the CXF endpoint property "mtom-enabled" to false).
To enable MTOM, set the CXF endpoint property "mtom-enabled" to true.
You can produce a Camel message with attachment to send to a CXF endpoint in Payload mode.
You can also consume a Camel message received from a CXF endpoint in Payload mode. The CxfMtomConsumerPayloadModeTest illustrates how this works:
Raw Mode: Attachments are not supported as it does not process the message at all.
CXF_RAW Mode: MTOM is supported, and Attachments can be retrieved by Camel Message APIs mentioned above. Note that when receiving a multipart (i.e. MTOM) message the default SOAPMessage to String converter will provide the complete multipart payload on the body. If you require just the SOAP XML as a String, you can set the message body with message.getSOAPPart(), and Camel convert can do the rest of work for you.
29.19. Streaming Support in PAYLOAD mode 링크 복사링크가 클립보드에 복사되었습니다!
The camel-cxf component now supports streaming of incoming messages when using PAYLOAD mode. Previously, the incoming messages would have been completely DOM parsed. For large messages, this is time consuming and uses a significant amount of memory. The incoming messages can remain as a javax.xml.transform.Source while being routed and, if nothing modifies the payload, can then be directly streamed out to the target destination. For common "simple proxy" use cases (example: from("cxf:…").to("cxf:…")), this can provide very significant performance increases as well as significantly lowered memory requirements.
However, there are cases where streaming may not be appropriate or desired. Due to the streaming nature, invalid incoming XML may not be caught until later in the processing chain. Also, certain actions may require the message to be DOM parsed anyway (like WS-Security or message tracing and such) in which case the advantages of the streaming is limited. At this point, there are two ways to control the streaming:
- Endpoint property: you can add "allowStreaming=false" as an endpoint property to turn the streaming on/off.
- Component property: the CxfComponent object also has an allowStreaming property that can set the default for endpoints created from that component.
Global system property: you can add a system property of "org.apache.camel.component.cxf.streaming" to "false" to turn it off. That sets the global default, but setting the endpoint property above will override this value for that endpoint.
29.20. Using the generic CXF Dispatch mode 링크 복사링크가 클립보드에 복사되었습니다!
The camel-cxf component supports the generic CXF dispatch mode that can transport messages of arbitrary structures (i.e., not bound to a specific XML schema). To use this mode, you simply omit specifying the wsdlURL and serviceClass attributes of the CXF endpoint.
<cxf:cxfEndpoint id="testEndpoint" address="http://localhost:9000/SoapContext/SoapAnyPort">
<cxf:properties>
<entry key="dataFormat" value="PAYLOAD"/>
</cxf:properties>
</cxf:cxfEndpoint>
<cxf:cxfEndpoint id="testEndpoint" address="http://localhost:9000/SoapContext/SoapAnyPort">
<cxf:properties>
<entry key="dataFormat" value="PAYLOAD"/>
</cxf:properties>
</cxf:cxfEndpoint>
It is noted that the default CXF dispatch client does not send a specific SOAPAction header. Therefore, when the target service requires a specific SOAPAction value, it is supplied in the Camel header using the key SOAPAction (case-insensitive).
29.21. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 13 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.cxf.allow-streaming | This option controls whether the CXF component, when running in PAYLOAD mode, will DOM parse the incoming messages into DOM Elements or keep the payload as a javax.xml.transform.Source object that would allow streaming in some cases. | Boolean | |
| camel.component.cxf.autowired-enabled | 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 |
| camel.component.cxf.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.cxf.enabled | Whether to enable auto configuration of the cxf component. This is enabled by default. | Boolean | |
| camel.component.cxf.header-filter-strategy | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. The option is a org.apache.camel.spi.HeaderFilterStrategy type. | HeaderFilterStrategy | |
| camel.component.cxf.lazy-start-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 |
| camel.component.cxf.use-global-ssl-context-parameters | Enable usage of global SSL context parameters. | false | Boolean |
| camel.component.cxfrs.autowired-enabled | 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 |
| camel.component.cxfrs.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.cxfrs.enabled | Whether to enable auto configuration of the cxfrs component. This is enabled by default. | Boolean | |
| camel.component.cxfrs.header-filter-strategy | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. The option is a org.apache.camel.spi.HeaderFilterStrategy type. | HeaderFilterStrategy | |
| camel.component.cxfrs.lazy-start-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 |
| camel.component.cxfrs.use-global-ssl-context-parameters | Enable usage of global SSL context parameters. | false | Boolean |
Chapter 30. CXF-RS 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The CXFRS component provides integration with Apache CXF for connecting to JAX-RS 1.1 and 2.0 services hosted in CXF.
30.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using camel-cxf-rest with Red Hat build of Camel Spring Boot, add the following Maven dependency to your pom.xml to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-cxf-rest-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-cxf-rest-starter</artifactId>
</dependency>
30.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
cxfrs://address?options
cxfrs://address?options
Where the address represents the address of the CXF endpoint.
cxfrs:bean:rsEndpoint
cxfrs:bean:rsEndpoint
Where the rsEndpoint represents the name of the spring bean, which presents the CXFRS client or server.
For the formats above, you can append options to the URI as follows:
cxfrs:bean:cxfEndpoint?resourceClasses=org.apache.camel.rs.Example
cxfrs:bean:cxfEndpoint?resourceClasses=org.apache.camel.rs.Example
30.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
30.3.1. 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.
30.3.2. 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.
30.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The CXF-RS component supports 5 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| 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 |
| 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 |
| headerFilterStrategy (filter) | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | |
| useGlobalSslContextParameters (security) | Enable usage of global SSL context parameters. | false | boolean |
30.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The CXF-RS endpoint is configured using URI syntax:
cxfrs:beanId:address
cxfrs:beanId:address
With the following path and query parameters:
30.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| beanId (common) |
To lookup an existing configured CxfRsEndpoint. Must use | String | |
| address (common) | The service publish address. | String |
30.5.2. Query Parameters (31 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| features (common) | Set the feature list to the CxfRs endpoint. | List | |
| loggingFeatureEnabled (common) | This option enables CXF Logging Feature which writes inbound and outbound REST messages to log. | false | boolean |
| loggingSizeLimit (common) | To limit the total size of number of bytes the logger will output when logging feature has been enabled. | int | |
| modelRef (common) | This option is used to specify the model file which is useful for the resource class without annotation. When using this option, then the service class can be omitted, to emulate document-only endpoints. | String | |
| providers (common) | Set custom JAX-RS provider(s) list to the CxfRs endpoint. You can specify a string with a list of providers to lookup in the registy separated by comma. | String | |
| resourceClasses (common) | The resource classes which you want to export as REST service. Multiple classes can be separated by comma. | List | |
| schemaLocations (common) | Sets the locations of the schema(s) which can be used to validate the incoming XML or JAXB-driven JSON. | List | |
| skipFaultLogging (common) | This option controls whether the PhaseInterceptorChain skips logging the Fault that it catches. | false | boolean |
| bindingStyle (consumer) | Sets how requests and responses will be mapped to/from Camel. Two values are possible: SimpleConsumer: This binding style processes request parameters, multiparts, etc. and maps them to IN headers, IN attachments and to the message body. It aims to eliminate low-level processing of org.apache.cxf.message.MessageContentsList. It also also adds more flexibility and simplicity to the response mapping. Only available for consumers. Default: The default style. For consumers this passes on a MessageContentsList to the route, requiring low-level processing in the route. This is the traditional binding style, which simply dumps the org.apache.cxf.message.MessageContentsList coming in from the CXF stack onto the IN message body. The user is then responsible for processing it according to the contract defined by the JAX-RS method signature. Custom: allows you to specify a custom binding through the binding option. Enum values:
| Default | BindingStyle |
| publishedEndpointUrl (consumer) | This option can override the endpointUrl that published from the WADL which can be accessed with resource address url plus _wadl. | String | |
| 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:
| ExchangePattern | |
| serviceBeans (consumer (advanced)) | The service beans (the bean ids to lookup in the registry) which you want to export as REST service. Multiple beans can be separated by comma. | String | |
| cookieHandler (producer) | Configure a cookie handler to maintain a HTTP session. | CookieHandler | |
| hostnameVerifier (producer) | The hostname verifier to be used. Use the # notation to reference a HostnameVerifier from the registry. | HostnameVerifier | |
| sslContextParameters (producer) | The Camel SSL setting reference. Use the # notation to reference the SSL Context. | SSLContextParameters | |
| throwExceptionOnFailure (producer) | This option tells the CxfRsProducer to inspect return codes and will generate an Exception if the return code is larger than 207. | true | boolean |
| httpClientAPI (producer (advanced)) | If it is true, the CxfRsProducer will use the HttpClientAPI to invoke the service. If it is false, the CxfRsProducer will use the ProxyClientAPI to invoke the service. | true | boolean |
| ignoreDeleteMethodMessageBody (producer (advanced)) | This option is used to tell CxfRsProducer to ignore the message body of the DELETE method when using HTTP API. | false | boolean |
| 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 |
| maxClientCacheSize (producer (advanced)) | This option allows you to configure the maximum size of the cache. The implementation caches CXF clients or ClientFactoryBean in CxfProvider and CxfRsProvider. | 10 | int |
| synchronous (producer (advanced)) | Sets whether synchronous processing should be strictly used. | false | boolean |
| binding (advanced) | To use a custom CxfBinding to control the binding between Camel Message and CXF Message. | CxfRsBinding | |
| bus (advanced) | To use a custom configured CXF Bus. | Bus | |
| continuationTimeout (advanced) | This option is used to set the CXF continuation timeout which could be used in CxfConsumer by default when the CXF server is using Jetty or Servlet transport. | 30000 | long |
| cxfRsConfigurer (advanced) | This option could apply the implementation of org.apache.camel.component.cxf.jaxrs.CxfRsEndpointConfigurer which supports to configure the CXF endpoint in programmatic way. User can configure the CXF server and client by implementing configure\\{Server/Client} method of CxfEndpointConfigurer. | CxfRsConfigurer | |
| defaultBus (advanced) | Will set the default bus when CXF endpoint create a bus by itself. | false | boolean |
| headerFilterStrategy (advanced) | To use a custom HeaderFilterStrategy to filter header to and from Camel message. | HeaderFilterStrategy | |
| performInvocation (advanced) | When the option is true, Camel will perform the invocation of the resource class instance and put the response object into the exchange for further processing. | false | boolean |
| propagateContexts (advanced) | When the option is true, JAXRS UriInfo, HttpHeaders, Request and SecurityContext contexts will be available to custom CXFRS processors as typed Camel exchange properties. These contexts can be used to analyze the current requests using JAX-RS API. | false | boolean |
30.6. Message Headers 링크 복사링크가 클립보드에 복사되었습니다!
The CXF-RS component supports 16 message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| operationName (common) Constant: OPERATION_NAME | The name of the operation. | String | |
| CamelAuthentication (common) Constant: AUTHENTICATION | The authentication. | Subject | |
| CamelHttpMethod (common) Constant: HTTP_METHOD | The http method to use. | String | |
| CamelHttpPath (common) Constant: HTTP_PATH | The http path. | String | |
| Content-Type (common) Constant: CONTENT_TYPE | The content type. | String | |
| CamelHttpQuery (common) Constant: HTTP_QUERY | The http query. | String | |
| CamelHttpResponseCode (common) Constant: HTTP_RESPONSE_CODE | The http response code. | Integer | |
| Content-Encoding (common) Constant: CONTENT_ENCODING | The content encoding. | String | |
| org.apache.cxf.message.Message.PROTOCOL_HEADERS (common) Constant: PROTOCOL_HEADERS | The protocol headers. | Map | |
| CamelCxfMessage (common) Constant: CAMEL_CXF_MESSAGE | The CXF message. | Message | |
| CamelCxfRsUsingHttpAPI (common) Constant: CAMEL_CXF_RS_USING_HTTP_API | If it is true, the CxfRsProducer will use the HttpClientAPI to invoke the service. If it is false, the CxfRsProducer will use the ProxyClientAPI to invoke the service. | Boolean | |
| CamelCxfRsVarValues (common) Constant: CAMEL_CXF_RS_VAR_VALUES | The path values. | Object[] | |
| CamelCxfRsResponseClass (common) Constant: CAMEL_CXF_RS_RESPONSE_CLASS | The response class. | Class | |
| CamelCxfRsResponseGenericType (common) Constant: CAMEL_CXF_RS_RESPONSE_GENERIC_TYPE | The response generic type. | Type | |
| CamelCxfRsQueryMap (common) Constant: CAMEL_CXF_RS_QUERY_MAP | The query map. | Map | |
| CamelCxfRsOperationResourceInfoStack (common) | The stack of MethodInvocationInfo representing resources path when JAX-RS invocation looks for target. | OperationResourceInfoStack |
You can also configure the CXF REST endpoint through the spring configuration.
Avoid creating your own HTTP server instances in a Camel Spring Boot application by using either of the cxf-rt-transports-jetty, cxf-rt-transports-netty-server, cxf-rt-transports-undertow libraries. It is recommended to use the Spring Boot embedded HTTP server stack which is created when you use the spring-boot-starter-web, cxf-spring-boot-starter-jaxrs, or cxf-spring-boot-starter-jaxws dependencies.
Since there are lots of differences between the CXF REST client and CXF REST Server, we provide different configuration for them.
+ Please check the following files for more details:
30.7. How to configure the REST endpoint in Camel 링크 복사링크가 클립보드에 복사되었습니다!
In the camel-cxf schema file, there are two elements for the REST endpoint definition:
-
cxf:rsServerfor REST consumer -
cxf:rsClientfor REST producer.
You can find a Camel REST service route configuration example there.
30.8. How to override the CXF producer address from message header 링크 복사링크가 클립보드에 복사되었습니다!
The camel-cxfrs producer supports overriding the service address by setting the message with the key of CamelDestinationOverrideUrl.
// set up the service address from the message header to override the setting of CXF endpoint exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, constant(getServiceAddress()));
// set up the service address from the message header to override the setting of CXF endpoint
exchange.getIn().setHeader(Exchange.DESTINATION_OVERRIDE_URL, constant(getServiceAddress()));
30.9. Consuming a REST Request - Simple Binding Style 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 2.11
The Default binding style is rather low-level, requiring the user to manually process the MessageContentsList object coming into the route. Thus, it tightly couples the route logic with the method signature and parameter indices of the JAX-RS operation which is somewhat inelegant, difficult and error-prone.
In contrast, the SimpleConsumer binding style performs the following mappings, to make the request data more accessible to you within the Camel Message:
-
JAX-RS Parameters (
@HeaderParam,@QueryParam, etc.) are injected as IN message headers. The header name matches the value of the annotation. -
The request entity (POJO or another type) becomes the IN message body. If a single entity cannot be identified in the JAX-RS method signature, it falls back to the original
MessageContentsList. -
Binary
@Multipartbody parts become IN message attachments, supportingDataHandler,InputStream,DataSourceand CXF’sAttachmentclass. -
Non-binary
@Multipartbody parts are mapped as IN message headers. The header name matches the Body Part name.
Additionally, the following rules apply to the Response mapping:
-
If the message body type is different to
javax.ws.rs.core.Response(user-built response), a newResponseis created and the message body is set as the entity (so long it’s not null). The response status code is taken from theExchange.HTTP_RESPONSE_CODEheader, or defaults to 200 OK if not present. -
If the message body type is equal to
javax.ws.rs.core.Response, it means that the user has built a custom response, and therefore it is respected, and it becomes the final response. -
In all cases, Camel headers permitted by custom or default
HeaderFilterStrategyare added to the HTTP response.
30.9.1. Enabling the Simple Binding Style 링크 복사링크가 클립보드에 복사되었습니다!
This binding style can be activated by setting the bindingStyle parameter in the consumer endpoint to value SimpleConsumer:
from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
.to("log:TEST?showAll=true");
from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
.to("log:TEST?showAll=true");
30.9.2. Examples of request binding with different method signatures 링크 복사링크가 클립보드에 복사되었습니다!
Below is a list of method signatures along with the expected result from the simple binding:
-
public Response doAction(BusinessObject request);: the request payload is placed in tbe IN message body, replacing the original MessageContentsList. -
public Response doAction(BusinessObject request, @HeaderParam("abcd") String abcd, @QueryParam("defg") String defg);: the request payload is placed in the IN message body, replacing the originalMessageContentsList. Both request parameters are mapped as IN message headers with names "abcd" and "defg". -
public Response doAction(@HeaderParam("abcd") String abcd, @QueryParam("defg") String defg);: both request parameters are mapped as the IN message headers with names "abcd" and "defg". The originalMessageContentsListis preserved, even though it only contains the two parameters. -
public Response doAction(@Multipart(value="body1") BusinessObject request, @Multipart(value="body2") BusinessObject request2);: the first parameter is transferred as a header with name "body1", and the second one is mapped as header "body2". The originalMessageContentsListis preserved as the IN message body. -
public Response doAction(InputStream abcd);: theInputStreamis unwrapped from theMessageContentsListand preserved as the IN message body. -
public Response doAction(DataHandler abcd);: the DataHandler is unwrapped from theMessageContentsListand preserved as the IN message body.
30.9.3. Examples of the Simple Binding Style 링크 복사링크가 클립보드에 복사되었습니다!
Given a JAX-RS resource class with this method:
@POST @Path("/customers/{type}")
public Response newCustomer(Customer customer, @PathParam("type") String type, @QueryParam("active") @DefaultValue("true") boolean active) {
return null;
}
@POST @Path("/customers/{type}")
public Response newCustomer(Customer customer, @PathParam("type") String type, @QueryParam("active") @DefaultValue("true") boolean active) {
return null;
}
Serviced by the following route:
from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
.recipientList(simple("direct:${header.operationName}"));
from("direct:newCustomer")
.log("Request: type=${header.type}, active=${header.active}, customerData=${body}");
from("cxfrs:bean:rsServer?bindingStyle=SimpleConsumer")
.recipientList(simple("direct:${header.operationName}"));
from("direct:newCustomer")
.log("Request: type=${header.type}, active=${header.active}, customerData=${body}");
The following HTTP request with XML payload (given that the Customer DTO is JAXB-annotated):
Will print the message:
Request: type=gold, active=true, customerData=<Customer.toString() representation>
Request: type=gold, active=true, customerData=<Customer.toString() representation>
- NOTE
- More examples on how to process requests and write responses can be found here .
30.10. Consuming a REST Request - Default Binding Style 링크 복사링크가 클립보드에 복사되었습니다!
The CXF JAXRS front end implements the JAX-RS (JSR-311) API, so we can export the resource classes as a REST service. We leverage the CXF Invoker API to turn a REST request into a normal Java object method invocation.There is no need to specify the URI template within your endpoint. The CXF takes care of the REST request URI to resource class method mapping according to the JSR-311 specification. All you need to do in Camel is delegate this method request to the right processor or endpoint.
CXFRS route example
And the corresponding resource class is used to configure the endpoint.
- NOTE
- By default, JAX-RS resource classes are only used to configure JAX-RS properties. Methods will not be executed during routing of messages to the endpoint. Instead, it is the responsibility of the route to do all processing.
It is sufficient to provide an interface only as opposed to a no-op service implementation class for the default mode.
If a performInvocation option is enabled, the service implementation will be invoked first, the response will be set on the Camel exchange, and the route execution will continue as usual. This can be useful for integrating the existing JAX-RS implementations into Camel routes and for post-processing JAX-RS Responses in custom processors.
30.11. How to invoke the REST service through camel-cxfrs producer 링크 복사링크가 클립보드에 복사되었습니다!
The CXF JAXRS front end implements a proxy-based client API. With this API you can invoke the remote REST service through a proxy. The camel-cxfrs producer is based on this proxy API. You can specify the operation name in the message header and prepare the parameter in the message body, the camel-cxfrs producer will generate the right REST request for you.
Example
The CXF JAXRS front end also provides an HTTP centric client API. You can also invoke this API from camel-cxfrs producer. You need to specify the HTTP_PATH and the HTTP_METHOD and let the producer use the http centric client API by using the URI option httpClientAPI or by setting the message header CxfConstants.CAMEL_CXF_RS_USING_HTTP_API. You can turn the response object to the type class specified with the message header CxfConstants.CAMEL_CXF_RS_RESPONSE_CLASS.
You can also specify the query parameters from cxfrs URI for the CXFRS http centric client.
Exchange exchange = template.send("cxfrs://http://localhost:9003/testQuery?httpClientAPI=true&q1=12&q2=13"
Exchange exchange = template.send("cxfrs://http://localhost:9003/testQuery?httpClientAPI=true&q1=12&q2=13"
To support the Dynamical routing, you can override the URI’s query parameters by using the CxfConstants.CAMEL_CXF_RS_QUERY_MAP header to set the parameter map for it.
Map<String, String> queryMap = new LinkedHashMap<>();
queryMap.put("q1", "new");
queryMap.put("q2", "world");
inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_QUERY_MAP, queryMap);
Map<String, String> queryMap = new LinkedHashMap<>();
queryMap.put("q1", "new");
queryMap.put("q2", "world");
inMessage.setHeader(CxfConstants.CAMEL_CXF_RS_QUERY_MAP, queryMap);
30.12. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 6 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.cxfrs.autowired-enabled | 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 |
| camel.component.cxfrs.bridge-error-handler | 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 |
| camel.component.cxfrs.enabled | Whether to enable auto configuration of the cxfrs component. This is enabled by default. | Boolean | |
| camel.component.cxfrs.header-filter-strategy | To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. The option is a org.apache.camel.spi.HeaderFilterStrategy type. | HeaderFilterStrategy | |
| camel.component.cxfrs.lazy-start-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 |
| camel.component.cxfrs.use-global-ssl-context-parameters | Enable usage of global SSL context parameters. | false | Boolean |
Chapter 31. Data Format 링크 복사링크가 클립보드에 복사되었습니다!
Only producer is supported
The Dataformat component allows to use the Data Format as a Camel Component.
31.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using dataformat with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-dataformat-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-dataformat-starter</artifactId>
</dependency>
31.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
dataformat:name:(marshal|unmarshal)[?options]
dataformat:name:(marshal|unmarshal)[?options]
Where name is the name of the Data Format. And then followed by the operation which must either be marshal or unmarshal. The options is used for configuring the Data Format in use. See the Data Format documentation for which options it support.
31.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
31.3.1. 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.
31.3.2. 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.
31.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Data Format component supports 2 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| 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 |
31.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Data Format endpoint is configured using URI syntax:
dataformat:name:operation
dataformat:name:operation
with the following path and query parameters:
31.5.1. Path Parameters (2 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| name (producer) | Required Name of data format. | String | |
| operation (producer) | Required Operation to use either marshal or unmarshal. Enum values:
| String |
31.5.2. Query Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| 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 |
31.6. Samples 링크 복사링크가 클립보드에 복사되었습니다!
For example to use the JAXB Data Format we can do as follows:
from("activemq:My.Queue").
to("dataformat:jaxb:unmarshal?contextPath=com.acme.model").
to("mqseries:Another.Queue");
from("activemq:My.Queue").
to("dataformat:jaxb:unmarshal?contextPath=com.acme.model").
to("mqseries:Another.Queue");
And in XML DSL you do:
31.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 3 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.dataformat.autowired-enabled | 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 |
| camel.component.dataformat.enabled | Whether to enable auto configuration of the dataformat component. This is enabled by default. | Boolean | |
| camel.component.dataformat.lazy-start-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 |
Chapter 32. Dataset 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
Testing of distributed and asynchronous processing is notoriously difficult. The Mock, Test and DataSet endpoints work great with the Camel Testing Framework to simplify your unit and integration testing using Enterprise Integration Patterns and Camel’s large range of Components together with the powerful Bean Integration.
The DataSet component provides a mechanism to easily perform load & soak testing of your system. It works by allowing you to create DataSet instances both as a source of messages and as a way to assert that the data set is received.
Camel will use the throughput logger when sending datasets.
32.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using dataset with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-dataset-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-dataset-starter</artifactId>
</dependency>
32.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
dataset:name[?options]
dataset:name[?options]
Where name is used to find the DataSet instance in the Registry
Camel ships with a support implementation of org.apache.camel.component.dataset.DataSet, the org.apache.camel.component.dataset.DataSetSupport class, that can be used as a base for implementing your own DataSet. Camel also ships with some implementations that can be used for testing: org.apache.camel.component.dataset.SimpleDataSet, org.apache.camel.component.dataset.ListDataSet and org.apache.camel.component.dataset.FileDataSet, all of which extend DataSetSupport.
32.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
32.3.1. 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.
32.3.2. 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.
32.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Dataset component supports 5 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| 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 |
| log (producer) | To turn on logging when the mock receives an incoming message. This will log only one time at INFO level for the incoming message. For more detailed logging then set the logger to DEBUG level for the org.apache.camel.component.mock.MockEndpoint class. | 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 |
| exchangeFormatter (advanced) | Autowired Sets a custom ExchangeFormatter to convert the Exchange to a String suitable for logging. If not specified, we default to DefaultExchangeFormatter. | ExchangeFormatter |
32.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Dataset endpoint is configured using URI syntax:
dataset:name
dataset:name
with the following path and query parameters:
32.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| name (common) | Required Name of DataSet to lookup in the registry. | DataSet |
32.5.2. Query Parameters (21 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| dataSetIndex (common) | Controls the behaviour of the CamelDataSetIndex header. For Consumers: - off = the header will not be set - strict/lenient = the header will be set For Producers: - off = the header value will not be verified, and will not be set if it is not present = strict = the header value must be present and will be verified = lenient = the header value will be verified if it is present, and will be set if it is not present. Enum values:
| lenient | String |
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| initialDelay (consumer) | Time period in millis to wait before starting sending messages. | 1000 | long |
| minRate (consumer) | Wait until the DataSet contains at least this number of messages. | 0 | int |
| preloadSize (consumer) | Sets how many messages should be preloaded (sent) before the route completes its initialization. | 0 | long |
| produceDelay (consumer) | Allows a delay to be specified which causes a delay when a message is sent by the consumer (to simulate slow processing). | 3 | long |
| 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:
| ExchangePattern | |
| assertPeriod (producer) | Sets a grace period after which the mock endpoint will re-assert to ensure the preliminary assertion is still valid. This is used for example to assert that exactly a number of messages arrives. For example if expectedMessageCount(int) was set to 5, then the assertion is satisfied when 5 or more message arrives. To ensure that exactly 5 messages arrives, then you would need to wait a little period to ensure no further message arrives. This is what you can use this method for. By default this period is disabled. | long | |
| consumeDelay (producer) | Allows a delay to be specified which causes a delay when a message is consumed by the producer (to simulate slow processing). | 0 | long |
| expectedCount (producer) | Specifies the expected number of message exchanges that should be received by this endpoint. Beware: If you want to expect that 0 messages, then take extra care, as 0 matches when the tests starts, so you need to set a assert period time to let the test run for a while to make sure there are still no messages arrived; for that use setAssertPeriod(long). An alternative is to use NotifyBuilder, and use the notifier to know when Camel is done routing some messages, before you call the assertIsSatisfied() method on the mocks. This allows you to not use a fixed assert period, to speedup testing times. If you want to assert that exactly n’th message arrives to this mock endpoint, then see also the setAssertPeriod(long) method for further details. | -1 | int |
| failFast (producer) | Sets whether assertIsSatisfied() should fail fast at the first detected failed expectation while it may otherwise wait for all expected messages to arrive before performing expectations verifications. Is by default true. Set to false to use behavior as in Camel 2.x. | 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 |
| log (producer) | To turn on logging when the mock receives an incoming message. This will log only one time at INFO level for the incoming message. For more detailed logging then set the logger to DEBUG level for the org.apache.camel.component.mock.MockEndpoint class. | false | boolean |
| reportGroup (producer) | A number that is used to turn on throughput logging based on groups of the size. | int | |
| resultMinimumWaitTime (producer) | Sets the minimum expected amount of time (in millis) the assertIsSatisfied() will wait on a latch until it is satisfied. | long | |
| resultWaitTime (producer) | Sets the maximum amount of time (in millis) the assertIsSatisfied() will wait on a latch until it is satisfied. | long | |
| retainFirst (producer) | Specifies to only retain the first n’th number of received Exchanges. This is used when testing with big data, to reduce memory consumption by not storing copies of every Exchange this mock endpoint receives. Important: When using this limitation, then the getReceivedCounter() will still return the actual number of received Exchanges. For example if we have received 5000 Exchanges, and have configured to only retain the first 10 Exchanges, then the getReceivedCounter() will still return 5000 but there is only the first 10 Exchanges in the getExchanges() and getReceivedExchanges() methods. When using this method, then some of the other expectation methods is not supported, for example the expectedBodiesReceived(Object…) sets a expectation on the first number of bodies received. You can configure both setRetainFirst(int) and setRetainLast(int) methods, to limit both the first and last received. | -1 | int |
| retainLast (producer) | Specifies to only retain the last n’th number of received Exchanges. This is used when testing with big data, to reduce memory consumption by not storing copies of every Exchange this mock endpoint receives. Important: When using this limitation, then the getReceivedCounter() will still return the actual number of received Exchanges. For example if we have received 5000 Exchanges, and have configured to only retain the last 20 Exchanges, then the getReceivedCounter() will still return 5000 but there is only the last 20 Exchanges in the getExchanges() and getReceivedExchanges() methods. When using this method, then some of the other expectation methods is not supported, for example the expectedBodiesReceived(Object…) sets a expectation on the first number of bodies received. You can configure both setRetainFirst(int) and setRetainLast(int) methods, to limit both the first and last received. | -1 | int |
| sleepForEmptyTest (producer) | Allows a sleep to be specified to wait to check that this endpoint really is empty when expectedMessageCount(int) is called with zero. | long | |
| copyOnExchange (producer (advanced)) | Sets whether to make a deep copy of the incoming Exchange when received at this mock endpoint. Is by default true. | true | boolean |
32.6. Configuring DataSet 링크 복사링크가 클립보드에 복사되었습니다!
Camel will lookup in the Registry for a bean implementing the DataSet interface. So you can register your own DataSet as:
<bean id="myDataSet" class="com.mycompany.MyDataSet"> <property name="size" value="100"/> </bean>
<bean id="myDataSet" class="com.mycompany.MyDataSet">
<property name="size" value="100"/>
</bean>
32.7. Example 링크 복사링크가 클립보드에 복사되었습니다!
For example, to test that a set of messages are sent to a queue and then consumed from the queue without losing any messages:
// send the dataset to a queue
from("dataset:foo").to("activemq:SomeQueue");
// now lets test that the messages are consumed correctly
from("activemq:SomeQueue").to("dataset:foo");
// send the dataset to a queue
from("dataset:foo").to("activemq:SomeQueue");
// now lets test that the messages are consumed correctly
from("activemq:SomeQueue").to("dataset:foo");
The above would look in the Registry to find the foo DataSet instance which is used to create the messages.
Then you create a DataSet implementation, such as using the SimpleDataSet as described below, configuring things like how big the data set is and what the messages look like etc.
32.8. DataSetSupport (abstract class) 링크 복사링크가 클립보드에 복사되었습니다!
The DataSetSupport abstract class is a nice starting point for new DataSets, and provides some useful features to derived classes.
32.8.1. Properties on DataSetSupport 링크 복사링크가 클립보드에 복사되었습니다!
| Property | Type | Default | Description |
|---|---|---|---|
|
|
|
|
Specifies the default message body. For SimpleDataSet it is a constant payload; though if you want to create custom payloads per message, create your own derivation of |
|
|
| null | |
|
|
|
| Specifies how many messages to send/consume. |
|
|
|
|
Specifies the number of messages to be received before reporting progress. Useful for showing progress of a large load test. If < 0, then |
32.9. SimpleDataSet 링크 복사링크가 클립보드에 복사되었습니다!
The SimpleDataSet extends DataSetSupport, and adds a default body.
32.9.1. Additional Properties on SimpleDataSet 링크 복사링크가 클립보드에 복사되었습니다!
| Property | Type | Default | Description |
|---|---|---|---|
|
|
|
|
Specifies the default message body. By default, the |
32.10. ListDataSet 링크 복사링크가 클립보드에 복사되었습니다!
The List`DataSet` extends DataSetSupport, and adds a list of default bodies.
32.10.1. Additional Properties on ListDataSet 링크 복사링크가 클립보드에 복사되었습니다!
| Property | Type | Default | Description |
|---|---|---|---|
|
|
|
|
Specifies the default message body. By default, the |
|
|
| the size of the defaultBodies list |
Specifies how many messages to send/consume. This value can be different from the size of the |
32.11. FileDataSet 링크 복사링크가 클립보드에 복사되었습니다!
The FileDataSet extends ListDataSet, and adds support for loading the bodies from a file.
32.11.1. Additional Properties on FileDataSet 링크 복사링크가 클립보드에 복사되었습니다!
| Property | Type | Default | Description |
|---|---|---|---|
|
|
| null | Specifies the source file for payloads |
|
|
| \z |
Specifies the delimiter pattern used by a |
32.12. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 11 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.dataset-test.autowired-enabled | 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 |
| camel.component.dataset-test.enabled | Whether to enable auto configuration of the dataset-test component. This is enabled by default. | Boolean | |
| camel.component.dataset-test.exchange-formatter | Sets a custom ExchangeFormatter to convert the Exchange to a String suitable for logging. If not specified, we default to DefaultExchangeFormatter. The option is a org.apache.camel.spi.ExchangeFormatter type. | ExchangeFormatter | |
| camel.component.dataset-test.lazy-start-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 |
| camel.component.dataset-test.log | To turn on logging when the mock receives an incoming message. This will log only one time at INFO level for the incoming message. For more detailed logging then set the logger to DEBUG level for the org.apache.camel.component.mock.MockEndpoint class. | false | Boolean |
| camel.component.dataset.autowired-enabled | 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 |
| camel.component.dataset.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.dataset.enabled | Whether to enable auto configuration of the dataset component. This is enabled by default. | Boolean | |
| camel.component.dataset.exchange-formatter | Sets a custom ExchangeFormatter to convert the Exchange to a String suitable for logging. If not specified, we default to DefaultExchangeFormatter. The option is a org.apache.camel.spi.ExchangeFormatter type. | ExchangeFormatter | |
| camel.component.dataset.lazy-start-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 |
| camel.component.dataset.log | To turn on logging when the mock receives an incoming message. This will log only one time at INFO level for the incoming message. For more detailed logging then set the logger to DEBUG level for the org.apache.camel.component.mock.MockEndpoint class. | false | Boolean |
Chapter 33. Direct 링크 복사링크가 클립보드에 복사되었습니다!
Both producer and consumer are supported
The Direct component provides direct, synchronous invocation of any consumers when a producer sends a message exchange.
This endpoint can be used to connect existing routes in the same camel context.
Asynchronous
The SEDA component provides asynchronous invocation of any consumers when a producer sends a message exchange.
33.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using direct with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-direct-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-direct-starter</artifactId>
</dependency>
33.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
direct:someName[?options]
direct:someName[?options]
Where someName can be any string to uniquely identify the endpoint
33.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
33.3.1. 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.
33.3.2. 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.
33.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Direct component supports 5 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| block (producer) | If sending a message to a direct endpoint which has no active consumer, then we can tell the producer to block and wait for the consumer to become active. | true | 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 |
| timeout (producer) | The timeout value to use if block is enabled. | 30000 | long |
| 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 |
33.5. Endpoint Options 링크 복사링크가 클립보드에 복사되었습니다!
The Direct endpoint is configured using URI syntax:
direct:name
direct:name
with the following path and query parameters:
33.5.1. Path Parameters (1 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| name (common) | Required Name of direct endpoint. | String |
33.5.2. Query Parameters (8 parameters) 링크 복사링크가 클립보드에 복사되었습니다!
| Name | Description | Default | Type |
|---|---|---|---|
| bridgeErrorHandler (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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:
| ExchangePattern | |
| block (producer) | If sending a message to a direct endpoint which has no active consumer, then we can tell the producer to block and wait for the consumer to become active. | true | boolean |
| failIfNoConsumers (producer) | Whether the producer should fail by throwing an exception, when sending to a DIRECT endpoint with no active consumers. | true | 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 |
| timeout (producer) | The timeout value to use if block is enabled. | 30000 | long |
| synchronous (advanced) | Whether synchronous processing is forced. If enabled then the producer thread, will be forced to wait until the message has been completed before the same thread will continue processing. If disabled (default) then the producer thread may be freed and can do other work while the message is continued processed by other threads (reactive). | false | boolean |
33.6. Samples 링크 복사링크가 클립보드에 복사되었습니다!
In the route below we use the direct component to link the two routes together:
And the sample using spring DSL:
See also samples from the SEDA component, how they can be used together.
33.7. Spring Boot Auto-Configuration 링크 복사링크가 클립보드에 복사되었습니다!
The component supports 6 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| camel.component.direct.autowired-enabled | 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 |
| camel.component.direct.block | If sending a message to a direct endpoint which has no active consumer, then we can tell the producer to block and wait for the consumer to become active. | true | Boolean |
| camel.component.direct.bridge-error-handler | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. 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 |
| camel.component.direct.enabled | Whether to enable auto configuration of the direct component. This is enabled by default. | Boolean | |
| camel.component.direct.lazy-start-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 |
| camel.component.direct.timeout | The timeout value to use if block is enabled. | 30000 | Long |
Chapter 34. Elasticsearch 링크 복사링크가 클립보드에 복사되었습니다!
Since Camel 3.18.3
Only producer is supported
The ElasticSearch component allows you to interface with an ElasticSearch 8.x API using the Java API Client library.
34.1. Dependencies 링크 복사링크가 클립보드에 복사되었습니다!
When using elasticsearch with Red Hat build of Camel Spring Boot make sure to use the following Maven dependency to have support for auto configuration:
<dependency> <groupId>org.apache.camel.springboot</groupId> <artifactId>camel-elasticsearch-starter</artifactId> </dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-elasticsearch-starter</artifactId>
</dependency>
34.2. URI format 링크 복사링크가 클립보드에 복사되었습니다!
elasticsearch://clusterName[?options]
elasticsearch://clusterName[?options]
34.3. Configuring Options 링크 복사링크가 클립보드에 복사되었습니다!
Camel components are configured on two separate levels:
- component level
- endpoint level
34.3.1. 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.
34.3.2. 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.
34.4. Component Options 링크 복사링크가 클립보드에 복사되었습니다!
The Elasticsearch component supports 14 options, which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
| connectionTimeout (producer) | The time in ms to wait before connection will timeout. |
|