Apache Camel JDBC and SQL components: queries, polling and transactions
Camel talks to relational databases through two components: jdbc, which runs the SQL in the message body, and sql, which runs a fixed statement with parameters from the message. This page explains how each one works, then runs every important case against a real database, from SQL injection and batch inserts to polling, transactions and duplicate detection.
Contents
Two components for SQL: jdbc and sql The jdbc component: the body is the SQL Parameters, and the SQL injection trap Batch inserts and other sql producer options Polling a table with the sql consumer Transactions across several statements Skipping duplicates with a database idempotent repository Choosing a database approach
Two components for SQL: jdbc and sql
Camel has two main components for relational databases. Both have been part of Camel since its early releases, and they work in different ways:
- jdbc (
): the message body is the SQL statement. The endpointcamel-jdbc names only thejdbc:shopDb , looked up in the registry. The component takes a connection, runs whatever SQL the body holds with plain JDBC, and puts the result in the body. It is a producer only.DataSource - sql (
): the SQL statement is in the endpoint URI, and parameters come from the message, by position (camel-sql ) or by name (# ). It runs on Spring's:#name , so it joins Spring transactions. It also works as a consumer that polls a table, and it can run batch inserts.JdbcTemplate
The difference decides where the SQL comes from. With jdbcsql
| Component | SQL from | Consumer | Best for |
|---|---|---|---|
jdbc | The message body | No | SQL that must be built at runtime, or statements passed through from elsewhere |
sql | The URI, or a file with classpath: | Yes, polling | Most routes: fixed statements, named parameters, batches, transactions |
sql-stored | The URI, as a procedure call template | No | Calling stored procedures with IN and OUT parameters |
jpa | Entities and JPQL | Yes, polling | Routes that already use a JPA model |
Both components return rows the same way: a ListMapJdbcDataSourcecamel-sqlcamel-springsql-storedjpa
The jdbc component: the body is the SQL
A small product table is enough to see every kind of result the jdbc
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
public class JdbcBasics {
// outputClass needs a JavaBean: a public no-argument constructor and setters
public static class Product {
private int id;
private String name;
private BigDecimal unitPrice;
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
@Override
public String toString() {
return "Product[id=" + id + ", name=" + name + ", unitPrice=" + unitPrice + "]";
}
}
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:shop;DB_CLOSE_DELAY=-1");
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("shopDb", dataSource);
context.start();
ProducerTemplate template = context.createProducerTemplate();
// with the jdbc component, the message body is the SQL statement
template.requestBody("jdbc:shopDb", "CREATE TABLE product (id INT PRIMARY KEY,"
+ " name VARCHAR(30), unit_price DECIMAL(6,2))");
Exchange insert = template.request("jdbc:shopDb", e -> e.getMessage().setBody(
"INSERT INTO product VALUES (1, 'book', 12.50), (2, 'pen', 1.20),"
+ " (3, 'lamp', 30.00)"));
System.out.println("INSERT: CamelJdbcUpdateCount = "
+ insert.getMessage().getHeader("CamelJdbcUpdateCount"));
Exchange select = template.request("jdbc:shopDb", e -> e.getMessage().setBody(
"SELECT id, name, unit_price FROM product ORDER BY id"));
List<?> rows = select.getMessage().getBody(List.class);
System.out.println("SELECT: body type " + rows.getClass().getSimpleName()
+ " of " + rows.get(0).getClass().getSimpleName()
+ ", CamelJdbcRowCount = " + select.getMessage().getHeader("CamelJdbcRowCount"));
rows.forEach(row -> System.out.println(" " + row));
System.out.println(" columns: " + select.getMessage().getHeader("CamelJdbcColumnNames"));
Map<?, ?> first = (Map<?, ?>) rows.get(0);
System.out.println(" get(\"name\") = " + first.get("name")
+ ", get(\"NAME\") = " + first.get("NAME"));
Object one = template.requestBody("jdbc:shopDb?outputType=SelectOne",
"SELECT name FROM product WHERE id = 3");
System.out.println("outputType=SelectOne, one column: " + one
+ " (" + one.getClass().getSimpleName() + ")");
List<?> products = template.requestBody(
"jdbc:shopDb?outputClass=JdbcBasics$Product",
"SELECT * FROM product WHERE unit_price > 10 ORDER BY id", List.class);
System.out.println("outputClass=JdbcBasics$Product:");
products.forEach(product -> System.out.println(" " + product));
context.close();
}
}
INSERT: CamelJdbcUpdateCount = 3
SELECT: body type ArrayList of LinkedHashMap, CamelJdbcRowCount = 3
{ID=1, NAME=book, UNIT_PRICE=12.50}
{ID=2, NAME=pen, UNIT_PRICE=1.20}
{ID=3, NAME=lamp, UNIT_PRICE=30.00}
columns: [ID, NAME, UNIT_PRICE]
get("name") = null, get("NAME") = book
outputType=SelectOne, one column: lamp (String)
outputClass=JdbcBasics$Product:
Product[id=1, name=book, unitPrice=12.50]
Product[id=3, name=lamp, unitPrice=30.00]
- The
set theINSERT header to 3, the number of rows changed. The body after an update is not useful.CamelJdbcUpdateCount - The
returned anSELECT ofArrayList , withLinkedHashMap 3 and the column names inCamelJdbcRowCount . Each map keeps the columns in query order.CamelJdbcColumnNames - The keys are
,ID andNAME , in upper case, because H2 stores unquoted names in upper case.UNIT_PRICE returnedget("name") . PostgreSQL returns lower case, so code that reads row maps by key can break when the database changes. Use column aliases, or map rows to a class.null with a single-column result returned the value itself: theoutputType=SelectOneString , not a list or a map.lamp mapped each row to aoutputClass . The defaultProduct lowers the column name and drops underscores, soBeanRowMapper matchedUNIT_PRICE . The class name is the binary name,setUnitPrice , because it is nested, and the class needs a no-argument constructor and setters: a record does not work here.JdbcBasics$Product
DDL statements such as CREATE TABLEresetAutoCommit=true
Parameters, and the SQL injection trap
A lookup by user name is the classic case for SQL injection. This program runs one query four ways, with a normal name and with the input nobody' OR '1'='1
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
public class Parameters {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:users;DB_CLOSE_DELAY=-1");
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("usersDb", dataSource);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
// unsafe: the header is pasted into the SQL text
from("direct:concatenated")
.setBody(simple("SELECT name FROM app_user"
+ " WHERE name = '${header.name}' ORDER BY name"))
.to("jdbc:usersDb");
// jdbc component: :?name placeholders filled from headers
from("direct:jdbcParams")
.setBody(constant("SELECT name FROM app_user"
+ " WHERE name = :?name ORDER BY name"))
.to("jdbc:usersDb?useHeadersAsParameters=true");
// sql component: the SQL is in the URI, :#name comes from the header
from("direct:sqlParams")
.to("sql:SELECT name FROM app_user WHERE name = :#name ORDER BY name"
+ "?dataSource=#usersDb");
// sql component: :#${...} takes any Simple expression
from("direct:sqlExpression")
.to("sql:SELECT name FROM app_user WHERE role = :#${body[role]}"
+ " ORDER BY name?dataSource=#usersDb");
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.requestBody("sql:CREATE TABLE app_user (name VARCHAR(20), role VARCHAR(10))"
+ "?dataSource=#usersDb", (Object) null);
template.requestBody("sql:INSERT INTO app_user VALUES ('alice', 'admin'),"
+ " ('bob', 'user'), ('carol', 'user')?dataSource=#usersDb", (Object) null);
String attack = "nobody' OR '1'='1";
for (String route : new String[] {"concatenated", "jdbcParams", "sqlParams"}) {
System.out.println(route + ":");
System.out.println(" name=alice -> " + template.requestBodyAndHeader(
"direct:" + route, null, "name", "alice"));
System.out.println(" name=" + attack + " -> " + template.requestBodyAndHeader(
"direct:" + route, null, "name", attack));
}
System.out.println("sqlExpression with body {role=user}: "
+ template.requestBody("direct:sqlExpression", Map.of("role", "user")));
context.close();
}
}
concatenated:
name=alice -> [{NAME=alice}]
name=nobody' OR '1'='1 -> [{NAME=alice}, {NAME=bob}, {NAME=carol}]
jdbcParams:
name=alice -> [{NAME=alice}]
name=nobody' OR '1'='1 -> []
sqlParams:
name=alice -> [{NAME=alice}]
name=nobody' OR '1'='1 -> []
sqlExpression with body {role=user}: [{NAME=bob}, {NAME=carol}]
built the SQL withconcatenated , pasting the header into the text. Forsimple() it worked. For the attack, the quote in the input ended the string, the statement becamealice , and all three users came back.WHERE name = 'nobody' OR '1'='1' used thejdbcParams component withjdbc and auseHeadersAsParameters=true placeholder. Camel sent the header as a:?name parameter, so the attack string was compared as a value, and no user has that name: the result was empty.PreparedStatement used thesqlParams component'ssql , which also becomes a:#name parameter, with the same safe result.PreparedStatement takes any Simple expression, here a value from a:#${body[role]} body, so parameters can come from the body, headers or exchange properties.Map
Named parameters are looked up in the body first, if it is a Mapsql#ListStringCamelSqlQueryallowQueryFromHeader=true
Batch inserts and other sql producer options
Inserting many rows one statement at a time costs one round trip and one statement execution per row. With batch=truesql
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
public class SqlBatch {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:metrics;DB_CLOSE_DELAY=-1");
CamelContext context = new DefaultCamelContext();
// with a single DataSource in the registry, sql: endpoints find it without a name
context.getRegistry().bind("metricsDb", dataSource);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:oneByOne")
.split(body())
.to("sql:INSERT INTO reading (sensor, celsius)"
+ " VALUES (:#sensor, :#celsius)")
.end();
from("direct:batch")
.to("sql:INSERT INTO reading (sensor, celsius)"
+ " VALUES (:#sensor, :#celsius)?batch=true");
from("direct:maxPerSensor")
.to("sql:SELECT sensor, MAX(celsius) AS top FROM reading"
+ " GROUP BY sensor ORDER BY sensor"
+ "?outputHeader=maxima")
.setBody(simple("${body} (body kept), maxima = ${header.maxima}"));
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.requestBody("sql:CREATE TABLE reading (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " sensor VARCHAR(10), celsius DOUBLE)", (Object) null);
List<Map<String, Object>> readings = new ArrayList<>();
for (int i = 0; i < 20000; i++) {
readings.add(Map.of("sensor", "s" + (i % 4), "celsius", 15.0 + i % 10));
}
long bestOneByOne = Long.MAX_VALUE;
long bestBatch = Long.MAX_VALUE;
Exchange batch = null;
for (int round = 1; round <= 3; round++) {
long start = System.nanoTime();
template.requestBody("direct:oneByOne", readings);
bestOneByOne = Math.min(bestOneByOne, System.nanoTime() - start);
start = System.nanoTime();
batch = template.request("direct:batch", e -> e.getMessage().setBody(readings));
bestBatch = Math.min(bestBatch, System.nanoTime() - start);
}
System.out.println("batch CamelSqlUpdateCount = "
+ batch.getMessage().getHeader("CamelSqlUpdateCount"));
System.out.printf("20,000 rows, best of 3: one by one %d ms, batch %d ms%n",
bestOneByOne / 1000000, bestBatch / 1000000);
System.out.println("rows in table: " + template.requestBody(
"sql:SELECT COUNT(*) FROM reading?outputType=SelectOne", (Object) null));
System.out.println(template.requestBody("direct:maxPerSensor", "original body"));
Exchange insert = template.request("sql:INSERT INTO reading (sensor, celsius)"
+ " VALUES ('s9', 99.5)", e -> e.getMessage().setHeader(
"CamelSqlRetrieveGeneratedKeys", true));
System.out.println("generated keys: "
+ insert.getMessage().getHeader("CamelSqlGeneratedKeyRows"));
context.close();
}
}
batch CamelSqlUpdateCount = 20000
20,000 rows, best of 3: one by one 1288 ms, batch 141 ms
rows in table: 120000
original body (body kept), maxima = [{SENSOR=s0, TOP=23.0}, {SENSOR=s1, TOP=24.0}, {SENSOR=s2, TOP=23.0}, {SENSOR=s3, TOP=24.0}]
generated keys: [{ID=120001}]
- With
and abatch=true ofList s as the body, one exchange inserted all 20,000 rows, andMap reported 20000.CamelSqlUpdateCount - The batch was several times faster than splitting the list and inserting each row. This is a rough comparison on a 2-core Xeon VM with an in-memory database, where each statement costs no network round trip. Across a network, the gap is usually larger. Across repeated runs, the ratio was between 5 and 10.
- The table holds 120,000 rows: three timed runs of each method, 20,000 rows per run.
put the query result in a header and left the body unchanged, which is useful when a route needs lookup data next to its original message.outputHeader=maxima- With the
header set toCamelSqlRetrieveGeneratedKeys , the insert returned the key that the database generated,true , inID=120001 .CamelSqlGeneratedKeyRows
The registry held a single DataSourcesqldataSourcedataSource=#namebatchAutoCommitDisabled=true
Polling a table with the sql consumer
Used in from()sql
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
public class SqlPolling {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:outbox;DB_CLOSE_DELAY=-1");
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("outboxDb", dataSource);
ProducerTemplate setup = context.createProducerTemplate();
context.start();
setup.requestBody("sql:CREATE TABLE outbox (id INT PRIMARY KEY, event VARCHAR(30),"
+ " status VARCHAR(10))", (Object) null);
setup.requestBody("sql:INSERT INTO outbox VALUES (1, 'order placed', 'NEW'),"
+ " (2, 'BROKEN', 'NEW'), (3, 'order shipped', 'NEW'),"
+ " (4, 'order paid', 'NEW'), (5, 'order closed', 'NEW')", (Object) null);
NotifyBuilder fiveRows = new NotifyBuilder(context).fromRoute("outbox-poller")
.whenDone(5).create();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("sql:SELECT * FROM outbox WHERE status = 'NEW' ORDER BY id"
+ "?initialDelay=0&delay=200&maxMessagesPerPoll=2"
+ "&onConsume=UPDATE outbox SET status = 'SENT' WHERE id = :#id"
+ "&onConsumeFailed=UPDATE outbox SET status = 'FAILED' WHERE id = :#id")
.routeId("outbox-poller")
.process(e -> {
Map<?, ?> row = e.getMessage().getBody(Map.class);
System.out.println("poll item " + (e.getProperty(
"CamelBatchIndex", Integer.class) + 1) + "/"
+ e.getProperty("CamelBatchSize") + ": " + row);
if (row.get("EVENT").equals("BROKEN")) {
throw new IllegalStateException("cannot publish");
}
});
}
});
System.out.println("all rows handled: " + fiveRows.matches(10, TimeUnit.SECONDS));
Thread.sleep(500); // a few more polls, which find nothing
context.getRouteController().stopRoute("outbox-poller");
List<?> rows = setup.requestBody("sql:SELECT id, status FROM outbox ORDER BY id",
(Object) null, List.class);
System.out.println("table afterwards:");
rows.forEach(row -> System.out.println(" " + row));
System.out.println("Without onConsume:");
NotifyBuilder threeTimes = new NotifyBuilder(context).fromRoute("no-mark")
.whenDone(3).create();
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("sql:SELECT id FROM outbox WHERE id = 1"
+ "?initialDelay=0&delay=200&repeatCount=3")
.routeId("no-mark")
.process(e -> System.out.println(" read " + e.getMessage().getBody()));
}
});
System.out.println(" the same row was delivered 3 times: "
+ threeTimes.matches(5, TimeUnit.SECONDS));
context.close();
}
}
poll item 1/2: {ID=1, EVENT=order placed, STATUS=NEW}
poll item 2/2: {ID=2, EVENT=BROKEN, STATUS=NEW}
poll item 1/2: {ID=3, EVENT=order shipped, STATUS=NEW}
poll item 2/2: {ID=4, EVENT=order paid, STATUS=NEW}
poll item 1/1: {ID=5, EVENT=order closed, STATUS=NEW}
all rows handled: true
table afterwards:
{ID=1, STATUS=SENT}
{ID=2, STATUS=FAILED}
{ID=3, STATUS=SENT}
{ID=4, STATUS=SENT}
{ID=5, STATUS=SENT}
Without onConsume:
read {ID=1}
read {ID=1}
read {ID=1}
the same row was delivered 3 times: true
limited each poll to two rows, so the five rows came in polls of 2, 2 and 1, numbered with themaxMessagesPerPoll=2 andCamelBatchIndex exchange properties.CamelBatchSize- After each row succeeded,
ranonConsume , withUPDATE ... SET status = 'SENT' WHERE id = :#id taken from the row itself. The next poll's:#id no longer matched it.WHERE status = 'NEW' - Row 2 threw an exception, so
marked itonConsumeFailed instead. Without that option, it would stayFAILED and be read again on every poll.NEW - The last part polls with no
at all. The same row was delivered three times, once per poll;onConsume stopped the scheduler after three polls so that the output is the same on every run.repeatCount=3
The consumer marks each row only after the route finishes, so a crash between processing and marking delivers the row again on restart. Routes that publish from a table should therefore be safe to repeat, or use the idempotent repository shown below. To read the whole result as one ListuseIterator=false
Transactions across several statements
Two statements in a route are two separate transactions unless the route says otherwise. A money transfer shows why that matters: credit Bob, then debit Alice, where a check constraint refuses a negative balance, so the debit fails when Alice cannot pay:
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.spring.spi.SpringTransactionPolicy;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
public class Transacted {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:bank;DB_CLOSE_DELAY=-1");
DataSourceTransactionManager txManager = new DataSourceTransactionManager(dataSource);
CamelContext context = new DefaultCamelContext();
context.getRegistry().bind("bankDb", dataSource);
context.getRegistry().bind("required", new SpringTransactionPolicy(txManager));
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
// CHECK (balance >= 0) makes the second statement fail when funds are short
from("direct:plain")
.to("sql:UPDATE account SET balance = balance + :#amount"
+ " WHERE name = 'bob'")
.to("sql:UPDATE account SET balance = balance - :#amount"
+ " WHERE name = 'alice'");
from("direct:transacted")
.transacted("required")
.to("sql:UPDATE account SET balance = balance + :#amount"
+ " WHERE name = 'bob'")
.to("sql:UPDATE account SET balance = balance - :#amount"
+ " WHERE name = 'alice'");
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
template.requestBody("sql:CREATE TABLE account (name VARCHAR(10) PRIMARY KEY,"
+ " balance INT CHECK (balance >= 0))", (Object) null);
for (String route : new String[] {"plain", "transacted"}) {
template.requestBody("sql:DELETE FROM account", (Object) null);
template.requestBody("sql:INSERT INTO account VALUES ('alice', 50), ('bob', 0)",
(Object) null);
System.out.println("direct:" + route + ", alice sends bob 80 but has only 50:");
try {
template.requestBodyAndHeader("direct:" + route, null, "amount", 80);
} catch (Exception e) {
Throwable root = e;
while (root.getCause() != null) {
root = root.getCause();
}
System.out.println(" failed: " + root.getClass().getSimpleName());
}
System.out.println(" balances: " + template.requestBody(
"sql:SELECT name, balance FROM account ORDER BY name", (Object) null));
}
context.close();
}
}
direct:plain, alice sends bob 80 but has only 50:
failed: JdbcSQLIntegrityConstraintViolationException
balances: [{NAME=alice, BALANCE=50}, {NAME=bob, BALANCE=80}]
direct:transacted, alice sends bob 80 but has only 50:
failed: JdbcSQLIntegrityConstraintViolationException
balances: [{NAME=alice, BALANCE=50}, {NAME=bob, BALANCE=0}]
- On
, the credit committed on its own before the debit failed. Bob now has 80 and Alice still has 50: money was created.direct:plain - On
,direct:transacted started a Spring transaction before the first statement. Bothtransacted("required") endpoints ran on the connection bound to that transaction, and the failure rolled back the credit, so the balances are unchanged at 50 and 0.sql - Both routes failed with H2's
, the root cause the program printed. Camel and Spring wrap it in their own exceptions on the way out.JdbcSQLIntegrityConstraintViolationException
transacted()TransactedPolicySpringTransactionPolicycamel-springDataSourceTransactionManagerrequiredtransacted()seda:
Skipping duplicates with a database idempotent repository
A message can arrive twice: a retry, a redelivered queue message, or a polled row read again after a crash. The Idempotent Consumer pattern remembers each message id and drops repeats. With JdbcMessageIdRepositorycamel-sql
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.processor.idempotent.jdbc.JdbcMessageIdRepository;
import org.h2.jdbcx.JdbcDataSource;
import org.slf4j.LoggerFactory;
public class IdempotentRepo {
public static void main(String[] args) throws Exception {
((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:payments;DB_CLOSE_DELAY=-1");
for (int run = 1; run <= 2; run++) {
// a new CamelContext each time stands for a restart, or a second node
CamelContext context = new DefaultCamelContext();
JdbcMessageIdRepository repo = new JdbcMessageIdRepository(dataSource, "payments");
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:payment")
.idempotentConsumer(header("paymentId"), repo)
.process(e -> System.out.println(" charged "
+ e.getMessage().getHeader("paymentId")));
}
});
context.start();
ProducerTemplate template = context.createProducerTemplate();
System.out.println("run " + run + ":");
for (String id : new String[] {"P-1", "P-2", "P-1", "P-" + (run + 2)}) {
template.sendBodyAndHeader("direct:payment", "amount=10", "paymentId", id);
}
context.close();
}
CamelContext reader = new DefaultCamelContext();
reader.getRegistry().bind("paymentsDb", dataSource);
reader.start();
System.out.println("CAMEL_MESSAGEPROCESSED: " + reader.createProducerTemplate()
.requestBody("sql:SELECT processorName, messageId FROM CAMEL_MESSAGEPROCESSED"
+ " ORDER BY messageId", (Object) null));
reader.close();
}
}
run 1:
charged P-1
charged P-2
charged P-3
run 2:
charged P-4
CAMEL_MESSAGEPROCESSED: [{PROCESSORNAME=payments, MESSAGEID=P-1}, {PROCESSORNAME=payments, MESSAGEID=P-2}, {PROCESSORNAME=payments, MESSAGEID=P-3}, {PROCESSORNAME=payments, MESSAGEID=P-4}]
- In run 1,
arrived twice and was charged once.P-1 andP-2 were new.P-3 - Run 2 used a new
and a new repository object, but the same table.CamelContext andP-1 were already recorded, so onlyP-2 was charged.P-4 - The repository created the table
on first use, with the processor name,CAMEL_MESSAGEPROCESSED , and the message id as a composite primary key, plus apayments timestamp that the query left out.createdAt
The primary key also protects against two nodes processing the same id at the same moment: only one insert can succeed. Old entries are never removed by Camel, so delete rows by createdAt
Choosing a database approach
| Situation | What to use |
|---|---|
| A fixed query with values from the message | sql::#name |
| SQL that must be built at runtime | jdbc:useHeadersAsParameters=true |
| Values from user input | Parameters only, never simple() |
| Thousands of inserts | sql:batch=trueList |
| Reading new rows from a table | The sqlonConsumeonConsumeFailed |
| Several statements that must succeed together | transacted()sql: |
| Messages that may arrive twice | idempotentConsumerJdbcMessageIdRepository |
| Rows as typed objects | outputClass |
| Stored procedures | sql-stored: |
The traps to remember are SQL text built from message values, column names whose case depends on the database, polled rows that are never marked, and statements that commit one by one outside a transaction. For the JDBC API underneath, see DataSourcespring.datasource.*