We will be making use of Spring Boot and Camel SQL Component for inserting and retrieving records from MySQL

The SQL component allows you to work with databases using JDBC queries. 

The SQL component allows you to work with databases using JDBC queries. 

The difference between this component and JDBC component is that in case of SQL the query is a property of the endpoint and it uses message payload as parameters passed to the query.

So it is much easier to use parameterized queries. In case of the scenes for the actual SQL handling, while JDBC component uses the standard JDBC API. 

 

So Camel SQL component is much advanced as we can also make use of features like Spring transaction


Gradle Project 생성 및 의존성, DB 설정 (application properties)

 

- Spring Web, Apche Camel, MySQL Driver dependency 추가

 

- Camel-SQL component dependency 추가

. SQL component는 camel core에 포함되어있지 않으므로 따로 추가해주어야 함

<dependency>
 <groupId>org.apache.camel</groupId>
 <artifactId>camel-sql</artifactId>
 <version>${camel.version}</version>
</dependency>

- application properties에 MySQL 연결 설정

. createDatabaseIfNotExist: DB가 없으면 자동으로 생성해주는 설정

. local에 설정한 username/password가 정확해야 함

spring.datasource.url=jdbc:mysql://localhost:3306/bootdb?createDatabaseIfNotExist=true
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=0103
spring.datasource.platform=mysql
spring.datasource.initialization-mode=always

- schema-mysql.sql 파일 생성

. Spring Boot JDBC가 resources/schema-mysql.sql script를 읽어들여 자동으로 table을 생성해준다

DROP TABLE IF EXISTS employee;

CREATE TABLE employee (
  empId VARCHAR(10) NOT NULL,
  empName VARCHAR(100) NOT NULL
);

Domain, Service, Controller Class 구성

 

- Employee Domain Class 생성

@Getter
@Setter
@ToString
public class Employee {

    private String empId;
    private String empName;

}

- Service Class 생성

. Camel Routebuilder를 상속받아 camel route를 정의하는 class

. Autowiring the datasource been created for us b y Spring Boot JDBC

. Spring Boot Controller가 받은 Http 요청을 Service Class에서 처리

@Service
public class EmployeeService extends RouteBuilder {

    @Autowired
    DataSource dataSource;

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    // define the SQL Component bean which will be used as an endpoint in our route
    @Bean
    public SqlComponent sql(DataSource dataSource) {
        SqlComponent sql = new SqlComponent();
        sql.setDataSource(dataSource);
        return sql;
    }

    @Override
    public void configure() throws Exception {
        //Insert Route
        from("direct:insert").log("Processing message ").setHeader("message", body()).process(
            new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    //take the Employee object from the exchange and create the parameter map
                    Employee employee = exchange.getIn().getBody(Employee.class);
                    Map<String, Object> employeeMap = new HashMap<>();
                    employeeMap.put("EmpId", employee.getEmpId());
                    employeeMap.put("EmpName", employee.getEmpName());
                    exchange.getIn().setBody(employeeMap);
                }
            }).to("sql:INSERT INTO employee(EmpId, EmpName) VALUES (:#EmpId, :#EmpName)");
        //Select Route
        from("direct:select").to("sql:select * from employee").process(
            new org.apache.camel.Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    //the camel sql select query has been executed. We get the list of employees.
                    ArrayList<Map<String, String>> dataList = (ArrayList<Map<String, String>>) exchange.getIn()
                        .getBody();
                    List<Employee> employees = new ArrayList<Employee>();
                    System.out.println(dataList);
                    for (Map<String, String> data : dataList) {
                        Employee employee = new Employee();
                        employee.setEmpId(data.get("empId"));
                        employee.setEmpName(data.get("empName"));
                        employees.add(employee);
                    }
                    exchange.getIn().setBody(employees);
                }
            });
    }
}

. POST(insert) 요청은 direct component(direct:insert)로 연결 → exchange에서 Employee 객체 정보를 꺼내서 parameter map  생성하고 exchange에 parameter map을 set해준다

. GET(select) 요청은 direct component(direct:select)연결하여 별도의 processing 없이 DB로 query를 날리게 되고, query가 실행된 후에 select 결과를 exchange에 담는다

 

- Controller Class 생성

. ProducerTemplate 를 사용해서 Camel Route를 호출하게 됨

@RestController
public class EmployeeController {
    @Autowired
    ProducerTemplate producerTemplate;

    @RequestMapping(value = "/employees", method = RequestMethod.GET)
    public List<Employee> getAllEmployees() {
        List<Employee> employees = producerTemplate.requestBody("direct:select", null, List.class);
        return employees;
    }

    @RequestMapping(value = "/employees", consumes = "application/json", method = RequestMethod.POST)
    public boolean insertEmployee(@RequestBody Employee employee) {
        producerTemplate.requestBody("direct:insert", employee, List.class);
        return true;
    }
}

API TEST

 

. POSTMAN으로 GET/POST 요청 후 결과 확인

POST API CALL
GET API CALL


ActiveMQ 설치


Camel Dependency 추가

 

- ActiveMQ 컴포넌트 추가

. ActiveMQ 컴포넌트는 Camel 컴포넌트가 아니기 때문에 pom.xml에 dependency 추가해주어야 한다.


Sender(Producer)

 

- Message Sender Route 정의

@Component
public class ActiveMqSenderRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        //timer
        from("timer:active-mq-timer?period=10000")
            .transform().constant("My message for Active MQ")
            .to("activemq:my-activemq-queue");
        //queue
    }
}

. sender(producer) route를 정의한 camel application을 구동하면, 아래와 같이 queue가 생성됨

. message가 생성되는 period는 30초로 설정 (timer 컴포넌트 옵션)

. 아직 receiver(consumer)가 없으므로 메시지가 pending messages로 쌓이는 것을 확인할 수 있음

- Message Receiver Route 정의 

@Component
public class ActiveMqReceiverRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("activemq:my-activemq-queue")
            .to("log:received-message-from-active-mq");
    }

}

. receiver(consumer) route를 정의한 camel application을 구동하면, 아래와 같이 queue에서 메시지를 가져와 log를 생성

. Queue 상태창을 보면 pending되었던 메시지들이 모두 소비된 것과, consumer application이 구동 중인 것을 확인할 수 있음

Route 정의

. file 컴포넌트 다른 Camel 컴포넌트에서 파일을 처리하거나, 다른 컴포넌트로부터 온 메시지를 디스크에 저장할 수 있게 해준다.

. log를 찍어보면 파일의 contents를 확인할 수 있다.

Message Transformation

 

- By Using transform() method

@Component
public class MyTimerRouterTransformation extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("timer:first-timer")
            .log("${body}")

            //// Transformation by Processing Method  ////
            .transform().constant("Time now is " + LocalDateTime.now())
            .log("${body}")

            .to("log:first-timer"); // Exchange[ExchangePattern: InOnly, BodyType: String, Body: My Constant Message]
    }
}

 

- By Using a Bean

2-1) bean name 호출을 통한 transformation

@Component
public class MyTimerRouterBeanTransformationA extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("timer:first-timer")
            .log("${body}")

            //// Bean Transformation ////
            .bean("getCurrentTimeBeanA") // bean 이름으로 bean 호출
            .log("${body}")

            .to("log:first-timer");
    }
}
@Component
public class GetCurrentTimeBeanA {

    public String getCurrentTime1() {
        return "Time now is " + LocalDateTime.now();
    }
}

 

2-2) Autowired 어노테이션으로 생성한 객체를 호출하여 transformation

. 아래와 같이 bean에 메소드가 2개 이상일 경우, 반드시 메소드명까지 명시해야 함

@Component
public class MyTimerRouterBeanTransformationB extends RouteBuilder {

    @Autowired
    private GetCurrentTimeBeanB getCurrentTimeBeanB;

    @Override
    public void configure() throws Exception {
        from("timer:first-timer")
            .log("${body}")            

            //// Bean Transformation ////
            .bean(getCurrentTimeBeanB, "getCurrentTime1") // 메소드가 2개이상이면 메소드이름도 명시해야함
            .log("${body}")

            .to("log:first-timer");
    }
}
@Component
public class GetCurrentTimeBeanB {

    public String getCurrentTime1() {
        return "1. Time now is " + LocalDateTime.now();
    }

    public String getCurrentTime2() {
        return "2. Time now is " + LocalDateTime.now();
    }
}


Message Processing

 

- By Using a Bean

. (3) getCurrentTimeBean을 통한 message transformation 이후에 message body가 바뀌었음을 알 수 있다
. (5) bean processing 이후에는 body가 변하지 않는다.
. bean method의 return type이 String이면 body 내용이 변하고(Transformation), void이면 message body가 변하지 않는다(Processing).

 

- By Creating Processor

Route 정의

- RouteBuilder를 상속받아 Route 정의

. timer 컴포넌트는 message exchange를 발생시키는 컴포넌트이며, 생성된 메시지는 오로지 소비(consume)만 가능

. log 컴포넌트는 message exchange에 대한 log를 기록

. 두 Endpoint 사이에서 log() 메소드로 message 내용을 확인할 수 있음 

@Component
public class MyFirstTimerRouter extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("timer:first-timer")
            .log("${body}") // null
            .transform().constant("My Constant Message")
            .log("${body}") // My Constant Message
            .to("log:first-timer"); // Exchange[ExchangePattern: InOnly, BodyType: String, Body: My Constant Message]
    }
}

  • pom.xml 에서 camel version 설정

CamelContext

  . Camel의 핵심 런타임 API로 컴포넌트, 프로세서, Endpoint, 데이터타입, 라우팅 등을 관리

  . CamelContext에 의해서 다양한 모듈이 로딩되고 관리된다.

  . RouteBuilder가 Route를 객체화하여 Context에 binding

** Registry: JNDI registry로, Spring으로 camel을 사용하면 ApplicationContext가 되고 OSGI 컨테이너에 camel을 탑재해 사용하면 OSGI registry가 됨

 

Route

. 컴포넌트, 프로세서들의 연속적인 메시지 연결 정의

. 송신 Component → Proceessor → 수신 Comonent로 하나의 Route가 정의됨

. 1:1 혹은 1:N, N:1 등 다양하게 정의될 수 있다

. https://camel.apache.org/manual/routes.html

Component 

. 일종의 아답터 개념

. Endpoint URL을 가지는 Camel이 메시지를 라우팅 할 수 있는 프로그램 단위

. 통신 프로토콜을 구현한 컴포넌트, 파일시스템 연동을 구현한 컴포넌트 등 자주 사용되는 거의 대부분의 기술에 대해 이미 제작되어있는 Component를 지원함

. 맞춤 Component 작성 기능도 제공

. 동일한 접근법과 구문을 사용하여 서로 다른 기술에 대한 인터페이스 제공 → 어떤 종류의 Transport가 사용되는지에 관계없이 동일한 API로 작업할 수 있게 해줌

. https://camel.apache.org/components/next/

Processor

. Camel 내부에서 메시지를 생성, 형식 변환, 수정, 검증, 필터링 등의 작업을 하여 다른 컴포넌트로 라우팅하는 모듈

. Camel은 EIP 패턴에 기반한 메시지 프로세싱을 지원한다

. Java 인터페이스를 구현해 메시지에 대한 거의 모든 처리를 구현할 수 있음

. https://camel.apache.org/manual/processor.html

 

CamelContext 생성 예시 

https://www.tutorialspoint.com/apache_camel/apache_camel_camelcontext.htm

1) with simple route/simple filter

CamelContext context = new DefaultCamelContext(); // CarnmelContext 생성
try {    
   context.addRoutes(new RouteBuilder() {
      @Override
      public void configure() throws Exception {  // 하나의 configure 매소드에 여러 route 설정 가능
         from("direct:DistributeOrderDSL")        // .xml을 사용한 Spring DSL이나 Scala DSL 등도 사용 가능
         .split(xpath("//order[@product = 'soaps']/items")) // 상품이 "비누"인 경우만 filter
         .to("stream:out"); }  }
} );

2) with simple route/multiple-predicates filter

from("direct:DistributeOrderDSL")
   .choice()
      .when(header("order").isEqualTo("oil"))
         .to("direct:oil")
      .when(header("order").isEqualTo("milk"))
         .to("direct:milk")
      .otherwise()
         .to("direct:d");

3) with simple route/simple filter/custom processor

Processor myCustomProcessor = new Processor() {
   public void process(Exchange exchange) {
      // implement your custom processing
   }
};
CamelContext context = new DefaultCamelContext(); 
try {    
   context.addRoutes(new RouteBuilder() {
      @Override
      public void configure() throws Exception {  
         from("direct:DistributeOrderDSL")        
         .split(xpath("//order[@product = 'soaps']/items")) 
         .process(myProcessor);}
} );

 

DSL(Domain Specific Language)

  . 컴포넌트와 프로세서를 통해 라우트 구성을 정의하기 위해 사용하는 언어

  . DSL을 통해 다양한 동적 라우팅 및 메시지 변환 등 프로그래밍 요소를 삽입 가능

  . DSL은 Route의 Processor 부분을 정의하는데 주로 사용되는데, 송/수신 Component만 정의되면 사실상 시스템 연계에서 구현해야 되는 부분은 거의 Processor이며

    Processor의 로직 대부분은 메세지 처리/변환/라우팅에 해당하는 내용이기 때문에 특수 목적의 DSL을 사용할 수 있으며 DSL 사용을 통해서 개발 생산성이나 코드양을 획기적으로 줄일 수 있음

  . http://camel.apache.org/dsl.html

EndPoint

  . Camel에서 라우팅을 위해 URI 형태로 기술한 컴포넌트 주소

  . 웹 서비스 URI, 대기열(queue) URI, 파일, 전자 메일 주소 등을 참조 가능

  . DSL에서 from() 안에 사용되는 엔드포인트를 Consumer 엔드포인트, to() 안에 사용되는 것을 Producer 엔드포인트라고 함

  . https://camel.apache.org/manual/endpoint.html

Producer

  . Endpoint에 메시지를 생성, 전달하는 개체(송신측)

Consumer

  . Producer에 의해 생성된 메시지를 수신하는 개체(수신측)

  . 수신 후 Exchange를 생성하여 라우터에 던져준다

'~2022 > Apache Camel' 카테고리의 다른 글

[Apache Camel] Feature  (0) 2022.03.12
[Apache Camel] Overview  (0) 2022.03.12

Camel Feature

 

통합 연계 라우팅 엔진

  . Camel은 메시지 라우팅 연계 엔진

  . 다양한 프로토콜, 메시지를 통합하여 일관된 인터페이스로 처리 가능

  . 기본적으로 Sender로부터 메시지를 받아 Receiver에 전달하는 역할

    + 위와 같이 복잡한 환경을 통합하기 위한 여러 기능을 제공

        1) 메시지 포맷 변환 (Format Translation) : ftp → http / jms → json

        2) 메시지 콘텐츠에 따른 필터링 (Filtering, User-Defined)

        3) 라우팅 규칙 정의 (Routing Rules) : Sender A → Receiver B,C / Sender B → Receiver A, C

  . Maintainalbe & Scalable

        1) 송/수신측 메시지 형식에 관계없이 동일한 API를 사용하기 때문에 Sender/Receiver의 변화에 유연함

        2) 새로운 Sender/Receiver 추가가 용이

 

Lightwight Core 라이브러리 모듈

  . camel core 모듈은 4M 정도의 라이브러리 형태로 가벼움

  . 다양한 컨테이너에 포함되어 구동될 수 있고 마이크로 서비스 형태의 서비스가 가능함

 

EIP (Enterprise Integration Patterns) 구현

  . Gregor Hohpe와 Bobby Woolf가 시스템 통합의 문제 해결을 위한 유사한 해법들을 패턴으로 정리한 것

  . 기업 연계 패턴을 분석하여 패턴화 시킨 것 → 메시지 변환, 라우팅, 로그 추적을 위한 글로벌 트랜잭션, 장애시 재처리 등 시스템 연동 등

  . Camel을 통해 EIP 패턴에 기반한 다양한 연계 유형을 조립하여 구성할 수 있음

https://camel.apache.org/components/3.15.x/eips/enterprise-integration-patterns.html

 

DSL (Domain Specific Language) 지원

  . 메시지 라우팅 및 메시지 프로세싱을 다양한 언어로 기술할 수 있도록 함

  . Java, XML, Groovy, Scalar, Kotlin 등 다양한 언어 지원

 

다양한 연계 컴포넌트(150+), 메시지 변환 프로세서 제공

  . 다양한 연계 컴포넌트, 메시지 변환 프로세스가 제작되어 포함되어 있음

  . 필요 시 사용자 컴포넌트를 제작하여 함께 구동시킬 수 있음

'~2022 > Apache Camel' 카테고리의 다른 글

[Apache Camel] Architecture  (0) 2022.03.12
[Apache Camel] Overview  (0) 2022.03.12

Camel Overview

 

Open-source integration framework based on EIP(Enterprise Integration Patterns)

  . 시스템 통합(System Integration)을 위한 오픈 소스 자바 프레임워크

  . Camel: Concise Application Message Exchange Language

  . 대부분의 EIP(Enterprise Integration Patterns) 연계 패턴 구현

  . 라우트 구성을 위해 다양한 언어로 구현된 DSL 지원(Java, XML, Scala, Groovy 등)

  . 다양한 연계 컴포넌트가 구현되어 있고 사용 가능(150+)

  . 특정 컨테이너나 프레임워크에 의존성 없음 → OSGI 컨테이너나 WAS, Spring 등에 탑재 가능하며, 마이크로 서비스 형태로 서비스 가능

'~2022 > Apache Camel' 카테고리의 다른 글

[Apache Camel] Architecture  (0) 2022.03.12
[Apache Camel] Feature  (0) 2022.03.12

+ Recent posts