Camel Components

PostgreSQL Replication Slot

Since Camel 3.0

Only consumer is supported

This is a component for Apache Camel that allows consuming from PostgreSQL replication slots. The component works with PostgreSQL 10 or later.

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

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

URI format

The pg-replication-slot component uses the following two styles of endpoint URI notation:

pg-replication-slot://host:port/database/slot:plugin[?parameters]

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

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

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

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

You can configure components using:

  • the Component DSL.

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

  • directly in the Java code.

Configuring Endpoint Options

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

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

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

Property placeholders provide a few benefits:

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

  • They allow externalizing the configuration from the code.

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

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

Component Options

The PostgreSQL Replication Slot component supports the following 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

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

Endpoint Options

The PostgreSQL Replication Slot endpoint is configured using URI syntax:

pg-replication-slot:host:port/database/slot:outputPlugin

With the following path and query parameters:

Path Parameters

Name Description Default Type

slot (common)

Required The name of the logical replication slot to read the changes from. PostgreSQL accepts only lower case letters, digits and underscores in a slot name.

String

host (common)

The host name or IP address of the PostgreSQL server.

localhost

String

port (common)

The port of the PostgreSQL server.

5432

Integer

database (common)

Required The name of the database to connect to. A logical replication slot belongs to one database and decodes only the changes of that database. The endpoint accepts only letters, digits and underscores in the name.

String

outputPlugin (common)

Required The name of the logical decoding output plugin, for example test_decoding, wal2json or pgoutput, which sets the format of the messages. The consumer uses it only when it creates the slot (see autoCreateSlot): an existing slot keeps the plugin that it was created with.

String

Query Parameters

Name Description Default Type

password (common)

The password of the database user.

String

user (common)

The name of the database user. The user needs the REPLICATION attribute, or must be a superuser.

postgres

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

bridgeErrorHandler (consumer (advanced))

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

false

boolean

exceptionHandler (consumer (advanced))

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

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

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

autoCreateSlot (advanced)

Whether the consumer creates a logical replication slot with the outputPlugin when it connects and no slot of this name exists. If false, the slot must exist, otherwise each poll fails. The consumer never drops the slot, so PostgreSQL keeps the WAL that the slot has not confirmed, also while the route is stopped.

true

Boolean

slotOptions (advanced)

The options that the consumer passes to the output plugin when it starts reading from the slot, for example slotOptions.include-xids=false for test_decoding, or slotOptions.proto_version=1 and slotOptions.publication_names=mypub for pgoutput. The plugin defines which options exist. This is a multi-value option with prefix: slotOptions.

Map

statusInterval (advanced)

The number of seconds between the status updates that the consumer sends to the PostgreSQL server, which report the position that it has received and flushed. While a message is routed, the consumer also sends a status update at this interval, so that the server does not close the connection when routing takes longer than wal_sender_timeout.

10

Integer

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

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

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

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

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. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

sslCert (security)

The file of the client certificate (PEM) for a server that checks client certificates. When not set, the PostgreSQL JDBC driver reads postgresql.crt in the .postgresql folder of the home directory of the user, if it exists.

String

sslKey (security)

The file of the private key of the client certificate. The PostgreSQL JDBC driver accepts PKCS-8 in DER format, PKCS-8 in PEM format (a .pem file, or a file that starts with -----BEGIN PRIVATE KEY-----), or a PKCS-12 file (.p12 or .pfx) that holds the certificate and the key. When not set, the driver reads postgresql.pk8 in the .postgresql folder of the home directory of the user, if it exists.

String

sslMode (security)

The SSL mode of the connection to the PostgreSQL server: disable, allow, prefer, require, verify-ca or verify-full. When not set, the default of the PostgreSQL JDBC driver applies, which is prefer: TLS when the server offers it, without checking the server certificate, and a plain connection otherwise. Use verify-full to require TLS and check both the certificate and the host name of the server.

Enum values:

  • disable

  • allow

  • prefer

  • require

  • verify-ca

  • verify-full

String

sslPassword (security)

The password of the private key in sslKey.

String

sslRootCert (security)

The file of the root certificates (PEM) that the server certificate is checked against with sslMode verify-ca or verify-full. When not set, the PostgreSQL JDBC driver reads root.crt in the .postgresql folder of the home directory of the user.

String

Message Headers

The PostgreSQL Replication Slot component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelPgReplicationSlotLsn (consumer)

Constant: LSN

The log sequence number (LSN) of the message, in the text form of PostgreSQL such as 0/16B3748. Several messages can have the same LSN, for example the BEGIN and the first change of a transaction.

String

Message Body

The message body at each side of the PostgreSQL Replication Slot 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

bytes (byte[])

One message of the output plugin of the slot, as bytes: text for test_decoding, JSON for wal2json, the binary protocol for pgoutput; convert it to a String for the text plugins. The LSN of the message is in the CamelPgReplicationSlotLsn header.

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

Tips

PostgreSQL can generate a huge number of empty transactions on certain operations (e.g. VACUUM). These transactions can congest your route. Using greedy=true query parameter can help with this problem. It will help your route filter out empty transactions quickly without waiting for the delay*timeUnit parameter between each exchange.

The order of the messages is guaranteed, but the same message might come more than once. So, for example, if you’re using this component to sync data from PostgreSQL to another database, make sure your operations are idempotent (e.g., use UPSERT instead of INSERT, etc). This will make sure repeated messages won’t affect your system negatively.

The log sequence number (LSN) of a message is in the CamelPgReplicationSlotLsn header. It is not unique: several messages can have the same LSN, for example the BEGIN and the first change of a transaction with test_decoding.

TLS

The sslMode option sets how the connection uses TLS. When it is not set, the default of the PostgreSQL JDBC driver applies, which is prefer: TLS when the server offers it, without checking the server certificate, and a plain connection otherwise. To require TLS and check the server, use verify-full (certificate and host name) or verify-ca (certificate only), with the root certificates of the server in sslRootCert:

pg-replication-slot:db.example.com:5432/mydb/myslot:test_decoding?user=replicator&password=RAW(secret)&sslMode=verify-full&sslRootCert=/etc/certs/root.crt

For a server that checks client certificates, set sslCert and sslKey (and sslPassword when the key has a password). The PostgreSQL JDBC driver accepts the key as PKCS-8 in DER format, as PKCS-8 in PEM format (a .pem file, or a file that starts with -----BEGIN PRIVATE KEY-----), or as a PKCS-12 file (.p12 or .pfx) that holds the certificate and the key.

Examples

Example route
  • Java

  • XML

  • YAML

from("pg-replication-slot://localhost:5432/finance/sync_slot:test_decoding?user={{username}}&password={{password}}&slotOptions.skip-empty-xacts=true&slotOptions.include-xids=false")
    .to("mock:result");
<route>
  <from uri="pg-replication-slot://localhost:5432/finance/sync_slot:test_decoding?user={{username}}&amp;password={{password}}&amp;slotOptions.skip-empty-xacts=true&amp;slotOptions.include-xids=false"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: pg-replication-slot://localhost:5432/finance/sync_slot:test_decoding
      parameters:
        user: "{{username}}"
        password: "{{password}}"
        slotOptions.skip-empty-xacts: true
        slotOptions.include-xids: false
      steps:
        - to:
            uri: mock:result