Messaging with RabbitMQ

2017. 5. 11. 18:06DB&NoSQL/RabbitMQ

메시지를 게시(publish)하고 구독(Subscribe)하는 RabbitMQ AMQP 서버를 셋업하는 절차를 알려드리도록 하겠습니다.

빌드 대상

Spring AMQP의 RabbitTempate를 사용해서 메시지를 게시(publish)하고,
MessageListenerAdaper를 사용해서 POJO 로 메시지를 구독(subscribe)하는 어플리케이션을 빌드합시다.

필요 조건 

- 15분쯤
- 즐겨쓰는 텍스트 에디터 나 IDE
- JDK 1.8 이상
- Gradle 2.3 이상 혹은 Maven 3.0 이상
- 여러분 IDE에 직접 코드를 임포트 할수 있습니다
     - STS
     - IntelliJ IDEA
          - RabbitMQ server(설치 구성은 아래에)

가이드 완성 방법

 "Spring 시작하기가이드들과 마찬가지로, 처음부터 차근차근 시작할수 있으며,
각 단계를 완료할 수 있거나,친숙한 기본 과정을 건너뛸 수도 있습니다.
어떤 방법이든 코드 작성을 완성 할 수 있습니다.

처음부터 시작하려면, Gradle로 빌드하는 법부터 보시면 됩니다.
이런 기초 단계를 건너뛰려면, 아래와 같이 하세요:

 - 해당가이드에 대한 소스 저장소를 다운로드해서 압축을  풀거나, Git을 사용해서 복제하세요.
 - gs-messaging-rabbit/initial 로 이동해요
 - "Create a RabbitMQ message receiver" 로 이동하세요.

완성하고 나서 ,  gs-messaging-rabbitmq/complete와 여러분의 코드를 비교할 수 있답니다.

> Gradle로 빌드하기

첫째, 기본 빌드 스크립트를 세팅합니다.
Spring 기반의 어플리케이션을 빌드 할 땐, 좋아하는 빌드 시스템중 어떤것이라도 가능합니다.
허나, 여기에는 Gradle 과 Maven으로 작성한 코드가  있습니다.
Gradle로 Java 프로젝트 빌드하기(https://spring.io/guides/gs/gradle) 나
Maven으로 Java 프로젝트 빌드하기(https://spring.io/guides/gs/maven)를 참조하세요

디렉토리 구조 생성하기

여러분이 선택한 프로젝트 디렉토리에는 아래 하위 디렉토리 구조를 따르게 생성하세요.
예를 들면, *nix 시스템상에  mkdir -p src/main/java/hello 이죠 (package)

└── src
    └── main
        └── java
            └── hello
아래는 초기 Gradle 빌드 파일 입니다.

build.gradle


buildscript{
    repositories{
        mavenCentral()
    }
    dependencies{
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
    }
}
apply plugin'java'
apply plugin'intellij'
apply plygin 'idea'
apply plugin 'org.springramework.boot'

jar{
    baseName='gs-messaging-rabbitmq'
    version '0.1.0'
}

repositories{
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8


dependencies {
    compile("org.springframework.boot:spring-boot-starter-amqp")
    testCompile group'junit'name'junit'version'4.11'
}

Spring Boot gradle 플러그인은 많은 편리한 기능을 제공합니다.

 - 클래스패스상에 모든  jars을 모아주고,  여러분의 서비스를 전송하고 실행하는데 좀 더 편하게 만들어 주는 단독 실행 가능한 "uber-jar"를 빌드합니다.  
 - public static void main() 메소드를 검색하여 실행가능한 클래스로 플래그를 지정합니다.
 - Spring Boot 의존관계를 매칭하는 버전 번호를 세팅해주는 내장형 의존관계 해결사(built-in dependency resolver)를 제공합니다.
  원하는 어떤 버전이라도 오버라이드할수 있습니다만,  부트가 선택한 버전이기본이 될것입니다.

RabbitMQ broker 세팅

메시징 어플리케이션을 빌드하기 전에, 메시지를 받고, 보내는것을 다루는 서버를 세팅해야 합니다.
RabbitMQ는 AMQP 서버입니다. 
https://www.rabbitmq.com/download.html 에서 무료로 이용할수 있습니다. 
수동으로 다운로드 하거나,  Mac 유저인 경우에는 brew 명령어를 통해서 다운로드 받을수 있습니다.

저희는 Windows 유저이니.. 수동으로 받아봅시다. : Rabbitmq-server-3....exe 받아서 설치 시작
헐.. Erlang을 사전에 설치해야 한다고 합니다. 설치하고 나서 아래와 같이 기동합시다. 

rabbitmq-server

아래와 같은 것을 볼수 있다고 합니다.



로컬에서 운영하는 dockerDocker를 갖고 있으면, Compose를 사용해서도 RabbotMQ 서버를 빠르게 기동할수 있다. 
Github에 complete 프로젝트 루트상에 docker-compose.yml 이 있는데, 매우 간단하다. 

docker-compose.yml

rabbitmq:
     image : rabbitmq:management
     ports:
          - "5672:5672"
          -"15672:15672"

현재 디렉토리에 이 파일을 가지고 컨테이너에서 기동하는 RabbitMQ를 갖기위해 docker-compose를 가동할수 있습니다.

RabbitMQ 메시지 리시버 생성하기

메시징 기반의 어플리케이션과 함께, 여러분은 게시된 메시지들에 응답 할 수있는 리시버를 생성할 필요가 있습니다.

src/main/java/hello/Receiver.java

import org.springframework.stereotype.Component;
import java.util.concurrent.CountDownLatch;

/**
 * Created by dennis on 2017-05-10.
 */

@Component
public class Receiver {

    private CountDownLatch latch new CountDownLatch(1);

    public void receiveMessage(String message){
        System.out.println("received < " + message + ">");
        latch.countDown();
    }

    public CountDownLatch getLatch(){
        return latch;
    }
}

리시버는 메세지들을 받기위한 메소드를 정의하는 하나의 단순 POJO 입니다.
메시지들을 받기 위한 것을 등록할 때, 여러분이 원하는 대로 이름 지을수 있습니다.

* 편의상, 해당 POJO는 CountDownLatch 을 갖고 있습니다. 이건 메시지가 받아졌음을 알릴수 있습니다.
이것은 제품 어플리케이션상에서 구현할 필요가 없다는 것입니다. 

리스너 등록하고 메시지 보내기

Spring AMQP의 RabbitTemplate은 여러분이 RabbitMQ을 가지고 메시지들을 보내고 받는데 필요한 모든것을 제공합니다. 
여러분은 확실하게  아래 내용을 구성해야 합니다 : 
-  메세지 리스터 컨테이너
-  큐, 익스체인지, 그리고 둘 사이를 바인딩하는 것을 선언
-  리스너를 테스트하기위해 메시지 몇개를 보내는 컴포넌트

* Spring Boot는 connection factory와 RabbitTemplate를 여러분이 작성해야할 코드 양을 줄이기 위해 자동으로 생성합니다. 

메시지를 보내는 RabbitTemplate을 사용하고, 메시지를 받기 위한 메시지 리스너 컨테이너를 포함한 Receiver를 등록할 것입니다.
커넥션 팩토리는 둘 다 기동하여,  RabbitMQ 서버에 연결할 수 있게 합니다.

src/main/java/hello/Application.java

package hello;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * Created by dennis on 2017-05-10.
 */
@SpringBootApplication
public class Application {

    final static String queueName "spring-boot";

    @Bean
    Queue queue(){
        return new Queue(queueName, false);
    }

    @Bean
    TopicExchange exchange(){
        return new TopicExchange("spring-boot-exchange");
    }

    @Bean
    Binding binding(Queue queueTopicExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactoryMessageListenerAdapter listenerAdapter){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver){
        return new MessageListenerAdapter(receiver,"receiveMessage");
    }

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class,args);
    }
}

@SpringBootApplication 은 아래 모든것이 포함된 편리한 어노테이션입니다.

- @Configuration 은 어플리케이션 컨텍스트에 대한 빈 정의 소스로써 클래스를 태그합니다.
- @EnableAutoConfiguration은 클래스패스 세팅들, 다른 빈즈 그리고 다양한 프로퍼티 세팅들에 기반한 빈즈를  추가하는 것을 시작하라고 Spring Boot에게 이야기합니다.
- 일반적으로, Spring MVC 앱에는 @EnableWebMvc을 추가하지만,  Spring Boot는 클래스패스에 spring-webmvc가 있을때 자동으로 추가합니다.
  이건 어플리케이션을 웹 어플리케이션으로써 플레그를 지정하고, DispatcherServlet을 세팅한 것과 같이 주요 동작등을 활성화합니다. 
- @ComponentScan은 Spring에게 다른 컴포넌트들, 구성, 그리고 서비스들을 hello 패키지안에서 찾아서, 컨트롤러들을 찾도록 지시합니다.

main() 메소드는 Spring Boot의 SpringApplication.run() 메소드를 어플리케이션을 런칭하기 하기 위해 사용합니다.
XML 라인 하나도 없었다는것을 알겠나요?어떤 web.xml 파일도 필요가 없지요.
이 웹 어플리케이션은 100% 순수 자바 이고, 여러분은 어떤 설정도 다룰 필요가 없습니다.

listenerAdapter() 메소드에 정의된 빈즈는 container()로 정의된 컨테이너에 메시지 리스너로 등록됩니다.
이건 "spring-boot" 큐에 메세지들을 리스닝 할것입니다.
Receiver 클래스는 POJO 이기 때문에, receiveMessage을 발생시키기위해 명시해놓은 MessageListenerAdapter에 랩핑 되어질 필요가 있습니다. 

* JMS 대기열과 AMQP 대기열은 다른 의미를 갖습니다.
예를 들면,  JMS은 대기하고 있던 메시지들을 오직 한 consumer에게 보냅니다.
AMQP 대기열이 같은 것을 하고 있는 중에, AMQP producter들은 대기열에 직접 메시지들을 보내지 않습니다.
대신에, 메세지는 exchange에게  보내집니다. exchange는 단일 대기열로 이동하거나 여러 대기열에게 퍼질 수 있습니다. JMS topics의 컨셉을 모방합니다.
보다 자세한  이해를 위해서는 해당 링크(Understanding AMQP : https://spring.io/understanding/AMQP)을 참고하세요 

메세지 리스너 컨테이너와 리시버 빈즈는 모두 메세지를 수신하기 위해 필요한 모든 것입니다.
메세지를 보내기 위해, Rabbit template이 필요합니다.

queue() 메소드는 AMQP 대기열을 생성합니다.
exchange() 메소드는 topic exchange을 생성합니다.
bind() 메소드는 위 두개를 묶습니다, RabbitTempate이 exchange에게 게시할때 발생하는 행동들을 정의합니다.

* Spring AMQP는 Queue, TopicExchange, Binding이 적당히 셋업하기 위해 상위 레벨 Spring beans로 정의되는 것을 요구합니다.

테스트 메시지 보내기

테스트 메세지들은 CommandLineRunner에 의해 보내진다.
이건 리시버안에 latch을 기다리고 어플리케이션 컨텍스트를 닫습니다. 

package hello;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by dennis on 2017-05-11.
 */
@Component
public class Runner implements CommandLineRunner {

    private final RabbitTemplate rabbitTemplate;
    private final Receiver receiver;
    private final ConfigurableApplicationContext context;

    public Runner(Receiver receiverRabbitTemplate rabbitTemplateConfigurableApplicationContext context){
        this.receiver = receiver;
        this.rabbitTemplate = rabbitTemplate;
        this.context = context;
    }
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Sending message....");
        rabbitTemplate.convertAndSend(Application.queueName"Hello from RabbitMQ!");
        receiver.getLatch().await(1000TimeUnit.MILLISECONDS);
        context.close();
    }
}


실행가능한 JAR 빌드하기 

Gradle이나 Maven을 가지고 커맨드 창에서 어플리케이션을 실행할수 있습니다.
또는 단독 실행가능한 JAR로 빌드 할수 있습니다.
해당 JAR는 모든 필요 의존관계들, 클래스들 그리고 리소스들을 포함하고 있고, 그것 구동합니다.
개발 수명주기, 다양한 환경을 걸쳐 서비스를 어플리케이션으로 탑재, 버전 그리고 배포하는 것이 쉽게 만들어 주네요

Gradle을 사용하고 있으면, ./gradlew bootRun 을 사용해서 어플리케이션을 기동하고,
./gradlew build 을 사용해서 JAR file로 빌드 할수 있습니다.
그리고 나서 JAR 파일을 실행합니다.

java - jar target/gs-messaging-rabbitmq-0.1.0.jar

메이븐을 사용하고 있으며, ./mvnw spring-boot:run 을 사용해서, 어플리케이션을 구동할수 있으며,
./mvnw clean package 을 사용해서 JAR 파일을 빌드 할수 있습니다.
그리고 나서 , JAR 파일을 실행합니다.

java - jar target/gs-messaging-rabbitmq-0.1.0.jar

* 위의 프로시저는  실행가능한 JAR을 생성하는데, 예전 WAR 파일로 선택하여 빌드할 수 있습니다. 

자 그럼 아래와 같은 결과를 볼수 있겠습니다.


Sending message....
received < Hello from RabbitMQ!>

요약

축하드려요. 이제 막 간단한 배포-구독 어플리케이션을 Spring 과 RabbitMQ을 이용해서 개발했습니다. 
여기에 있는 것 보다 좀 더 많은 것을 Spring 과 RabbitMQ을 가지고 할수 있지만, 이것은 좋은 시작을 제시합니다.



=============================================================================================

This guide walks you through the process of setting up a RabbitMQ AMQP server that publishes and subscribes to messages.

What you'll build 
You'll build an application that publishes a message using Spring AMQP's RabbitTemplate  and subscribes to the message on a POJO using MessageListenerAdapter.

What you'll need
- About 15  minutes
- A favorite text editor or IDE
- JDK 1.8 or later
- Gradle 2.3+ or Maven 3.0+
- You can also import the code straight into your IDE:
     - Spring Tool Sute(STS)
     - IntelliJ IDEA
          - RabbitMQ server(installation instructions below)

How to complete this guide


Like most Spring Getting Started Guides, you can start from scratch and complete each step, 
or you can bypass basic setup steps that are already familiar to you.
Either way, you end up with working code.

To start from scratch, move on to Build with Gradle. 

To skip the  basics, do the following : 

 - Download and unzip the source repository for this guide, or clone it using Git:
 - cd into gs-messaging-rabbitmq/initial
 - Jump ahead to Create a RabbitMQ message receiver.

When you're finished, you can check your results against the code in  gs-messaging-rabbitmq/complete.

> Build with Gradle

First you set up a basic build script.
You can use any build system you like when building apps with Spring, but the code you need to work with Gradle and Maven is included here.
If you're not familiar with either, refer to Building Java Projects with Gradle or Building Java Projects with Maven.

Create the directory structure

In a project directory of your choosing, create the following subdirectory structure; 
for example, with  mkdir -p src/main/java/hello on *nix systems: 

└── src
    └── main
        └── java
            └── hello
Create a Gradle build file

Below  is the initial Gradle build file.

build.gradle


buildscript{
    repositories{
        mavenCentral()
    }
    dependencies{
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
    }
}
apply plugin'java'
apply plugin'intellij'
apply plygin 'idea'
apply plugin 'org.springramework.boot'

jar{
    baseName='gs-messaging-rabbitmq'
    version '0.1.0'
}

repositories{
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8


dependencies {
    compile("org.springframework.boot:spring-boot-starter-amqp")
    testCompile group'junit'name'junit'version'4.11'
}

The Spring Boot gradle plugin provides many convenient features:

- It collects all  the jars on the classpath and builds a single, runnable "uber-jar", which makes it more convenient to execute and transport your service.
- It searches for the public static void main() method to flag as a runnable class.
- It provides a built-in dependency resolver that sets the version number to match  Spring Boot dependencies.
  You can override any version you wish, but it will default to  Boot's chosen set of versions.

Set up RabbitMQ broker

Before  you can build your messaging application, you need to set up the server that will handle receiving and sending messages.
RabbitMQ is an AMQP server.
The Server is freely available at  https://www.rabbitmq.com/download.html
You can download it manually, or if you are using a Mac with homebrew : 

brew install rabbitmq

Unpack the server and launch it with default settings.

rabbitmq-server

You should see something like this: 



You can also use Docker Compose to quickly launch a RabbitMQ server if you have docker running locally.
There is a docker-compose.yml in the root of the "complete" project in Github. 
It is very simple:

docker-compose.yml

rabbitmq:
     image : rabbitmq:management
     ports:
          - "5672:5672"
          -"15672:15672"

With this file in the current directory you can run docker-compose up to get RabbitMQ running in a container


Create a RabbitMQ message receiver

with any messaging-based application, you need to create a receiver that will respond to published messages.

src/main/java/hello/Receiver.java



import org.springframework.stereotype.Component;
import java.util.concurrent.CountDownLatch;

/**
 * Created by dennis on 2017-05-10.
 */

@Component
public class Receiver {

    private CountDownLatch latch new CountDownLatch(1);

    public void receiveMessage(String message){
        System.out.println("received < " + message + ">");
        latch.countDown();
    }

    public CountDownLatch getLatch(){
        return latch;
    }
}

The Receiver is a simple POJO that defines a method for receiving messages.
When you register it to receive messages, you can name it anything you want.

* For convenience, this POJO also has a CountDownLatch. 
This allows it to signal that the message is received.
This is something you are not likely to implement in a production application.

Register the listener and send a message

Spring AMQP's RabbitTemplate provides everything you need to send and receive messages with RabbitMQ.
Specifically, you need to configure :
 - A message listener container
 - Declare the queue, the exchange, and the binding between them 
 - A component to send some messages to test the listener 

* Spring Boot automatically creates a connection factory and a RabbitTemplate, reducing the amount of code you have to write.

You'll use RabbitTemplate to send messages, and you will register a Receiver with the message listener container to receive messages.
The connection factory drives both, allowing them to connect to the RabbitMQ server.

src/main/java/hello/Application.java

package hello;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

/**
 * Created by dennis on 2017-05-10.
 */
@SpringBootApplication
public class Application {

    final static String queueName "spring-boot";

    @Bean
    Queue queue(){
        return new Queue(queueName, false);
    }

    @Bean
    TopicExchange exchange(){
        return new TopicExchange("spring-boot-exchange");
    }

    @Bean
    Binding binding(Queue queueTopicExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(queueName);
    }

    @Bean
    SimpleMessageListenerContainer container(ConnectionFactory connectionFactoryMessageListenerAdapter listenerAdapter){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setQueueNames(queueName);
        container.setMessageListener(listenerAdapter);
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver){
        return new MessageListenerAdapter(receiver,"receiveMessage");
    }

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class,args);
    }
}

@SpringBootApplication is a convenience annotation that adds all of the following : 
 - @Configuration tags the class as a source of bean definitions for the application context. 
 - @EnableAutoConfiguration tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
 - Normally you would add @EnableWebMvc for a Spring MVC app, but Spring Boot adds it automatically when it sees spring-webmvc on the classpath.
   This flags the application as a web application and activates key behaviors such as setting up a DispatcherServlet.
 - @ComponentScan tells Spring to look for other components, configurations and services in the hello package, allowing it to find the controllers.

The main() method uses Spring Boot's SpringApplication.run() method to launch an application.
Did you notice that there wasn't a single line of XML? 
No web.xml file either.
This web application is 100% pure Java and you didn't have to deal with configuring any plumbing or intrastructure.

The bean defined in the listenerAdapter() method is registered as a message listener in the container defined in container().
It will listen for messages on the "spring-boot" queue.
Because the Receiver class is a POJO, it needs to be wrapped in the MessageListenerAdapter, where you specify it to invoke receiveMessage.

* JMS queues and AMQP queues have different semantics.
 For Example, JMS sends queued messages to only one consumer.
While AMQP queues do the same thing, AMQP producers don't send messages directly to  queues.
Instead , a message is sent to an exchange, which can go to a single queue, or fanout to multiple queues, 
emulating the concept of JMS topics.
For more, see Understanding AMQP.

The message listener container and receiver beans are all you need to listen for messages.
To send a message, you also need a Rabbit template.

The queue() method creates an AMQP queue.
The exchange() method creates a topic exchange.
The binding() method binds these two together, defining the behavior that occurs when RabbitTemplate publishes to an exchange.


* Spring AMQP requires that the Queue, the TopicExchange, and the Binding be declared as top level Spring beans in order to be set up properly.

Send a Test Message

Test Messages are sent by a CommandLineRunner, which also waits for the latch in the receiver and closes the application context:


package hello;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by dennis on 2017-05-11.
 */
@Component
public class Runner implements CommandLineRunner {

    private final RabbitTemplate rabbitTemplate;
    private final Receiver receiver;
    private final ConfigurableApplicationContext context;

    public Runner(Receiver receiverRabbitTemplate rabbitTemplateConfigurableApplicationContext context){
        this.receiver = receiver;
        this.rabbitTemplate = rabbitTemplate;
        this.context = context;
    }
    @Override
    public void run(String... args) throws Exception {
        System.out.println("Sending message....");
        rabbitTemplate.convertAndSend(Application.queueName"Hello from RabbitMQ!");
        receiver.getLatch().await(1000TimeUnit.MILLISECONDS);
        context.close();
    }
}

The runner can be mocked out in tests, so that the receiver can be tested in isolation.


Run the Application

The main() method starts that process by creating a Spring application context. 
This starts the message listener container, which will start listening for messages.
There is a Runner bean which is then automatically executed: it retrieves the RabbitTemplate from the application context 
and sends a "Hello from RabbitMQ!" message on the "spring-boot" queue.
Finally, it closes the Spring application context and the application ends.


runner는 테스트상에서 목아웃되어 질수 있어서, 리시버는 독립적으로 테스트 할수 있습니다.

어플리케이션 기동

메인메소드는 Spring 어플리케이션 컨텍스트를 생성하여 프로세스를 시작합니다.
메시지 리스너 컨테이너가 시작하며, 메시지 수신을 시작합니다.
Runner 빈이 있고, 자동으로 실행됩니다 : 어플리케이션 컨텍스트로 부터 RabbitTemplate을 주고 받고, "Hello from  RabbitMQ!" 메시지를 
"Spring-boot" 대기열에 보냅니다.
마지막으로 Spring 어플리케이션 컨텍스는 닫고, 어플리케이션이 종료됩니다.


Build an executable JAR

You can run the application from the command line with Gradle or Maven.
Or you can build a single executable JAR file that contains all the necesary dependencies, classes, and resources, and run that.
This makes it easy to ship, version and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you are using Gradle, you can run the application using ./gradlew bootRun.
Or you can build the JAR file using ./gradlew build 
Then you can run the JAR file:

java -jar build/libs/gs-messaging-rabbitmq-0.1.0.jar

If you are using Maven, you can run the application using ./mvnw spring-boot:run 
Or you can build the JAR file with ./mvnw clean package .
Then you can run the JAR file:

java - jar target/gs-messaging-rabbitmq-0.1.0.jar

* The procedure above will create a runnable JAR. You can also opt to build a classic WAR file instead.

You should see the following output: 

Sending message....
received < Hello from RabbitMQ!>


Summary

Congratulation! You're just developed a simple publish-and-subscribe application with Spring and RabbitMQ.
There's more you can do with Spring and RabbitMQ than what is covered here, but this should provide a good start.

Want to write a new guide or contribute to an existing one?
Check out our contribution guidelines.

All guides are released with an ASLv2 license for the code, and an Attribution, NoDerivatives creative commons license for the writing.