Apache Camel 是強大的企業整合模式(EIP)路由引擎,支援 300+ 組件(HTTP、JMS、FTP、檔案、資料庫等),讓業務邏輯與傳輸細節解耦。本文以純 Java DSL 示範核心概念與快速上手。
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>2.11.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
public class TimerRouteBuilder extends RouteBuilder {
private static final Logger LOG = LoggerFactory.getLogger(TimerRouteBuilder.class);
@Override
public void configure() {
from("timer://timer1?period=1000")
.process(exchange -> LOG.info("Processing {}", exchange));
}
}
from():定義訊息來源端點process():自定義處理邏輯to():發送至目標端點mvn compile exec:java \ -Dexec.mainClass=org.apache.camel.main.Main \ -Dexec.args='-r camelcoredemo.TimerRouteBuilder'
public class TimerMain {
public static void main(String[] args) throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(new TimerRouteBuilder());
context.setTracing(true); // 開啟追蹤
context.start();
// 優雅關閉鉤子
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try { context.stop(); } catch (Exception e) { throw new RuntimeException(e); }
}));
// 阻塞主線程
Thread.sleep(Long.MAX_VALUE);
}
}
public class TimerMain2 extends Main {
public static void main(String[] args) throws Exception {
TimerMain2 main = new TimerMain2();
main.enableHangupSupport(); // 優雅關閉
main.addRouteBuilder(new TimerRouteBuilder());
main.run(args); // 支援命令列參數
}
}
# 啟用追蹤 mvn exec:java -Dexec.mainClass=camelcoredemo.TimerMain2 -Dexec.args='-t'
將處理邏輯提取為獨立 Bean,路由僅聲明流向:
public class TimerBeansMain extends Main {
public static void main(String[] args) throws Exception {
TimerBeansMain main = new TimerBeansMain();
main.enableHangupSupport();
main.bind("processByBean1", new Bean1());
main.bind("processAgainByBean2", new Bean2());
main.addRouteBuilder(() -> new RouteBuilder() {
public void configure() {
from("timer://timer1?period=1000")
.to("bean:processByBean1")
.to("bean:processAgainByBean2");
}
});
main.run(args);
}
static class Bean1 implements Processor {
public void process(Exchange exchange) { LOG.info("First process {}", exchange); }
}
static class Bean2 implements Processor {
public void process(Exchange exchange) { LOG.info("Second process {}", exchange); }
}
}
優勢:
bash> mvn compile bash> mvn exec:java -Dexec.mainClass=camelcoredemo.TimerMain2 -Dexec.args='-t'
控制台將每秒輸出處理日誌,確認路由正常運行。
Apache Camel 以「約定優於配置」與豐富 EIP 實作,大幅降低系統整合複雜度。掌握 Java DSL 與 Bean 解耦模式,是構建可維護整合方案的關鍵起點。