Skip to content

Content-based Router

A Content-Based Router looks at each message that arrives. It reads data in the message and picks the channel that fits. A channel is a path that carries messages to a receiver (see the article Message Channel). The router then puts the message on that channel.

The pattern solves a common problem. Sometimes one logical function is spread over several systems. The router sends each message to the right system, based on what the message contains.

How it looks in tools

  • Apache Camel implements the pattern with its Choice feature. Choice routes on the contents of the message exchange.
  • In Camel, the first when clause that matches decides the branch.
  • An optional otherwise clause handles messages that match no when. Without it, no branch is selected.
  • Spring Integration describes routers as components that read from one channel. They forward each message to other channels based on conditions.
  • Spring Integration offers payload-type, header-value, recipient-list, XPath and generic routers. By default it throws an exception if no channel is found.

Related pattern

The rules in a Content-Based Router are fixed. The router depends on all possible destinations. The Dynamic Router removes this dependency. It adds a control channel. Recipients announce themselves on that channel, so the router configures itself. See the article Dynamic Router.

An online shop receives orders on one channel. Each order carries a product category. The router reads the category. Book orders go to the channel of the book supplier. Electronics orders go to the channel of the electronics supplier. A fallback branch, or an error, must handle a category that no rule covers.

  • The routing logic is a maintenance concern. The pattern itself warns that it must be kept easy to maintain.
  • The router depends on all possible destinations. Each new destination means a change to the router.
  • Order matters in Camel: the first matching when wins, so rule sequence affects results.
  • Messages that match no rule need a deliberate answer. Camel’s otherwise clause is one option. Spring Integration throws an exception by default.
  • The Dynamic Router trades fixed rules for self-configuration through a control channel.

A router reads the category in each order and picks the matching channel.

Diagram source
flowchart LR
In[Incoming orders] --> R{Content-Based Router}
R -->|category = books| A[Book supplier channel]
R -->|category = electronics| B[Electronics supplier channel]
R -->|no rule matches| C[Fallback or error handling]
  • The routing rules are documented and kept easy to maintain.
  • The document states what happens to a message that matches no rule.
  • Where rules are checked in order, the order is documented, because the first match decides the branch.
  • The document lists the destinations the router depends on, or explains how they are discovered, for example with a Dynamic Router.