콘텐츠로 이동

Apache Camel과 EIP: 연계 route의 경계와 실패 처리

Interactive Diagram

새 탭 ↗

Apache Camel은 file, HTTP, REST, JMS처럼 서로 다른 transport와 protocol을 하나의 route 모델로 연결하는 integration framework다. 이 문서는 2021년 Camel·EIP 학습 기록을 바탕으로, 어떤 문제에서 Camel이 유용한지와 JMS route 예시를 어떻게 해석해야 하는지 정리한다.

Camel은 모든 연계 문제의 기본 선택지가 아니다. 단일 HTTP client 호출이나 application 내부 function 호출만 필요한 경우에는 framework를 추가하는 것보다 해당 client와 domain code를 명확히 두는 편이 단순하다. 반대로 source와 destination의 protocol·data format·retry·delivery boundary가 반복해서 바뀌고, 이를 business logic에서 분리해야 할 때 Camel route가 유용하다.

  • EIP와 Apache Camel은 각각 무엇을 제공하며, 어떤 관계인가
  • route, endpoint URI, component, message는 어떤 Responsibility를 가지는가
  • file·HTTP·REST·JMS 연계에서 transport-specific code를 business logic과 분리하려면 어떻게 생각해야 하는가
  • direct:에서 jms:queue:로 전달하는 예제는 실제로 무엇을 의미하는가
  • retry, dead-letter queue, idempotency, correlation, observability를 왜 별도 설계해야 하는가

EIP(Enterprise Integration Patterns)는 message channel, message router, message translator, pipes and filters, dead letter channel처럼 서로 다른 system을 연결할 때 반복되는 문제와 해결 구조를 설명한다. Camel은 이 pattern 다수를 Java DSL, XML DSL, YAML DSL과 component endpoint로 표현하게 하는 implementation framework다.

예를 들어 message channel은 application이 메시지를 주고받는 통로를, message translator는 서로 다른 payload format 사이의 변환을, content-based router는 message 내용에 따른 destination 선택을 설명한다. Camel은 이러한 구조를 route step으로 조합하지만, pattern을 사용한다고 해서 delivery guarantee나 business correctness가 자동으로 만들어지는 것은 아니다.

현재 pattern 목록과 component별 option은 Apache Camel EIP 문서와 사용하는 Camel version의 component reference에서 확인한다.

  • Route는 message가 source에서 destination까지 이동하면서 거치는 처리 흐름이다. route에는 수신, 검증, 변환, routing, delivery, error handling의 경계를 둔다.
  • Endpoint는 route가 message를 받거나 보내는 주소다. file:, http:, rest:, jms:처럼 component scheme과 path·option으로 표현한다.
  • Component는 endpoint scheme을 구현하는 integration adapter다. JMS broker, HTTP client/server, filesystem 등 protocol-specific 연결을 담당한다.
  • Message는 body와 header를 포함한 전달 단위다. payload schema, content type, correlation identifier, idempotency key가 필요한지 route의 business contract에서 정한다.
  • Processor 또는 bean은 route 안에서 validation, mapping, business-specific enrichment를 수행한다. transport 처리와 domain rule을 하나의 processor에 섞지 않는 편이 test와 변경 관리에 유리하다.

다음은 source, transform, destination을 분리해 읽는 최소 route 예시다.

from("file:inbox?noop=true")
.routeId("file-to-orders")
.process(this::validateOrder)
.process(this::translateToOrderMessage)
.to("jms:queue:orders.in");

이 예시는 file을 읽고 JMS queue로 보낸다는 흐름만 보여준다. noop=true 같은 option의 적합성, file 이동·중복 처리, schema validation, broker connection, transaction, error handling은 운영 요구사항에 맞게 별도로 결정해야 한다.

JMS component는 queue 또는 topic에 message를 보내거나 소비할 수 있다. endpoint URI 기본 형태는 다음과 같다.

jms:[queue:|topic:]destinationName[?options]
  • jms:queue:orders.in은 point-to-point queue를 명시한다. 하나의 message를 어떤 consumer가 처리할지와 consumer concurrency는 broker·consumer configuration까지 포함해 결정한다.
  • jms:topic:orders.created는 publish/subscribe topic을 명시한다. subscription, durable subscription, consumer lifecycle에 따라 수신 보장이 달라질 수 있다.
  • option은 endpoint 동작을 바꾸므로 URI에 credentials나 민감한 connection detail을 직접 넣지 않는다. connection factory, credential, broker endpoint는 approved secret delivery와 property placeholder mechanism으로 주입한다.

direct: endpoint는 같은 Camel context 안에서 route를 연결하는 in-memory entry point다. 다음 예시는 HTTP controller나 다른 route가 direct:submit-order로 message를 넘기고, producer route가 JMS queue로 전달하는 구조를 나타낸다.

from("direct:submit-order")
.routeId("submit-order-to-jms")
.process(this::validateOrder)
.setHeader("orderId", simple("${body[orderId]}"))
.to("jms:queue:orders.in");

이 route만으로 consumer 구현이나 end-to-end completion은 보장되지 않는다. consumer는 별도 route로 작성하고, producer와 consumer가 공유하는 message schema, header contract, versioning을 명시해야 한다.

from("jms:queue:orders.in")
.routeId("consume-order")
.process(this::validateIncomingOrder)
.bean(orderService, "process")
.to("log:orders.processed");

JMS queue와 topic 구분, transaction과 cache level, request/reply option은 사용하는 broker와 Camel version에 따라 달라진다. Camel JMS component 문서를 현재 dependency version과 함께 확인한다.

실패 처리는 route 밖으로 미루지 않는다

섹션 제목: “실패 처리는 route 밖으로 미루지 않는다”

network timeout, broker outage, malformed payload, downstream business rejection은 서로 같은 실패가 아니다. retry 횟수와 backoff, 재처리 가능성, poison message 격리, alert 조건을 구분해야 한다. 특히 retry가 가능한 transient failure와 retry해도 성공하지 않는 validation failure를 같은 policy로 처리하면 queue backlog나 duplicate side effect가 발생할 수 있다.

Camel의 Dead Letter Channel은 처리·전송에 실패한 message를 dedicated endpoint로 옮기도록 구성할 수 있는 error handler다. 하지만 dead-letter destination을 정하는 것만으로 운영 설계가 끝나지 않는다. DLQ message에는 original payload를 재처리해도 안전한지, failed route와 exception을 어떻게 기록하는지, 누가 어떤 기준으로 replay하는지를 함께 정의해야 한다.

errorHandler(deadLetterChannel("jms:queue:orders.dlq")
.useOriginalMessage()
.maximumRedeliveries(3)
.redeliveryDelay(1000));
from("jms:queue:orders.in")
.routeId("consume-order")
.process(this::validateIncomingOrder)
.bean(orderService, "process");

위 값은 production default가 아니라 구조를 보여주는 예시다. broker delivery policy, transaction boundary, idempotency store, downstream API의 retry semantics를 확인한 뒤에 설정한다. Dead Letter Channel 문서는 error handler와 dead-letter endpoint의 동작을 설명한다.

운영 가능한 route를 위한 확인 항목

섹션 제목: “운영 가능한 route를 위한 확인 항목”
관심사적용 전에 결정할 질문최소 검증
Contractbody schema, required header, version은 무엇인가producer와 consumer contract test를 통과한다
Deliveryat-most-once, at-least-once, duplicate 가능성 중 무엇을 허용하는가duplicate message를 재처리해도 side effect가 안전한지 확인한다
Failureretry할 error와 즉시 DLQ로 보낼 error는 무엇인가timeout, malformed payload, business rejection을 각각 재현한다
Observabilityroute ID, correlation ID, message ID, failure reason을 어디에 남기는가한 message가 producer·broker·consumer·DLQ에서 추적된다
Securitybroker credential과 payload의 sensitive field를 어떻게 다루는가secret이 URI·log·source repository에 남지 않는지 확인한다
Changeroute·schema·endpoint option 변경을 어떻게 rollout하는가consumer compatibility와 rollback path를 검증한다

실습 기록: legacy open API를 Spring Boot + Camel REST로 감싸기 (2021)

섹션 제목: “실습 기록: legacy open API를 Spring Boot + Camel REST로 감싸기 (2021)”

이 절은 2021년에 legacy system의 open API를 내부 UI용 REST endpoint로 감싸던 구현 기록이다. 이런 연계는 대부분 같은 순서를 따른다.

  1. target API를 정의한다.
  2. target API가 요구하는 payload를 만든다.
  3. target API를 호출한다.
  4. 응답 object를 UI가 쓰는 JSON으로 변환해 반환한다.

Camel은 이 반복 흐름을 route로 선언하게 해 준다. 아래에서는 같은 route를 Java DSL과 XML로 각각 작성한다. 2021년 당시 Spring Boot와 Camel 3.x 기준이므로, 현재 적용할 때는 아래 현재 적용 전 다시 확인할 항목을 함께 본다.

Springboot 와 Apache Camel 을 이용한 개발 절차

섹션 제목: “Springboot 와 Apache Camel 을 이용한 개발 절차”

Apache Camel 은 Springboot 을 위해 별도의 라이브러리를 제공할 정도로 친화적입니다. Apache Camel 만으로도 충분히 개발이 가능하지만 개발에 익숙한 springboot 를 이용하여 개발하는 과정을 설명합니다.

  • vs code 에 Spring Boot Extension Pack 을 install 합니다.
  • vs code > View > Command Palette 메뉴를 선택합니다.
  • 입력창에 spring 을 입력한 후 Spring Initializer : Create a Maven Project 를 선택합니다.
  • 이후 단계별 wizard 를 통해 springboot project 를 생성합니다.

pom.xml 에 필요한 라이브러리 추가

섹션 제목: “pom.xml 에 필요한 라이브러리 추가”
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-http-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-rest-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-servlet-starter</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.springboot</groupId>
<artifactId>camel-jackson-starter</artifactId>
</dependency>

Camel Rest 를 사용하여 Rest API 를 제공하려면 ServletRegistrationBean 를 Bean 으로 생성해야 합니다. CamelWebConfig 클래스는 위 작업을 수행합니다.

@Configuration
public class CamelWebConfig {
private static final String CAMEL_URL_MAPPING = "/camel/*";
private static final String CAMEL_SERVLET_NAME = "CamelServlet";
@Bean
public ServletRegistrationBean<CamelHttpTransportServlet> servletRegistrationBean() {
CamelHttpTransportServlet camelHttpTransportServlet = new CamelHttpTransportServlet();
camelHttpTransportServlet.setAsync(true);
ServletRegistrationBean<CamelHttpTransportServlet> registration = new ServletRegistrationBean<>(
camelHttpTransportServlet, CAMEL_URL_MAPPING);
registration.setName(CAMEL_SERVLET_NAME);
return registration;
}
}

아래 java class 를 생성합니다.

@Component
public class RestRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
restConfiguration().component("servlet").bindingMode(RestBindingMode.json);
// rest api 를 정의합니다.
rest("/sample")
.get("/")
.to("direct:get_sample")
.post("/")
.to("direct:post_sample")
;
// get 에 대한 다른 rest api 로 routing 처리합니다.
// api 는 별도로 개발이 필요합니다.
from("direct:get_sample")
.to("rest:get:?host=localhost:8090/sample/")
;
// post 에 대한 다른 rest api 로 routing 처리합니다.
// api 는 별도로 개발이 필요합니다.
from("direct:post_sample")
.to("rest:post:?host=localhost:8090/sample/")
;
}
}

java 로 개발된 코드를 xml 로 구성

섹션 제목: “java 로 개발된 코드를 xml 로 구성”
  • resources 폴더에 아래 파일을 생성합니다.
  • SpringRouteContext.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://camel.apache.org/schema/spring
    http://camel.apache.org/schema/spring/camel-spring.xsd ">
    <camelContext xmlns="http://camel.apache.org/schema/spring">
    <rests>
    <rest path="/sample">
    <get uri="/">
    <to uri="direct:get_sample"/>
    </get>
    <post uri="/">
    <to uri="direct:post_sample"/>
    </post>
    </rest>
    </rests>
    <routes>
    <route>
    <from uri="direct:get_sample" />
    <to uri="rest:get:?host=localhost:8090/sample/"/>
    </route>
    <route>
    <from uri="direct:post_sample" />
    <to uri="rest:post:?host=localhost:8090/sample/"/>
    </route>
    </routes>
    </camelContext>
    </beans>
  1. 이 문서에서 route·endpoint·EIP·JMS의 기본 경계를 이해한다.
  2. 이 글의 실습 기록에서 Spring Boot와 Camel로 legacy API를 받아 payload를 변환하고 REST endpoint로 노출하던 2021년 구현을 따라간다.
  3. 더 큰 integration Runtime의 listener·mapper·adapter 경계는 통합 플랫폼 Runtime을 Listener, Mapper, Adapter로 나누는 이유에서 확인한다.
  4. 실행 이력과 failure signal의 설계는 분산 Integration Trace와 Integration Alerting과 Metrics 설계로 이어서 본다.
  • Version과 dependency: Camel core, Spring Boot starter, JMS provider, component artifact는 compatibility matrix와 BOM을 기준으로 함께 결정한다.
  • Endpoint option: URI option, transaction, cache level, consumer concurrency, request/reply behavior는 component와 broker 조합별로 확인한다.
  • Data contract: route DSL이 payload schema와 business validation을 대체하지 않는다. versioning과 backward compatibility를 명시한다.
  • Delivery semantics: retry와 redelivery는 duplicate delivery를 만들 수 있다. external side effect에는 idempotency key와 replay procedure를 설계한다.
  • Operations: route ID, correlation ID, error class, DLQ depth, redelivery count를 metric·log·trace에 연결하고 alert threshold를 정한다.
  • Credentials: broker URL, username, password, client certificate를 example URI나 source code에 넣지 않는다.