[Camel in Action] 3-5. Apache Velocity 템플릿으로 메시지 생성하기

템플릿 기반 메시지 생성

Apache Velocity는 Java 기반 템플릿 엔진입니다. 정해진 형식에 동적 데이터를 채워 넣어야 할 때(이메일 본문, 보고서, XML 요청 등) 매우 유용합니다. Camel은 Velocity와의 통합을 기본으로 제공합니다.

의존성 추가

<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-velocity-starter</artifactId>
</dependency>

Velocity 템플릿 작성

## src/main/resources/templates/order-email.vm

안녕하세요, ${body.customerName}님!

주문 접수 확인 메일입니다.

주문 정보:
- 주문 번호: ${body.orderId}
- 주문 일시: $date
- 상품: #foreach($item in $body.items)
  * ${item.productName} x ${item.quantity} = ${item.subtotal}원
  #end
- 총 금액: ${body.totalAmount}원

배송 주소: ${headers.deliveryAddress}

감사합니다!

라우트에서 Velocity 사용

from("direct:sendOrderConfirmation")
    .to("velocity:templates/order-email.vm")  // 템플릿 적용
    .log("이메일 내용 생성 완료")
    .to("smtp://mail.example.com?to=${header.customerEmail}");

Velocity 컨텍스트 변수

템플릿에서 접근 가능한 기본 변수들:

  • ${body}: 메시지 본문 객체
  • ${headers}: 메시지 헤더 Map
  • ${header.xxx}: 특정 헤더 값
  • ${exchange}: Exchange 객체 전체
  • ${camelContext}: CamelContext
  • $date: 현재 날짜 (VelocityTools)

XML API 요청 템플릿

## soap-request.vm
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
    <soap:Body>
        <OrderRequest xmlns="http://example.com/orders">
            <OrderId>${body.orderId}</OrderId>
            <CustomerId>${body.customerId}</CustomerId>
            <Amount>${body.amount}</Amount>
            <Currency>${header.currency}</Currency>
        </OrderRequest>
    </soap:Body>
</soap:Envelope>
from("direct:callSoap")
    .to("velocity:soap-request.vm")
    .setHeader(Exchange.HTTP_METHOD, constant("POST"))
    .to("http://legacy-service/soap?bridgeEndpoint=true");

FreeMarker – Velocity의 대안

Velocity 대신 FreeMarker 템플릿 엔진도 사용할 수 있습니다.

<!-- FreeMarker 의존성 -->
<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-freemarker-starter</artifactId>
</dependency>
// FreeMarker 사용 (동일한 방식)
from("direct:generateReport")
    .to("freemarker:templates/report.ftl")
    .to("file:reports?fileName=report_${date:now:yyyyMMdd}.html");

Mustache 템플릿

// Mustache - Logic-less 템플릿
from("direct:mustache")
    .to("mustache:templates/notification.mustache");

Leave a Comment