연습 - Azure Service Bus에서 메시지 받기

완료됨

이제 Azure Service Bus 큐에서 메시지를 받을 수 있는 Spring Boot 애플리케이션을 만들어 보겠습니다.

Spring Boot 프로젝트 만들기

새 터미널 창을 열어 보겠습니다. 보낸 사람 Spring Boot 애플리케이션과 마찬가지로 Spring Initializr를 사용하여 Spring Boot 프로젝트를 만듭니다.

curl https://start.spring.io/starter.tgz -d type=maven-project -d dependencies=web -d baseDir=spring-receiver-application -d bootVersion=2.4.1.RELEASE -d javaVersion=1.8 | tar -xzvf -

Service Bus 큐에서 메시지 받기

여기서는 다시 종속성 및 구성을 추가합니다.

Service Bus Spring Boot 스타터에 대한 maven 종속성 추가

pom.xml 파일의 spring-receiver-application에서 종속성 아래에 다음 명령을 추가합니다.

            <dependency>
                <groupId>com.microsoft.azure</groupId>
                <artifactId>azure-servicebus-jms-spring-boot-starter</artifactId>
                <version>2.3.3</version>
            </dependency>

구성 매개 변수 추가

  1. spring-receiver-application\src\main\resources 폴더에서 application.properties 파일을 편집하고 다음 매개 변수를 추가합니다.

    server.port=9090
    
    spring.jms.servicebus.connection-string=<xxxxx>
    spring.jms.servicebus.idle-timeout=20000
    
  2. spring.jms.servicebus.connection-string 속성을 이전에 저장한 Service Bus 네임스페이스에 대한 연결 문자열로 설정합니다.

Service Bus에서 메시지를 받는 코드 추가

다음으로 Service Bus 큐에서 메시지를 수신하는 비즈니스 논리를 추가합니다.

src/main/java/com/example/demo 디렉터리에서 다음 콘텐츠가 있는 ReceiveController.java 파일을 만듭니다.

package com.example.demo;

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class ReceiveController {
    
    @JmsListener(destination = "test-queue-jms")
    public void receiveMessage(String message) {
        System.out.println("Received <" + message + ">");
    }
}

애플리케이션을 로컬로 실행

  1. pom.xml 파일이 있는 샘플 spring-receiver-application 폴더의 루트로 다시 전환하고 다음 명령을 실행하여 Spring Boot 애플리케이션을 시작합니다. 이 단계에서는 Windows 컴퓨터에 mvn을 설치했으며 PATH에 있다고 가정합니다.

    mvn spring-boot:run
    
  2. 애플리케이션 시작이 완료된 후에는 콘솔 창에 다음 로그 문이 표시됩니다.

    Received <Hello>
    Received <HelloAgain>
    Received <HelloOnceAgain>
    

    명령문의 모양은 Spring Boot 애플리케이션이 Service Bus 큐에서 메시지를 성공적으로 수신했음을 나타냅니다.

작동 중인 전체 워크플로 보기

송신기 애플리케이션(4단원)이 계속 실행되고 있는 경우 다음 링크를 선택하여 Service Bus 큐에 메시지를 보낼 수 있습니다.

http://localhost:8080/messages?message=HelloOnceAgainAndAgain

수신자 애플리케이션은 Service Bus 큐에서 메시지를 수신하고 콘솔에 표시합니다.

Received <HelloOnceAgainAndAgain>