Knative
Since Camel 3.15
Both producer and consumer are supported
The Knative component provides support for interacting with Knative.
Maven users will need to add the following dependency to their pom.xml for this component.
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-knative</artifactId>
<version>x.x.x</version>
<!-- use the same version as your Camel version -->
</dependency> URI format
knative:type/name[?options] You can append query options to the URI in the following format:
?option=value&option=value&... Configuring Options
Camel components are configured on two separate levels:
-
component level
-
endpoint level
Configuring Component Options
At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.
For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.
Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.
You can configure components using:
-
the Component DSL.
-
in a configuration file (
application.properties,*.yamlfiles, etc). -
directly in the Java code.
Configuring Endpoint Options
You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.
Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.
A good practice when configuring options is to use Property Placeholders.
Property placeholders provide a few benefits:
-
They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.
-
They allow externalizing the configuration from the code.
-
They help the code to become more flexible and reusable.
The following two sections list all the options, firstly for the component followed by the endpoint.
Component Options
The Knative component supports the following options which are listed below.
| Name | Description | Default | Type |
|---|---|---|---|
CloudEvents attributes to set on the events that the producer sends, and on the consumer reply with replyWithCloudEvent, with the ce.override. prefix. The name is the HTTP header of the attribute, such as ce-type or ce-source (a camelCase name such as ceSource becomes ce-source), and the value replaces the one of the message headers or of the defaults. A value can use property placeholders. | Map | ||
The version of the CloudEvents specification. The producer, and the consumer reply with replyWithCloudEvent, send it as the ce-specversion attribute when the CamelCloudEventVersion header is not set. All the versions use the attributes of CloudEvents 1.0. Enum values:
| 1.0 | String | |
The CloudEvents type (ce-type) of the events that the producer sends, and of the consumer reply with replyWithCloudEvent, when neither the CamelCloudEventType header nor the event type of the resource in the Knative environment sets one. An endpoint of type event with a name in the URI sends that name as the type instead. | org.apache.camel.event | String | |
The configuration of the component; each endpoint starts from a copy of it. | KnativeConfiguration | ||
The factory of the transport that creates the consumers. When not set, the component uses the KnativeConsumerFactory bean named after the protocol (http) in the registry, else the one of camel-knative-http on the classpath. | KnativeConsumerFactory | ||
The Knative environment: the resources (channels, endpoints and events) that the endpoints look up by type and name, each with the URL to send to or the path to receive on. When not set, the component loads it from environmentPath, else from the CAMEL_KNATIVE_CONFIGURATION environment variable (the JSON itself, or a file: or classpath: location), else uses the single KnativeEnvironment bean in the registry. KnativeResource beans in the registry are looked up as well. | KnativeEnvironment | ||
The location of the Knative environment as a JSON file, such as classpath:knative.json or file:/etc/camel/knative.json (a classpath resource without a prefix). The JSON has a resources array; each resource has a type (channel, endpoint or event), a name, an endpointKind (source for a consumer, sink for a producer), the url to send to or the path to receive on, and optionally objectKind, objectApiVersion, objectName, cloudEventType, reply, filters, ceOverrides and metadata. Used when the environment option is not set, before the CAMEL_KNATIVE_CONFIGURATION environment variable. | String | ||
Filters of the consumer, with the filter. prefix: the consumer accepts only the HTTP requests where every named header equals the value or matches it as a Java regular expression. The name is a Camel CloudEvents header, such as CamelCloudEventSource (which checks the ce-source HTTP header), or an HTTP header name. A request that does not match goes to the next consumer on the same path. A structured-mode event (Content-Type application/cloudevents+json) has no ce-* HTTP headers, so a filter on a CloudEvents attribute does not accept it. | Map | ||
The factory of the transport that creates the producers. When not set, the component uses the KnativeProducerFactory bean named after the protocol (http) in the registry, else the one of camel-knative-http on the classpath. | KnativeProducerFactory | ||
The Knative SinkBinding that the producer sends to. Knative injects the URL of the sink into the bound workload as the K_SINK environment variable (read as the property k.sink) and the CloudEvents overrides as K_CE_OVERRIDES (property k.ce.overrides); the component adds a sink resource with that URL and with the name, type, object kind and API version of the binding to the Knative environment. The producer health check is DOWN while K_SINK is not set. Only the component configuration adds the resource: set on an endpoint, only the health check uses it. | KnativeSinkBinding | ||
Options of the transport (camel-knative-http), with the transport. prefix, set on the HTTP consumer and producer that the transport creates, for example transport.maxBodySize or transport.basePath of the consumer. Set on the component, they also configure the transport factories that the component discovers. Unknown options are ignored. | Map | ||
The name of the resource to look up in the Knative environment, for every endpoint of the component, in place of the name in the endpoint URI. For an endpoint of type event, it is also the CloudEvents type that the consumer accepts. | String | ||
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 | |
Whether to leave the stack trace out of the response when the exchange failed: the consumer answers the error status (500 unless the CamelHttpResponseCode header sets one) with an empty body. When false, the body is the stack trace as text/plain. Applies only with reply. | true | boolean | |
Whether the consumer replies with a CloudEvent: as the producer does, the reply gets the ce-* HTTP headers from the CamelCloudEvent headers (those of the received event unless the route changes them), the cloudEventsType and the ceOverride options. A Knative broker publishes such a reply as a new event, so give it another type (for example with ceOverride) or the consumer may receive its own reply again; an endpoint of type event replies with the type in its URI, the type it consumes. When false, the reply does not get the CloudEvents attributes. Needs reply. | false | boolean | |
Whether the consumer routes each request synchronously. When true, the route runs on a thread of the Vert.x worker pool, which waits until the route is complete, so the size of the worker pool limits how many requests are routed at the same time. When false, the route starts on a worker thread with the asynchronous routing engine, and the worker thread is free as soon as the route continues on another thread (such as an asynchronous producer), so the worker pool no longer limits the requests in flight. Keep it false for a route that calls an asynchronous producer using the same Vert.x as the HTTP server (such as vertx-http in Camel Quarkus): with true, such requests can occupy every worker thread while their producers need a worker thread to complete, and then no request completes. (currently only supported by camel-knative-http). | false | boolean | |
Whether the consumer sends the message headers and body back in the HTTP response. When false, it answers 204 No Content without a body (or the error status when the exchange failed). When not set, the reply setting of the resource in the Knative environment applies, which is true by default. | true | Boolean | |
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 | |
The API version of the Kubernetes object of the resource, such as eventing.knative.dev/v1 for a broker. When set, the endpoint uses only the resources of the Knative environment with this objectApiVersion (or knative.apiVersion metadata). | String | ||
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 | |
The kind of the Kubernetes object of the resource, such as Broker or InMemoryChannel. When set, the endpoint uses only the resources of the Knative environment with this objectKind (or knative.kind metadata). | String | ||
The name of the Kubernetes object of the resource, such as the name of the broker. When set, the endpoint uses only the resources of the Knative environment with this objectName (or knative.name metadata). The producer of an endpoint of type event also looks up the resource by this name, as the name in its URI is the CloudEvents type. | String | ||
Used for enabling or disabling all consumer based health checks from this component. | true | boolean | |
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 |
Endpoint Options
The Knative endpoint is configured using URI syntax:
knative:type/typeId
With the following path and query parameters:
Path Parameters
| Name | Description | Default | Type |
|---|---|---|---|
The type of the Knative resource: channel for a Knative channel, endpoint for a Knative Service or another addressable HTTP endpoint, or event for the events of a Knative Eventing broker. Enum values:
| Type | ||
The name of the resource to look up in the Knative environment; when no resource has this name, the one named default is used. For type event, it is also the CloudEvents type: the producer sends it as the ce-type attribute and the consumer accepts only the events of this type. | String |
Query Parameters
| Name | Description | Default | Type |
|---|---|---|---|
CloudEvents attributes to set on the events that the producer sends, and on the consumer reply with replyWithCloudEvent, with the ce.override. prefix. The name is the HTTP header of the attribute, such as ce-type or ce-source (a camelCase name such as ceSource becomes ce-source), and the value replaces the one of the message headers or of the defaults. A value can use property placeholders. | Map | ||
The version of the CloudEvents specification. The producer, and the consumer reply with replyWithCloudEvent, send it as the ce-specversion attribute when the CamelCloudEventVersion header is not set. All the versions use the attributes of CloudEvents 1.0. Enum values:
| 1.0 | String | |
The CloudEvents type (ce-type) of the events that the producer sends, and of the consumer reply with replyWithCloudEvent, when neither the CamelCloudEventType header nor the event type of the resource in the Knative environment sets one. An endpoint of type event with a name in the URI sends that name as the type instead. | org.apache.camel.event | String | |
The Knative environment: the resources (channels, endpoints and events) that the endpoints look up by type and name, each with the URL to send to or the path to receive on. When not set, the component loads it from environmentPath, else from the CAMEL_KNATIVE_CONFIGURATION environment variable (the JSON itself, or a file: or classpath: location), else uses the single KnativeEnvironment bean in the registry. KnativeResource beans in the registry are looked up as well. | KnativeEnvironment | ||
Filters of the consumer, with the filter. prefix: the consumer accepts only the HTTP requests where every named header equals the value or matches it as a Java regular expression. The name is a Camel CloudEvents header, such as CamelCloudEventSource (which checks the ce-source HTTP header), or an HTTP header name. A request that does not match goes to the next consumer on the same path. A structured-mode event (Content-Type application/cloudevents+json) has no ce-* HTTP headers, so a filter on a CloudEvents attribute does not accept it. | Map | ||
The Knative SinkBinding that the producer sends to. Knative injects the URL of the sink into the bound workload as the K_SINK environment variable (read as the property k.sink) and the CloudEvents overrides as K_CE_OVERRIDES (property k.ce.overrides); the component adds a sink resource with that URL and with the name, type, object kind and API version of the binding to the Knative environment. The producer health check is DOWN while K_SINK is not set. Only the component configuration adds the resource: set on an endpoint, only the health check uses it. | KnativeSinkBinding | ||
Options of the transport (camel-knative-http), with the transport. prefix, set on the HTTP consumer and producer that the transport creates, for example transport.maxBodySize or transport.basePath of the consumer. Set on the component, they also configure the transport factories that the component discovers. Unknown options are ignored. | Map | ||
Whether to leave the stack trace out of the response when the exchange failed: the consumer answers the error status (500 unless the CamelHttpResponseCode header sets one) with an empty body. When false, the body is the stack trace as text/plain. Applies only with reply. | true | boolean | |
Whether the consumer replies with a CloudEvent: as the producer does, the reply gets the ce-* HTTP headers from the CamelCloudEvent headers (those of the received event unless the route changes them), the cloudEventsType and the ceOverride options. A Knative broker publishes such a reply as a new event, so give it another type (for example with ceOverride) or the consumer may receive its own reply again; an endpoint of type event replies with the type in its URI, the type it consumes. When false, the reply does not get the CloudEvents attributes. Needs reply. | false | boolean | |
Whether the consumer routes each request synchronously. When true, the route runs on a thread of the Vert.x worker pool, which waits until the route is complete, so the size of the worker pool limits how many requests are routed at the same time. When false, the route starts on a worker thread with the asynchronous routing engine, and the worker thread is free as soon as the route continues on another thread (such as an asynchronous producer), so the worker pool no longer limits the requests in flight. Keep it false for a route that calls an asynchronous producer using the same Vert.x as the HTTP server (such as vertx-http in Camel Quarkus): with true, such requests can occupy every worker thread while their producers need a worker thread to complete, and then no request completes. (currently only supported by camel-knative-http). | false | boolean | |
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 | |
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 | ||
Sets the exchange pattern when the consumer creates an exchange. Enum values:
| ExchangePattern | ||
Whether the consumer sends the message headers and body back in the HTTP response. When false, it answers 204 No Content without a body (or the error status when the exchange failed). When not set, the reply setting of the resource in the Knative environment applies, which is true by default. | true | Boolean | |
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 | |
The API version of the Kubernetes object of the resource, such as eventing.knative.dev/v1 for a broker. When set, the endpoint uses only the resources of the Knative environment with this objectApiVersion (or knative.apiVersion metadata). | String | ||
The kind of the Kubernetes object of the resource, such as Broker or InMemoryChannel. When set, the endpoint uses only the resources of the Knative environment with this objectKind (or knative.kind metadata). | String | ||
The name of the Kubernetes object of the resource, such as the name of the broker. When set, the endpoint uses only the resources of the Knative environment with this objectName (or knative.name metadata). The producer of an endpoint of type event also looks up the resource by this name, as the name in its URI is the CloudEvents type. | String |
Message Headers
The Knative component supports the following message header(s), which is/are listed below:
| Name | Description | Default | Type |
|---|---|---|---|
| Constant: | The event ID. The producer uses the exchange ID when not set. | String | |
CamelCloudEventSource (common) Constant: | The event source. The producer uses the route ID when not set. | String | |
CamelCloudEventVersion (common) Constant: | The CloudEvents specification version. The producer uses the configured version when not set. | String | |
| Constant: | The event type. On a knative event endpoint with a type ID in the URI, the type ID takes precedence over this header. | String | |
CamelCloudEventDataContentType (common) Constant: | The content type of the event data. | String | |
CamelCloudEventSchemaURL (common) Constant: | The URI of the schema that the event data adheres to. | String | |
CamelCloudEventSubject (common) Constant: | The subject of the event in the context of the event source. | String | |
| Constant: | The time the event occurred. The producer uses the exchange creation time when not set. | String | |
| Constant: | The HTTP Content-Type of the message. The consumer reads it to tell a structured-mode event (application/cloudevents+json, whose JSON it decodes) from a binary-mode one, and sets it to the datacontenttype of a structured-mode event. The producer sets it to the content type of the Knative resource when the message has none. | String |
Message Body
The message body at each side of the Knative component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.
| Side | Body | Description |
|---|---|---|
Consumer |
| The data of the event as a byte array, empty or null for an event without data. A structured event (Content-Type application/cloudevents+json) gives its data field parsed from JSON: a Map, a List, text or a value. |
Consumer reply |
| The data of the reply, sent as bytes: text, bytes, a stream or a file; no body answers 204 No Content. A Map or a POJO fails: marshal it first. With reply=false the body is not sent.
|
Producer input |
| The data of the event: text, bytes, a stream or a file, sent as bytes. No body fails, and so does a Map or a POJO: marshal it first. |
Producer output |
| The body of the response, also for a message that expects no reply (InOnly): a byte array, null for a response without a body. |
The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.
Usage
Supported Knative resources
The component support the following Knative resources you can target or exposes using the type path parameter:
-
channel: allow producing or consuming events to or from a Knative Channel -
endpoint: allow exposing or targeting serverless workloads using Knative Services -
event: allow producing or consuming events to or from a Knative Broker
Knative Environment
As the Knative component hides the technical details of how to communicate with Knative services to the user (protocols, addresses, etc.), it needs some metadata that describes the Knative environment to set up the low-level transport details. To do so, the component needs a so called Knative Environment, which is essence is a Json document made by a number of service elements which looks like the below example:
{
"services": [
{
"type": "channel|endpoint|event", (1)
"name": "", (2)
"metadata": {
"service.url": "http://my-service.svc.cluster.local" (3)
"knative.event.type": "", (4)
"camel.endpoint.kind": "source|sink", (5)
}
}, {
...
}
]
} | 1 | the type of the Knative resource |
| 2 | the name of the resource |
| 3 | the url of the service to invoke (for producer only) |
| 4 | the Knative event type received or produced by the component |
| 5 | the type of the Camel Endpoint associated with this Knative resource (source=consumer, sink=producer) |
The metadata fields has some additional advanced fields:
| Name | Description | Example |
|---|---|---|
filter. | The prefix to define filters to be applied to the incoming message headers. |
|
knative.kind | The type of the k8s resource referenced by the endpoint. |
|
knative.apiVersion | The version of the k8s resource referenced by the endpoint |
|
knative.reply | If the consumer should construct a full reply to knative request. |
|
ce.override. | The prefix to define CloudEvents values that have to be overridden. |
|
CamelContext context = new DefaultCamelContext();
KnativeComponent component = context.getComponent("knative", KnativeComponent.class);
component.setEnvironmentPath("classpath:knative.json"); (1)
RouteBuilder.addRoutes(context, b -> {
b.from("knative:endpoint/myEndpoint") (2)
.to("log:info");
}); | 1 | set the location of the Knative Environment file |
| 2 | expose knative service |
You can also use property based component configuration to set the Knative Environment configuration file.
camel.component.knative.environmentPath=classpath:knative.json Using custom Knative transports
As today the Knative component only supports http as transport as this is the only supported protocol on Knative side. The transport implementation is pluggable though by implementing the following interface:
public interface KnativeTransport extends Service {
/**
* Create a camel {@link org.apache.camel.Producer} in place of the original endpoint for a specific protocol.
*
* @param endpoint the endpoint for which the producer should be created
* @param configuration the general transport configuration
* @param service the service definition containing information about how make reach the target service.
*/
Producer createProducer(
Endpoint endpoint,
KnativeTransportConfiguration configuration,
KnativeEnvironment.KnativeServiceDefinition service);
/**
* Create a camel {@link org.apache.camel.Producer} in place of the original endpoint for a specific protocol.
*
* @param endpoint the endpoint for which the consumer should be created.
* @param configuration the general transport configuration
* @param service the service definition containing information about how make the route reachable from knative.
*/
Consumer createConsumer(
Endpoint endpoint,
KnativeTransportConfiguration configuration,
KnativeEnvironment.KnativeServiceDefinition service, Processor processor);
} Knative eventing
With Knative eventing you have the opportunity to produce/consume events on the Knative broker.
Producing events
The Apache Camel route is able to produce events by sending requests to the Knative broker. In the Camel route you need to use the event resource for this kind of interaction with the Knative eventing broker. Configure the Knative component with following Knative Environment configuration.
{
"resources": [
{
"name": "default",
"type": "event",
"endpointKind": "sink",
"url": "http://default-broker.some-namespace.svc.cluster.local",
"objectApiVersion": "eventing.knative.dev/v1",
"objectKind": "Broker",
"objectName": "default"
}
]
} The Knative Environment configuration is set on the Knative component and specifies the Knative broker URL. You can then use the event resource type in your Camel route to send data to the Knative broker.
CamelContext context = new DefaultCamelContext();
KnativeComponent component = context.getComponent("knative", KnativeComponent.class);
component.setEnvironmentPath("classpath:knative.json"); (1)
RouteBuilder.addRoutes(context, b -> {
b.from("timer:tick")
.setBody()
.simple("Hello Knative!")
.transformDataType(new DataType("http:application-cloudevents")) (2)
.to("knative:event/default?kind=Broker&name=default"); (3)
}); | 1 | configure the Knative component to use the Knative Environment file |
| 2 | transform data to proper Http CloudEvents format |
| 3 | push event to the broker that gets resolved via the Knative Environment |
The same route in the DSLs, with the component configured through camel.component.knative.environmentPath as shown above:
-
Java
-
XML
-
YAML
from("timer:tick")
.setBody().simple("Hello Knative!")
.transformDataType("http:application-cloudevents")
.to("knative:event/default?kind=Broker&name=default"); <route>
<from uri="timer:tick"/>
<setBody>
<simple>Hello Knative!</simple>
</setBody>
<transformDataType toType="http:application-cloudevents"/>
<to uri="knative:event/default?kind=Broker&name=default"/>
</route> - route:
from:
uri: timer:tick
steps:
- setBody:
expression:
simple:
expression: Hello Knative!
- transformDataType:
toType: http:application-cloudevents
- to:
uri: knative:event/default?kind=Broker&name=default The Knative eventing broker uses CloudEvents data format by default. This is why we transform the data with the given data type before sending the request to the broker. The data type will set proper CloudEvent attributes like event type, id, source, subject and so on.
You can customize the CloudEvent attributes by setting specific message headers (e.g. CamelCloudEventID=myEventId or CamelCloudEventType=myEventType).
Also, you may set the CloudEvent attributes via property based configuration on the Knative component.
camel.component.knative.ceOverride[ce-type]=dev.knative.connector.event.timer
camel.component.knative.ceOverride[ce-source]=dev.knative.eventing.timer-source
camel.component.knative.ceOverride[ce-subject]=timer SinkBinding
As an alternative to specifying the Knative broker URL statically in the Knative Environment configuration you can leverage the concept of a SinkBinding resource that is able to inject the broker URL as an environment variable named K_SINK.
The SinkBinding is a Kubernetes resource that makes Knative eventing automatically inject the resource URL into your Camel application on startup. The real Knative broker URL will be available in the form of the environment varoable K_SINK.
You can use property binding support to resolve this environment variable in the Knative component configuration:
{
"resources": [
{
"name": "default",
"type": "event",
"endpointKind": "sink",
"url": "{{k.sink}}",
"objectApiVersion": "eventing.knative.dev/v1",
"objectKind": "Broker",
"objectName": "default"
}
]
} As you can see the Knative Environment configuration now uses the expression {{k.sink}} as a broker URL. On startup the SinkBinding will inject this environment variable.
The SinkBinding is created as a Kubernetes resource and looks like this:
apiVersion: sources.knative.dev/v1
kind: SinkBinding
metadata:
labels:
app.kubernetes.io/name: my-camel-app
name: my-camel-app-binding
spec:
sink:
ref:
apiVersion: eventing.knative.dev/v1
kind: Broker
name: default
subject:
apiVersion: apps/v1
kind: Deployment
name: my-camel-app The binding resource specifies the reference to the Knative broker and a subject which usually is the Deployment resource that represents your Camel application running on Kubernetes.
It may take some time for the SinkBinding to inject the K_SINK environment variable into the Deployment resource. The Camel application may run into errors because of the missing variable when starting the Camel context. As a result you may want to wait for the environment variable to be present before starting the Camel context. You can do this with a Camel startup condition, for instance by setting CAMEL_STARTUPCONDITION_ENVIRONMENT_VARIABLE_EXISTS=K_SINK. |
Using ProducerTemplate
When using Knative producer with a ProducerTemplate, it is necessary to specify a value for the CloudEvent source, simply by setting a value for the header 'CamelCloudEventSource'.
producerTemplate.sendBodyAndHeader("knative:event/broker-test", body, CloudEvent.CAMEL_CLOUD_EVENT_SOURCE, "my-source-name"); Consuming events
The Knative event consumption is based on starting a Http service as part of the Camel application. The Knative broker will invoke the service then with the event data. The concept uses a so called Trigger resource that connects the application with the Knative broker event stream. The trigger specifies which events should be sent to the Http service that is part of the Camel application.
As sample trigger resource looks like this:
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
labels:
app.kubernetes.io/name: my-camel-app
eventing.knative.dev/broker: default
name: my-camel-app-trigger
spec:
broker: default
subscriber:
ref:
apiVersion: v1
kind: Service
name: my-camel-app The trigger resource references a Knative broker by its name (default) and specifies the subscriber which is an arbitrary Kubernetes Service. The trigger will invoke the service subscriber for each event on the broker. The trigger may specify filters on event attributes to select the events that should be sent to the subscriber.
The Service resource is part of the Camel application running on the Kubernetes cluster and points to an exposed Http service and port. The Knative Camel component will automatically configure this Http service when consuming events in a Camel route.
Just use the event resource type in your Camel route like this:
RouteBuilder.addRoutes(context, b -> {
b.from("knative:event/default?kind=Broker&name=default")
.to("log:info");
}); The same route in the DSLs; the body is the data of the CloudEvent and its attributes are message headers such as CamelCloudEventType and CamelCloudEventSource:
-
Java
-
XML
-
YAML
from("knative:event/default?kind=Broker&name=default")
.log("Received event: ${body}"); <route>
<from uri="knative:event/default?kind=Broker&name=default"/>
<log message="Received event: ${body}"/>
</route> - route:
from:
uri: knative:event/default?kind=Broker&name=default
steps:
- log:
message: "Received event: ${body}" The according Knative Environment configuration that specifies the Http service looks like this:
{
"resources": [
{
"name": "default",
"type": "event",
"endpointKind": "source",
"path": "/",
"objectApiVersion": "eventing.knative.dev/v1",
"objectKind": "Broker",
"objectName": "default",
"reply": false
}
]
} This will create a proper Http service with the right resource path routing so that all incoming event requests will be consumed by the Camel route. Once again the Knative broker will use CloudEvent data format by default, so you can access the CloudEvent attributes such as event type, id, source, subject in the Camel route.
Bridging channels
The channel resource type works the same way with Knative channels: a route consumes the messages of one channel and produces to another, with both channels declared in the Knative Environment as channel resources, the consumed one with "endpointKind": "source" and the produced one with "endpointKind": "sink":
-
Java
-
XML
-
YAML
from("knative:channel/messages")
.transform().simple("transformed ${body}")
.to("knative:channel/words"); <route>
<from uri="knative:channel/messages"/>
<transform>
<simple>transformed ${body}</simple>
</transform>
<to uri="knative:channel/words"/>
</route> - route:
from:
uri: knative:channel/messages
steps:
- transform:
expression:
simple:
expression: transformed ${body}
- to:
uri: knative:channel/words