Apache camel applications using Spring Boot ตอนที่ 2

Chiwa Kantawong (Pea)
2 min readJul 3, 2019

--

ตอนนี้เราจะมาพูดถึง File Component เราจะทำต่อจากโปรเจคส์จากตอนที่ 1 กันนะครับ ให้สร้าง folder input และ output ใน project แล้วก็สร้างไฟล์ test1.txt ใน input ครับ

ต่อไปใน CamelRouter.java เพิ่ม

package com.zengcode.camel;

import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class CamelRouter extends RouteBuilder {

@Override
public void configure() throws Exception {

from("timer://testTimer?period=30s")
.log(LoggingLevel.INFO, "Timer trigger " + new Date());

from("file:input?noop=true")
.log(LoggingLevel.INFO,"Read from the input file")
.to("file:output")
.log(LoggingLevel.INFO,"Written to output file");

}
}

จะเป็นการสร้าง router เพื่อ copy file จาก folder input -> output นะครับ

เมื่อสั่ง spring boot run ก็จะได้ดังภาพ

Camel ก็จะ copy file จาก input->output ให้อัตโนมัติ เมื่อมีไฟล์ใหม่ใน input มันก็จะ copy file ไปยัง output อัตโนมัตินะครับ

เรามาเพิ่มอะไรเล่นๆ สักหน่อยครับ

package com.zengcode.camel;

import org.apache.camel.Exchange;
import org.apache.camel.LoggingLevel;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class CamelRouter extends RouteBuilder {

@Override
public void configure() throws Exception {

from("timer://testTimer?period=30s")
.log(LoggingLevel.INFO, "Timer trigger " + new Date())
.process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
String content = new Date().toString();
exchange.getIn().setHeader(Exchange.FILE_NAME, content + ".txt");
exchange.getIn().setBody(content, String.class);
}
})
.to("file:input");

from("file:input?noop=true")
.log(LoggingLevel.INFO,"Read from the input file")
.to("file:output")
.log(LoggingLevel.INFO,"Written to output file");

}
}

เมื่อ timer ทำงาน เราจะให้มันสร้างไฟล์ ชื่อว่า new Date().txt และมี content เป็น new Date(); โดยสร้างไว้ใน input เมื่อมี ไฟล์เกิดขึ้นที่ input มันก็จะมีการ copy ไปยัง output อัตโนมัติ ดังรูปนะครับ

เอาไว้ติดตามกันต่อตอนที่สามนะครับ

--

--

Chiwa Kantawong (Pea)
Chiwa Kantawong (Pea)

Written by Chiwa Kantawong (Pea)

Software Development Expert at Central Tech

No responses yet