달력

3

« 2024/3 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

'Spring Integration'에 해당되는 글 1

  1. 2009.02.28 10분만에 Spring Integration 따라잡기

(역자 주)

본 글은 Springsource 사의 Mark Fisher가 2009년 2월 13일에 영어로 쓴 Spring Integration in 10 minutes을 우리말로 번역한 것입니다.


10분만에 Spring Integration 따라잡기

두 달 전 SpringOne America에서 Spring Integration 1.0 GA release를 발표했고, 그 때부터 얼른 "바로 시작하기" blog post를 쓰려 했습니다. 글쎄요, 새해부터는 늘 바쁜 나머지, 일단 10단계의 따라하기 예제 제공을 목표로 했습니다. 각 단계는 대략 1분 정도가 걸립니다... 생각하느라 멈추지만 않으면요. ^^ 어쨌든, 더 꾸물거리지 말고, 바로 가 보죠!

1단계: Spring Integration 배포본 내려받기

여기에서 가장 최신의 배포판을 얻을 수 있습니다.
http://www.springsource.com/download/community?project=Spring%20Integration

내려받기가 끝나면, zip file을 푸세요. Spring Integration project를 이루는 JAR들을 담은 'dist' directory가 있을 것입니다. 또한 'lib' directory에는 Spring Integration이 필요로 하는 외부 library들이 있습니다.

2단계: project 생성

이 예제에서 Eclipse를 쓰지만, 이 작업은 당연히 다른 IDE에서도 가능합니다. Maven이나 Ivy도 쓸 수 있지만, 이 예제는 매우 간단해서, directory를 만들고 JAR file들을 추가하는 것으로 충분합니다.

새 'Java Project'를 생성하고('Package Explorer' view에서 오른쪽 click 후 'New -> Java Project'), 그 project 안에 'lib' directory를 만듭니다. 그리고나서 다음 JAR file들을 Spring Integration의 'dist'와 'lib' directory에서 이 project의 'lib'으로 옮깁니다.

dist에서는

  • org.springframework.integration-1.0.1.RELEASE.jar
  • org.springframework.integration-file-1.0.1.RELEASE.jar

lib에서는

  • com.springsource.org.aopalliance-1.0.0.jar
  • com.springsource.org.apache.commons.logging-1.1.1.jar
  • org.springframework.aop-2.5.6.A.jar
  • org.springframework.beans-2.5.6.A.jar
  • org.springframework.context-2.5.6.A.jar
  • org.springframework.core-2.5.6.A.jar
  • org.springframework.transaction-2.5.6.A.jar

'lib' directory를 refresh(F5를 치세요)한 다음 build-path에 위 JAR file들을 추가하십시오(JAR file들을 고른 다음, 오른쪽 click 후 "Build Path -> Add to Build Path" 선택). 마지막으로, 'src' directory에 'blog' package를 추가하시고요.

3단계: Spring Integration 시작

Spring IDE나 SpringSource Tool Suite을 쓰신다면, Spring project의 특성을 자연스럽게 쓸 수 있으므로 그냥 새 bean 정의 file을 생성하려면 'blog' package를 오른쪽 click만 하면 됩니다. 그렇지 않더라도 아래 내용을 생성하고 file 이름을 'config.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"
       xmlns:si="http://www.springframework.org/schema/integration"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/integration
           http://www.springframework.org/schema/integration/spring-integration-1.0.xsd"
>
</beans>

element 한 개를 더 추가하겠습니다. 이는 Java in-memory queue를 근간으로 하는, 한 번에 10개의 message를 담을 수 있는 Message channel을 정의합니다.

<si:channel id="channel">
    <si:queue capacity="10"/>
</si:channel>

4단계: Bootstrap Java class 정의

Spring Integration component들은 Spring ApplicationContext에 들어있습니다. 그래서 설정 file로 ApplicationContext 하나를 만드는 일만 하면 됩니다. Web Application에서 구동하려면 Spring의 ContextLoaderListener으로 기동할 수 있고, 또는 만약 dmServer에서라면, 저절로 알아서 기동할 겁니다. 이 초간단 예제에서는 그냥 ('blog' package에 있는) Bootstrap이라는 class에 main() method를 만드는 것으로 하겠습니다.

public class Bootstrap {
    public static void main(String[] args) {
        new ClassPathXmlApplicationContext("blog/config.xml");
    }
}

(언제든지 Eclipse에서 Ctrl+Shift+O…, Mac에서는 Command+Shift+O를 눌러 "organize imports"를 할 수 있습니다).

5단계: Spring Integration Message 송/수신

이제, context에세 channel을 가져와 message를 보낼 수 있습니다. 아직 구독자(subscriber)가 없기 때문에(다음 단계에서 할 것입니다), 같은 channel에서 message를 받기로 하겠습니다. 이를 통해 설정이 제대로 되었는지 확인할 수 있죠. 아래처럼 main() method를 고치세요.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("blog/config.xml");
    PollableChannel channel = (PollableChannel) context.getBean("channel");
    channel.send(new StringMessage("Spring Integration이 끝내줘요"));
    Message<?> reply = channel.receive();
    System.out.println("received: " + reply);
}

이걸 돌리면 message 객체의 toString() method 수행 결과가 console에 찍히는 것을 보실 수 있습니다.

6단계: Service 생성

Spring Integration은 program들이 Spring과 느슨한 결합도를 가지는 것을 추구합니다. 즉, 우린 이 예제를 점진적으로 고쳐서 어떤 code도 framework에 엮여버리지 않도록 할 것입니다. 첫번째 할 일은,  message를 구독할 POJO Service를 추가하는 것입니다. 이 예제에서는 단순히 문자열을 대문자로 바꾼 뒤 느낌표를 덧붙이는 일을 합니다.

public class Shouter {
    public String shout(String s) {
        return s.toUpperCase().concat("!!!");
    }
}

7단계: Spring 설정에 Service 추가

이 Service는 그냥 일반적인 bean으로 추가하면 됩니다.

<bean id="shouter" class="blog.Shouter"/>

그 다음, 우린 Service bean에 입/출력 channel을 붙이는 "Service Activator"를 추가할 것입니다. 현재 있는 "channel"의 이름을 "output"으로 바꾸고, 입력용으로 단순한 non-buffering channel을 더합니다. 전체 설정은 아래와 같습니다.

<si:channel id="input"/>
<si:channel id="output">
    <si:queue capacity="10"/>
</si:channel>
<si:service-activator input-channel="input"
           output-channel="output"
           ref="shouter"
           method="shout"/>
<bean id="shouter" class="blog.Shouter"/>

단계 8: Message를 보내 Service 호출

input channel에 message를 보내고 output channel에서 message를 받도록 main() method를 고칩니다. 의존성을 lookup하는 부분과 channel 객체에 대한 type casting이 바뀌었음을 주목하세요(지금부터 output은 PollableChannel이고 'input' channel은 output과 달리 non-buffering channel입니다).

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("blog/config.xml");
    MessageChannel input = (MessageChannel) context.getBean("input");
    PollableChannel output = (PollableChannel) context.getBean("output");
    input.send(new StringMessage("Spring Integration이 끝내줘요"));
    Message<?> reply = output.receive();
    System.out.println("received: " + reply);
}

9단계: 출력을 file로 보내기

Channel Adapter를 추가하면 main() method에서 출력을 polling하지 않고 결과를 곧장 file에 보낼 수 있습니다. 이렇게 하면 polling이 필요 없으므로, 먼저 output channel의 하위 element인 queue를 없애겠습니다.

<si:channel id="output"/>

Channel Adapter를 더합니다. 현재 directory를 지정할 수도 있고, Windows라는 drive 문자를 포함할 수도 있습니다(예를 들면 "C:/tmp" 같은).

<file:outbound-channel-adapter channel="output" directory="/tmp"/>


그 다음, Bootstrap의 main() method를 송신만 하도록 고칩니다.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("blog/config.xml");
    MessageChannel input = (MessageChannel) context.getBean("input");
    input.send(new StringMessage("Spring Integration이 끝내줘요"));
}

XSD 설정에 'file' namespace를 추가하는 일도 해야 합니다. 최상위의 'beans' element가 아래처럼 생길 것입니다.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:si="http://www.springframework.org/schema/integration"
       xmlns:file="http://www.springframework.org/schema/integration/file"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/integration
            http://www.springframework.org/schema/integration/spring-integration-1.0.xsd
            http://www.springframework.org/schema/integration/file
            http://www.springframework.org/schema/integration/file/spring-integration-file-1.0.xsd">

예제를 돌리면 ".msg" 확장자가 달린 file에 결과를 볼 수 있습니다(file 이름 생성 규칙도 추가할 수 있지만 이 post의 범위를 벗어납니다).

10단계: Gateway interface 생성

마지막 단계의 목표는 Spring과의 의존성을 완벽하게 없애는 것입니다. Message를 Message Channel에 보내기보다는, 단순한 interface의 인자로 문자열를 보내는 것이 훨씬 더 깔끔합니다. 'blog' package에 다음 interface를 추가합니다.

public interface Gateway {
    void send(String s);
}

그리고, 다음 element를 설정에 추가합니다.

<si:gateway id="gateway" service-interface="blog.Gateway" default-request-channel="input"/>


마지막으로, main() method에서 channel 대신 Gateway를 씁니다. 이제 단순히 문자열만 넘기면 됩니다.

public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("blog/config.xml");
    Gateway gateway = (Gateway) context.getBean("gateway");
    gateway.send("Spring Integration이 끝내줘요");
}

마치며

이 글이 Spring Integration에 대한 쓸만한 소개글이었으면 좋겠습니다. 여지껏 다룬 내용의 주안점은 Spring과 낮은 결합도를 가지면서도 통합 계층을 쉽게 만들 수 있다는 점입니다. 만약 독자 제위께서 여러 endpoint를 추가하기 시작한다면 이에 대한 가치를 피부로 느끼실 수 있을 것입니다. 하다 보면 filter, transformer, router를 더 추가해야 할 지도 모르겠습니다.

Spring Integration에는 이 예제에서 나온 것보다 훨씬 더 풍부한 기능이 있습니다. 더 살펴보시려면, 'org.springframework.integration.samples' module(배포본의 'src' directory에 source도 들어있습니다)에 들어있는 다양한 project들을 검토해 보시고 참조 문서를 읽어보십시오. 물론, Spring Integration home page에서도 풍부한 정보를 찾을 수 있습니다.

이 글은 스프링노트에서 작성되었습니다.

:
Posted by 하얀 말