This is an automated email from the ASF dual-hosted git repository.

davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel-jbang-examples.git


The following commit(s) were added to refs/heads/main by this push:
     new f2f40df  route/cache - the Cache EIP keeps a slow customer service's 
answer per customer (#151)
f2f40df is described below

commit f2f40dfb697790f078fc778a9fed014263656906
Author: Claus Ibsen <[email protected]>
AuthorDate: Mon Nov 30 07:03:13 2026 +0100

    route/cache - the Cache EIP keeps a slow customer service's answer per 
customer (#151)
    
    Closes #150
    
    
    Claude-Session: https://claude.ai/code/session_016Y4dDi5iQNgtHrDdz2NpwF
    
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 .github/workflows/build.yml                        |   2 +
 README.md                                          |   1 +
 camel-jbang-example-catalog.json                   |  60 +++++++++
 route/README.md                                    |   1 +
 route/cache/README.md                              |  92 +++++++++++++
 route/cache/application.properties                 |  21 +++
 route/cache/cache.camel.yaml                       | 148 +++++++++++++++++++++
 route/cache/customers/C-207.json                   |   1 +
 route/cache/customers/C-482.json                   |   1 +
 route/cache/incoming/1-order-1001.json             |   1 +
 route/cache/incoming/2-order-1002.json             |   1 +
 route/cache/incoming/3-order-1004.json             |   1 +
 route/cache/incoming/4-order-1005.json             |   1 +
 route/cache/incoming/5-customer-C-482-changed.json |   1 +
 route/cache/incoming/6-order-1006.json             |   1 +
 route/cache/incoming/7-order-1007.json             |   1 +
 route/cache/metadata.json                          |  43 ++++++
 route/cache/test/cache.citrus.it.yaml              |  51 +++++++
 18 files changed, 428 insertions(+)

diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 61f0563..dfbba05 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -91,6 +91,8 @@ jobs:
             path: route/batch-file
           - name: Scatter-gather
             path: route/scatter-gather
+          - name: Cache
+            path: route/cache
           - name: Error handling
             path: fail-well/error-handling
           - name: Circuit breaker
diff --git a/README.md b/README.md
index e79c77e..46c1eb0 100644
--- a/README.md
+++ b/README.md
@@ -79,6 +79,7 @@ The routing patterns: content-based router, splitter, 
aggregator, filter and mul
 | [Dynamic routing](route/dynamic-routing/) | Each of the three orders goes to 
the warehouse of its country and to the billing of its status through a 
recipient list computed from the order; billing a paid order fails over from a 
primary invoice service that is down to a backup one, the pending order gets no 
invoice, and the US warehouse is throttled to one order per second. | nothing |
 | [Batch file](route/batch-file/) | Two settlement files of the payment 
provider, 5000 payments each, are read line by line with a streaming split; 
each payment of 500 EUR or more is logged, the two lines whose amount is not a 
number go to rejects/ while the rest of the file goes on, and a summary line is 
logged when a file is done. | nothing |
 | [Scatter-gather](route/scatter-gather/) | Two restock requests are sent to 
three suppliers at the same time with a multicast that waits at most two 
seconds; the slow supplier is left out, a supplier that answers 404 is logged 
and skipped, and Groovy picks the lowest price, with the shorter delivery time 
on the same price. | nothing |
+| [Cache](route/cache/) | Six orders and a customer-changed notice are read in 
order; the Cache EIP keeps each customer from a slow customer service for ten 
seconds, so a second order of the same customer is served from the cache, the 
notice removes a customer from the cache with a bean call, and a customer the 
service does not know (404) is caught and never cached. | nothing |
 
 ### [Fail well](fail-well/)
 
diff --git a/camel-jbang-example-catalog.json b/camel-jbang-example-catalog.json
index 1610eab..b2bfcc9 100644
--- a/camel-jbang-example-catalog.json
+++ b/camel-jbang-example-catalog.json
@@ -1381,6 +1381,66 @@
         ],
         "order": 7
     },
+    {
+        "name": "route/cache",
+        "title": "Cache",
+        "description": "Six orders and a customer-changed notice are read in 
order; the Cache EIP keeps each customer from a slow customer service for ten 
seconds, so a second order of the same customer is served from the cache, the 
notice removes a customer from the cache with a bean call, and a customer the 
service does not know (404) is caught and never cached.",
+        "level": "route",
+        "teaches": {
+            "components": [
+                "file",
+                "direct",
+                "http",
+                "platform-http",
+                "bean",
+                "log"
+            ],
+            "eips": [
+                "cache",
+                "doTry",
+                "choice",
+                "delay",
+                "pollEnrich",
+                "setVariable",
+                "setHeader",
+                "setBody",
+                "toD",
+                "convertBodyTo",
+                "unmarshal"
+            ],
+            "languages": [
+                "simple"
+            ],
+            "dataformats": [
+                "json"
+            ]
+        },
+        "tags": [
+            "shop",
+            "eip",
+            "cache",
+            "ttl",
+            "invalidation"
+        ],
+        "bundled": true,
+        "requiresDocker": false,
+        "hasCitrusTests": true,
+        "files": [
+            "README.md",
+            "application.properties",
+            "cache.camel.yaml",
+            "customers/C-207.json",
+            "customers/C-482.json",
+            "incoming/1-order-1001.json",
+            "incoming/2-order-1002.json",
+            "incoming/3-order-1004.json",
+            "incoming/4-order-1005.json",
+            "incoming/5-customer-C-482-changed.json",
+            "incoming/6-order-1006.json",
+            "incoming/7-order-1007.json"
+        ],
+        "order": 9
+    },
     {
         "name": "route/content-based-router",
         "title": "Content-based router",
diff --git a/route/README.md b/route/README.md
index a60a931..18d7eae 100644
--- a/route/README.md
+++ b/route/README.md
@@ -13,6 +13,7 @@ The routing patterns: content-based router, splitter, 
aggregator, filter and mul
 | [Dynamic routing](dynamic-routing/) | Each of the three orders goes to the 
warehouse of its country and to the billing of its status through a recipient 
list computed from the order; billing a paid order fails over from a primary 
invoice service that is down to a backup one, the pending order gets no 
invoice, and the US warehouse is throttled to one order per second. | nothing |
 | [Batch file](batch-file/) | Two settlement files of the payment provider, 
5000 payments each, are read line by line with a streaming split; each payment 
of 500 EUR or more is logged, the two lines whose amount is not a number go to 
rejects/ while the rest of the file goes on, and a summary line is logged when 
a file is done. | nothing |
 | [Scatter-gather](scatter-gather/) | Two restock requests are sent to three 
suppliers at the same time with a multicast that waits at most two seconds; the 
slow supplier is left out, a supplier that answers 404 is logged and skipped, 
and Groovy picks the lowest price, with the shorter delivery time on the same 
price. | nothing |
+| [Cache](cache/) | Six orders and a customer-changed notice are read in 
order; the Cache EIP keeps each customer from a slow customer service for ten 
seconds, so a second order of the same customer is served from the cache, the 
notice removes a customer from the cache with a bean call, and a customer the 
service does not know (404) is caught and never cached. | nothing |
 
 Start with [Content-based router](content-based-router/); the examples read 
best in the order above, each one building on what the one before it set up.
 
diff --git a/route/cache/README.md b/route/cache/README.md
new file mode 100644
index 0000000..1d5501f
--- /dev/null
+++ b/route/cache/README.md
@@ -0,0 +1,92 @@
+# Cache
+
+Each order needs its customer, and the customer service is slow. The Cache EIP 
keeps the answer per customer for a
+while, so the shop calls the service once for many orders of the same 
customer. A customer that changes is removed
+from the cache, and a failed lookup is never cached.
+
+## What you will see
+
+```text
+INFO ... cache.camel.yaml:77 : Calling the customer service for C-482
+INFO ... cache.camel.yaml:87 : Order ORD-1001 for Anna Jensen (gold), customer 
from the service
+INFO ... cache.camel.yaml:77 : Calling the customer service for C-207
+INFO ... cache.camel.yaml:87 : Order ORD-1002 for Jonas Weber (silver), 
customer from the service
+INFO ... cache.camel.yaml:87 : Order ORD-1004 for Anna Jensen (gold), customer 
from the cache
+INFO ... cache.camel.yaml:87 : Order ORD-1005 for Jonas Weber (silver), 
customer from the cache
+INFO ... cache.camel.yaml:112 : Customer C-482 changed, removed from the cache
+INFO ... cache.camel.yaml:77 : Calling the customer service for C-482
+INFO ... cache.camel.yaml:87 : Order ORD-1006 for Anna Jensen (gold), customer 
from the service
+INFO ... cache.camel.yaml:77 : Calling the customer service for C-999
+INFO ... cache.camel.yaml:93 : Order ORD-1007: customer C-999 not found (HTTP 
404)
+```
+
+## Install Camel CLI
+
+Install [JBang](https://www.jbang.dev/download/) and the Camel CLI as 
described in the
+[root README](../../README.md#install-the-camel-cli); `camel --version` 
confirms the install. The Cache EIP is new
+in Camel 4.23.
+
+## Run it
+
+```shell
+camel run *
+```
+
+This runs the shop's routes and the customer service in one app, on port 8080. 
Stop the example with `ctrl` + `c`.
+
+## How it works
+
+- `incoming/` holds six orders and, after the fourth, a notice from the back 
office that customer C-482 changed. The
+  files are read one a second in name order. `customers/` holds the data of 
the customer service. C-999 has no file.
+- The `customer-service` route plays the slow customer service: `GET 
/customers/{id}` takes a second and answers with
+  the customer's file, or 404.
+- The `order` route wraps the call in a `cache` block, with the customer id as 
the key and a time to live of ten
+  seconds (`customer.cache.ttl`). On a miss, the steps inside run and their 
result is stored. On a hit, the cached
+  customer becomes the body, and the steps inside are skipped. The variable 
`source` shows which one it was.
+- `convertBodyTo: String` at the end of the block stores the customer as text, 
not as the stream that the HTTP call
+  returns.
+- The cache's store is a named bean, `customerCache`, a 
`MemoryKeyValueRepository`. The `customer-changed` route calls
+  its `delete` method with the customer id, so the next order of C-482 gets 
fresh data.
+- The call for C-999 fails with 404 inside the cache block, so nothing is 
stored for it. The `doTry` around the block
+  catches the failure and logs it, and the shop goes on with the next order.
+
+## Build it step by step
+
+Ask your assistant, or type it yourself, one step at a time, and run after 
each:
+
+1. A `platform-http` route for `GET /customers/{id}` that answers with 
`customers/<id>.json` after a second, and a
+   file route on `incoming` that calls it for each order and logs the order 
with the customer's name and tier.
+2. The customer service is slow. Keep its answer per customer id for ten 
seconds, so it is called only once for many
+   orders of the same customer. Log whether the customer came from the service 
or from the cache.
+3. A file with `customerChanged` instead of an order says that a customer 
changed. Remove that customer from the
+   cache, so the next order gets fresh data.
+4. The service answers 404 for a customer it does not know. Log "customer ... 
not found" and go on with the next order.
+
+## Try changing
+
+- Set `customer.cache.ttl=1s`: the cached customers expire before the next 
order, and every order calls the service.
+- Remove `keyValueRepository: customerCache`: the cache still uses the bean, 
because it is the only
+  `KeyValueRepository` in the registry. With two such beans, name the one each 
`cache` block uses.
+- Move the `doTry` inside the `cache` block: the failure for C-999 is then 
caught inside, the block succeeds, and its
+  result is cached.
+
+## Integration testing
+
+The example comes with a test in the [Citrus](https://citrusframework.org/) 
YAML DSL, `test/cache.citrus.it.yaml`,
+which the Camel CLI runs:
+
+```shell
+camel test run test/cache.citrus.it.yaml
+```
+
+The test runs the routes and verifies the hits, the removed customer and the 
unknown customer.
+
+## Help and contributions
+
+If you hit any problem using Camel or have some feedback, then please
+[let us know](https://camel.apache.org/community/support/).
+
+We also love contributors, so
+[get involved](https://camel.apache.org/community/contributing/) :-)
+
+The Camel riders!
diff --git a/route/cache/application.properties 
b/route/cache/application.properties
new file mode 100644
index 0000000..76fdbfd
--- /dev/null
+++ b/route/cache/application.properties
@@ -0,0 +1,21 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# the customer service; in this example it is a route of the same app
+shop.customers.url=http://localhost:8080/customers
+# how long a customer is kept in the cache
+customer.cache.ttl=10s
diff --git a/route/cache/cache.camel.yaml b/route/cache/cache.camel.yaml
new file mode 100644
index 0000000..9cb9166
--- /dev/null
+++ b/route/cache/cache.camel.yaml
@@ -0,0 +1,148 @@
+# Each order needs its customer, and the customer service is slow. The Cache 
EIP keeps the answer per customer for a
+# while, so the shop calls the service once for many orders of the same 
customer.
+- beans:
+    # the store of the cache; a named store, so the customer-changed route can 
remove an entry from it
+    - name: customerCache
+      type: org.apache.camel.support.MemoryKeyValueRepository
+
+# incoming/ holds the orders and, in between, a notice from the back office 
that a customer changed
+- route:
+    id: incoming
+    from:
+      uri: file
+      parameters:
+        directoryName: incoming
+        noop: true
+        sortBy: "file:name"
+        # one file a second, in name order, so the log reads in order
+        maxMessagesPerPoll: 1
+        eagerMaxMessagesPerPoll: false
+        delay: 1000
+      steps:
+        - unmarshal:
+            json:
+              library: Jackson
+        - choice:
+            when:
+              - expression:
+                  simple:
+                    expression: "${body[customerChanged]} != null"
+                steps:
+                  - to:
+                      uri: direct:customer-changed
+            otherwise:
+              steps:
+                - to:
+                    uri: direct:order
+
+- route:
+    id: order
+    from:
+      uri: direct
+      parameters:
+        name: order
+      steps:
+        - setVariable:
+            name: orderId
+            expression:
+              simple:
+                expression: "${body[orderId]}"
+        - setVariable:
+            name: customerId
+            expression:
+              simple:
+                expression: "${body[customer]}"
+        # the steps inside the cache block run only on a miss, so this says 
where the customer came from
+        - setVariable:
+            name: source
+            expression:
+              constant:
+                expression: the cache
+        - doTry:
+            steps:
+              # on a hit, the cached customer becomes the body and the steps 
inside are skipped; on a miss, the steps
+              # run and their result is stored; a failed lookup is never stored
+              - cache:
+                  expression:
+                    simple:
+                      expression: "${variable.customerId}"
+                  keyValueRepository: customerCache
+                  ttl: "{{customer.cache.ttl}}"
+                  steps:
+                    - setVariable:
+                        name: source
+                        expression:
+                          constant:
+                            expression: the service
+                    - log:
+                        message: "Calling the customer service for 
${variable.customerId}"
+                    - toD:
+                        uri: 
"{{shop.customers.url}}/${variable.customerId}?httpMethod=GET"
+                    # store the customer as text, not as the stream the HTTP 
call returns
+                    - convertBodyTo:
+                        type: String
+              - unmarshal:
+                  json:
+                    library: Jackson
+              - log:
+                  message: "Order ${variable.orderId} for ${body[name]} 
(${body[tier]}), customer from ${variable.source}"
+            doCatch:
+              - exception:
+                  - org.apache.camel.http.base.HttpOperationFailedException
+                steps:
+                  - log:
+                      message: "Order ${variable.orderId}: customer 
${variable.customerId} not found (HTTP ${exception.statusCode})"
+
+# A customer changed: remove it from the cache, so the next order gets fresh 
data from the service
+- route:
+    id: customer-changed
+    from:
+      uri: direct
+      parameters:
+        name: customer-changed
+      steps:
+        - setVariable:
+            name: customerId
+            expression:
+              simple:
+                expression: "${body[customerChanged]}"
+        - bean:
+            ref: customerCache
+            method: "delete(${variable.customerId})"
+        - log:
+            message: "Customer ${variable.customerId} changed, removed from 
the cache"
+
+# The slow customer service, as a route of the same app: it reads 
customers/<id>.json and answers 404 when there is
+# no such customer
+- route:
+    id: customer-service
+    from:
+      uri: platform-http
+      parameters:
+        path: "/customers/{id}"
+        httpMethodRestrict: GET
+      steps:
+        - delay:
+            expression:
+              constant:
+                expression: "1000"
+        - pollEnrich:
+            expression:
+              simple:
+                expression: 
"file:customers?fileName=${header.id}.json&noop=true&idempotent=false"
+            timeout: 0
+        - choice:
+            when:
+              - expression:
+                  simple:
+                    expression: "${body} == null"
+                steps:
+                  - setHeader:
+                      name: CamelHttpResponseCode
+                      expression:
+                        constant:
+                          expression: "404"
+                  - setBody:
+                      expression:
+                        simple:
+                          expression: '{"error": "no customer ${header.id}"}'
diff --git a/route/cache/customers/C-207.json b/route/cache/customers/C-207.json
new file mode 100644
index 0000000..db5d259
--- /dev/null
+++ b/route/cache/customers/C-207.json
@@ -0,0 +1 @@
+{"id": "C-207", "name": "Jonas Weber", "tier": "silver"}
diff --git a/route/cache/customers/C-482.json b/route/cache/customers/C-482.json
new file mode 100644
index 0000000..0d6881c
--- /dev/null
+++ b/route/cache/customers/C-482.json
@@ -0,0 +1 @@
+{"id": "C-482", "name": "Anna Jensen", "tier": "gold"}
diff --git a/route/cache/incoming/1-order-1001.json 
b/route/cache/incoming/1-order-1001.json
new file mode 100644
index 0000000..35a4312
--- /dev/null
+++ b/route/cache/incoming/1-order-1001.json
@@ -0,0 +1 @@
+{"orderId": "ORD-1001", "customer": "C-482", "country": "DK", "status": 
"paid", "lines": [{"sku": "CAMEL-TSHIRT", "qty": 2, "price": 19.95}, {"sku": 
"CAMEL-MUG", "qty": 1, "price": 9.50}]}
diff --git a/route/cache/incoming/2-order-1002.json 
b/route/cache/incoming/2-order-1002.json
new file mode 100644
index 0000000..c6c010d
--- /dev/null
+++ b/route/cache/incoming/2-order-1002.json
@@ -0,0 +1 @@
+{"orderId": "ORD-1002", "customer": "C-207", "country": "DE", "status": 
"paid", "lines": [{"sku": "CAMEL-MUG", "qty": 3, "price": 9.50}]}
diff --git a/route/cache/incoming/3-order-1004.json 
b/route/cache/incoming/3-order-1004.json
new file mode 100644
index 0000000..c4c6481
--- /dev/null
+++ b/route/cache/incoming/3-order-1004.json
@@ -0,0 +1 @@
+{"orderId": "ORD-1004", "customer": "C-482", "country": "DK", "status": 
"paid", "lines": [{"sku": "CAMEL-CAP", "qty": 1, "price": 14.00}]}
diff --git a/route/cache/incoming/4-order-1005.json 
b/route/cache/incoming/4-order-1005.json
new file mode 100644
index 0000000..7e009c2
--- /dev/null
+++ b/route/cache/incoming/4-order-1005.json
@@ -0,0 +1 @@
+{"orderId": "ORD-1005", "customer": "C-207", "country": "DE", "status": 
"paid", "lines": [{"sku": "CAMEL-TSHIRT", "qty": 1, "price": 19.95}]}
diff --git a/route/cache/incoming/5-customer-C-482-changed.json 
b/route/cache/incoming/5-customer-C-482-changed.json
new file mode 100644
index 0000000..b545f39
--- /dev/null
+++ b/route/cache/incoming/5-customer-C-482-changed.json
@@ -0,0 +1 @@
+{"customerChanged": "C-482", "change": "new delivery address"}
diff --git a/route/cache/incoming/6-order-1006.json 
b/route/cache/incoming/6-order-1006.json
new file mode 100644
index 0000000..90cef08
--- /dev/null
+++ b/route/cache/incoming/6-order-1006.json
@@ -0,0 +1 @@
+{"orderId": "ORD-1006", "customer": "C-482", "country": "DK", "status": 
"paid", "lines": [{"sku": "CAMEL-MUG", "qty": 2, "price": 9.50}]}
diff --git a/route/cache/incoming/7-order-1007.json 
b/route/cache/incoming/7-order-1007.json
new file mode 100644
index 0000000..edcf105
--- /dev/null
+++ b/route/cache/incoming/7-order-1007.json
@@ -0,0 +1 @@
+{"orderId": "ORD-1007", "customer": "C-999", "country": "SE", "status": 
"paid", "lines": [{"sku": "CAMEL-CAP", "qty": 1, "price": 14.00}]}
diff --git a/route/cache/metadata.json b/route/cache/metadata.json
new file mode 100644
index 0000000..a8166aa
--- /dev/null
+++ b/route/cache/metadata.json
@@ -0,0 +1,43 @@
+{
+    "title": "Cache",
+    "description": "Six orders and a customer-changed notice are read in 
order; the Cache EIP keeps each customer from a slow customer service for ten 
seconds, so a second order of the same customer is served from the cache, the 
notice removes a customer from the cache with a bean call, and a customer the 
service does not know (404) is caught and never cached.",
+    "level": "route",
+    "order": 9,
+    "teaches": {
+        "components": [
+            "file",
+            "direct",
+            "http",
+            "platform-http",
+            "bean",
+            "log"
+        ],
+        "eips": [
+            "cache",
+            "doTry",
+            "choice",
+            "delay",
+            "pollEnrich",
+            "setVariable",
+            "setHeader",
+            "setBody",
+            "toD",
+            "convertBodyTo",
+            "unmarshal"
+        ],
+        "languages": [
+            "simple"
+        ],
+        "dataformats": [
+            "json"
+        ]
+    },
+    "tags": [
+        "shop",
+        "eip",
+        "cache",
+        "ttl",
+        "invalidation"
+    ],
+    "bundled": true
+}
diff --git a/route/cache/test/cache.citrus.it.yaml 
b/route/cache/test/cache.citrus.it.yaml
new file mode 100644
index 0000000..b4d8340
--- /dev/null
+++ b/route/cache/test/cache.citrus.it.yaml
@@ -0,0 +1,51 @@
+name: cache-test
+description: The cache example calls the customer service once per customer, 
as its README shows
+actions:
+  - camel:
+      cli:
+        run:
+          integration:
+            name: "cache"
+            file: "../cache.camel.yaml"
+            systemProperties:
+              file: "../application.properties"
+          resources:
+            - "incoming/1-order-1001.json"
+            - "incoming/2-order-1002.json"
+            - "incoming/3-order-1004.json"
+            - "incoming/4-order-1005.json"
+            - "incoming/5-customer-C-482-changed.json"
+            - "incoming/6-order-1006.json"
+            - "incoming/7-order-1007.json"
+            - "customers/C-482.json"
+            - "customers/C-207.json"
+  - camel:
+      cli:
+        verify:
+          integration: "cache"
+          logMessage: "Order ORD-1001 for Anna Jensen (gold), customer from 
the service"
+  - camel:
+      cli:
+        verify:
+          integration: "cache"
+          logMessage: "Order ORD-1004 for Anna Jensen (gold), customer from 
the cache"
+  - camel:
+      cli:
+        verify:
+          integration: "cache"
+          logMessage: "Order ORD-1005 for Jonas Weber (silver), customer from 
the cache"
+  - camel:
+      cli:
+        verify:
+          integration: "cache"
+          logMessage: "Customer C-482 changed, removed from the cache"
+  - camel:
+      cli:
+        verify:
+          integration: "cache"
+          logMessage: "Order ORD-1006 for Anna Jensen (gold), customer from 
the service"
+  - camel:
+      cli:
+        verify:
+          integration: "cache"
+          logMessage: "Order ORD-1007: customer C-999 not found (HTTP 404)"

Reply via email to