Spring 애플리케이션에서 Azure Service Bus 사용

이 문서에서는 Spring Framework로 빌드된 Java 애플리케이션에서 Azure Service Bus를 사용하는 방법을 보여 줍니다.

Azure는 AMQP 1.0(고급 메시지 큐 프로토콜 1.0) 표준을 기반으로 하는 Azure Service Bus(Service Bus)라는 비동기 메시징 플랫폼을 제공합니다. 지원되는 Azure 플랫폼 범위에서 Service Bus를 사용할 수 있습니다.

Spring Cloud Azure는 Spring 프레임워크를 사용하여 Service Bus 및 토픽/구독에서 메시지를 보내고 받기 위한 다양한 모듈을 제공합니다.

다음 모듈을 독립적으로 사용하거나 다른 사용 사례에 대해 결합할 수 있습니다.

필수 조건

참고 항목

Service Bus 리소스에 대한 액세스 권한을 계정에 부여하려면 새로 만든 Azure Service Bus 네임스페이스에서 현재 사용 중인 Microsoft Entra 계정에 Azure Service Bus Data SenderAzure Service Bus 데이터 수신기 역할을 할당합니다. 자세한 내용은 Azure Portal을 사용하여 Azure 역할 할당을 참조하십시오.

Important

이 자습서의 단계를 완료하려면 Spring Boot 버전 2.5 이상이 필요합니다.

로컬 환경 준비

이 자습서에서는 구성 및 코드에 인증 작업이 없습니다. 그러나 Azure 서비스에 연결하려면 인증이 필요합니다. 인증을 완료하려면 Azure ID 클라이언트 라이브러리를 사용해야 합니다. Spring Cloud Azure는 코드 변경 없이 자격 증명을 가져오는 데 도움이 되는 Azure ID 라이브러리를 사용합니다 DefaultAzureCredential.

DefaultAzureCredential은 여러 인증 방법을 지원하고 런타임에 사용할 방법을 결정합니다. 이 방법을 사용하면 앱이 환경별 코드를 구현하지 않고 로컬 또는 프로덕션 환경과 같은 다양한 환경에서 다양한 인증 방법을 사용할 수 있습니다. 자세한 내용은 Azure 호스팅 Java 애플리케이션 인증의 DefaultAzureCredential 섹션을 참조하세요.

Azure CLI, IntelliJ 또는 기타 방법을 사용하여 로컬 개발 환경에서 인증을 완료하려면 Java 개발 환경에서 Azure 인증을 참조 하세요. Azure 호스팅 환경에서 인증을 완료하려면 관리 ID를 사용하는 것이 좋습니다. 자세한 내용은 Azure 리소스에 대한 관리 ID란?을 참조하세요.

참고 항목

JMS API용 Azure Service Bus는 현재 지원하지 DefaultAzureCredential않습니다. Service Bus에서 Spring JMS를 사용하는 경우 이 단계를 무시합니다.

Spring Cloud Azure Service Bus Starter 사용

Spring Cloud Azure Service Bus Starter 모듈은 Spring Boot 프레임워크를 사용하여 Service Bus Java 클라이언트 라이브러리를 가져옵니다. 상호 배타적이지 않은 패턴으로 Spring Cloud Azure와 Azure SDK를 함께 사용할 수 있습니다. 따라서 Spring 애플리케이션에서 Service Bus Java 클라이언트 API를 계속 사용할 수 있습니다.

Service Bus 종속성 추가

Spring Cloud Azure Service Bus Starter 모듈을 설치하려면 pom.xml 파일에 다음 종속성을 추가합니다.

  • Spring Cloud AZURE BOM(청구서)

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.12.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    참고 항목

    Spring Boot 2.x를 사용하는 경우 버전을 .로 설정 spring-cloud-azure-dependencies 해야 합니다 4.18.0. 이 BOM(청구서)은 pom.xml 파일의 섹션에서 구성 <dependencyManagement> 해야 합니다. 이렇게 하면 모든 Spring Cloud Azure 종속성이 동일한 버전을 사용합니다. 이 BOM에 사용되는 버전에 대한 자세한 내용은 어떤 버전의 Spring Cloud Azure를 사용해야 하는지를 참조하세요.

  • Spring Cloud Azure Service Bus 아티팩트:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-servicebus</artifactId>
    </dependency>
    

메시지를 보내고 받도록 애플리케이션 코딩

이 가이드에서는 Spring 애플리케이션의 컨텍스트에서 Service Bus Java 클라이언트를 사용하는 방법을 설명합니다. 여기서는 두 가지 대안을 소개합니다. 권장되는 방법은 Spring Boot 자동 구성을 사용하고 Spring 컨텍스트에서 기본 제공 클라이언트를 사용하는 것입니다. 다른 방법은 프로그래밍 방식으로 직접 클라이언트를 빌드하는 것입니다.

Spring IoC 컨테이너에서 클라이언트 빈을 자동으로 배선하는 첫 번째 방법은 두 번째 방법과 비교할 때 다음과 같은 이점이 있습니다. 이러한 이점은 Service Bus 클라이언트를 사용하여 개발할 때 보다 유연하고 효율적인 환경을 제공합니다.

  • 다른 환경에서 동일한 애플리케이션 코드를 사용할 수 있도록 외부화된 구성을 사용할 수 있습니다.

  • 작성기 패턴을 학습하고 이 클라이언트를 애플리케이션 컨텍스트에 Spring Boot 프레임워크에 등록하는 프로세스를 위임할 수 있습니다. 이 위임을 사용하면 고유한 비즈니스 요구 사항으로 클라이언트를 사용하는 방법에 집중할 수 있습니다.

  • 상태 표시기를 사용하여 애플리케이션 및 내부 구성 요소의 상태 및 상태를 쉽게 검사할 수 있습니다.

다음 코드 예제에서는 이러한 두 가지 대안을 사용하는 ServiceBusSenderClientServiceBusProcessorClient 방법을 보여 줍니다.

참고 항목

Service Bus용 Azure Java SDK는 Service Bus와 상호 작용할 수 있는 여러 클라이언트를 제공합니다. 또한 시작은 모든 Service Bus 클라이언트 및 클라이언트 빌더에 대한 자동 구성을 제공합니다. 여기서는 예제로만 ServiceBusSenderClientServiceBusProcessorClient 사용합니다.

Spring Boot 자동 구성 사용

Service Bus에 메시지를 보내고 메시지를 받으려면 다음 단계를 사용하여 애플리케이션을 구성합니다.

  1. 다음 예제와 같이 Service Bus 네임스페이스 및 큐를 구성합니다.

    spring.cloud.azure.servicebus.namespace=<your-servicebus-namespace-name>
    spring.cloud.azure.servicebus.entity-name=<your-servicebus-queue-name>
    spring.cloud.azure.servicebus.entity-type=queue
    

    여기서는 Service Bus 큐를 예로 사용합니다. 토픽/구독을 사용하려면 속성을 추가하고 spring.cloud.azure.servicebus.processor.subscription-name 값을 .로 변경 entity-type 해야 합니다 topic.

  2. 다음 예제와 같이 새 ServiceBusProcessorClientConfiguration Java 클래스를 만듭니다. 이 클래스는 의 메시지 및 오류 처리기를 ServiceBusProcessorClient등록하는 데 사용됩니다.

    @Configuration(proxyBeanMethods = false)
    public class ServiceBusProcessorClientConfiguration {
    
        @Bean
        ServiceBusRecordMessageListener processMessage() {
            return context -> {
                ServiceBusReceivedMessage message = context.getMessage();
                System.out.printf("Processing message. Id: %s, Sequence #: %s. Contents: %s%n", message.getMessageId(),
                        message.getSequenceNumber(), message.getBody());
            };
        }
    
        @Bean
        ServiceBusErrorHandler processError() {
            return context -> {
                System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n",
                        context.getFullyQualifiedNamespace(), context.getEntityPath());
            };
        }
    }
    
  3. ServiceBusSenderClient 다음 예제와 같이 Spring 애플리케이션에 삽입하고 관련 API를 호출하여 메시지를 보냅니다.

    @SpringBootApplication
    public class ServiceBusQueueApplication implements CommandLineRunner {
    
        private final ServiceBusSenderClient senderClient;
    
        public ServiceBusQueueApplication(ServiceBusSenderClient senderClient) {
            this.senderClient = senderClient;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceBusQueueApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            // send one message to the queue
            senderClient.sendMessage(new ServiceBusMessage("Hello, World!"));
            System.out.printf("Sent a message to the queue");
            senderClient.close();
    
            // wait the processor client to consume messages
            TimeUnit.SECONDS.sleep(10);
        }
    
    }
    

    참고 항목

    기본적으로 자동 배선된 ServiceBusProcessorClient 콩의 수명 주기는 Spring 컨텍스트에서 관리됩니다. 프로세서는 Spring 애플리케이션 컨텍스트가 시작될 때 자동으로 시작되고 Spring 애플리케이션 컨텍스트가 중지될 때 중지됩니다. 이 기능을 사용하지 않도록 설정하려면 .를 구성합니다 spring.cloud.azure.servicebus.processor.auto-startup=false.

  4. 애플리케이션을 시작합니다. 다음 예제와 유사한 로그가 표시됩니다.

    Sent a message to the queue
    Processing message. Id: 6f405435200047069a3caf80893a80bc, Sequence #: 1. Contents: Hello, World!
    

프로그래밍 방식으로 Service Bus 클라이언트 빌드

이러한 클라이언트 콩을 직접 빌드할 수 있지만 프로세스는 복잡합니다. Spring Boot 애플리케이션에서는 속성을 관리하고, 작성기 패턴을 알아보고, Spring 애플리케이션 컨텍스트에 클라이언트를 등록해야 합니다. 다음 코드 예제에서는 이 작업을 수행하는 방법을 보여줍니다.

  1. 다음 예제와 같이 새 ServiceBusClientConfiguration Java 클래스를 만듭니다. 이 클래스는 콩과 ServiceBusProcessorClient 콩을 선언하는 ServiceBusSenderClient 데 사용됩니다.

    @Configuration(proxyBeanMethods = false)
    public class ServiceBusClientConfiguration {
    
        private static final String SERVICE_BUS_FQDN = "<service-bus-fully-qualified-namespace>";
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        @Bean
        ServiceBusClientBuilder serviceBusClientBuilder() {
            return new ServiceBusClientBuilder()
                       .fullyQualifiedNamespace(SERVICE_BUS_FQDN)
                       .credential(new DefaultAzureCredentialBuilder().build());
        }
    
        @Bean
        ServiceBusSenderClient serviceBusSenderClient(ServiceBusClientBuilder builder) {
            return builder
                   .sender()
                   .queueName(QUEUE_NAME)
                   .buildClient();
        }
    
        @Bean
        ServiceBusProcessorClient serviceBusProcessorClient(ServiceBusClientBuilder builder) {
            return builder.processor()
                          .queueName(QUEUE_NAME)
                          .processMessage(ServiceBusClientConfiguration::processMessage)
                          .processError(ServiceBusClientConfiguration::processError)
                          .buildProcessorClient();
        }
    
        private static void processMessage(ServiceBusReceivedMessageContext context) {
            ServiceBusReceivedMessage message = context.getMessage();
            System.out.printf("Processing message. Id: %s, Sequence #: %s. Contents: %s%n",
                message.getMessageId(), message.getSequenceNumber(), message.getBody());
        }
    
        private static void processError(ServiceBusErrorContext context) {
            System.out.printf("Error when receiving messages from namespace: '%s'. Entity: '%s'%n",
                    context.getFullyQualifiedNamespace(), context.getEntityPath());
        }
    }
    

    참고 항목

    자리 표시자를 Azure Portal의 <service-bus-fully-qualified-namespace> Service Bus 호스트 이름으로 바꿔야 합니다. <service-bus-queue-name> 자리 표시자를 Service Bus 네임스페이스에 구성된 고유한 큐 이름으로 바꿉니다.

  2. 다음 예제와 같이 클라이언트 빈을 애플리케이션에 삽입합니다.

    @SpringBootApplication
    public class ServiceBusQueueApplication implements CommandLineRunner {
    
        private final ServiceBusSenderClient senderClient;
    
        private final ServiceBusProcessorClient processorClient;
    
        public ServiceBusQueueApplication(ServiceBusSenderClient senderClient, ServiceBusProcessorClient processorClient) {
            this.senderClient = senderClient;
            this.processorClient = processorClient;
        }
    
        public static void main(String[] args) {
            SpringApplication.run(ServiceBusQueueApplication.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            // send one message to the queue
            senderClient.sendMessage(new ServiceBusMessage("Hello, World!"));
            System.out.printf("Sent a message to the queue");
            senderClient.close();
    
            System.out.printf("Starting the processor");
            processorClient.start();
            TimeUnit.SECONDS.sleep(10);
            System.out.printf("Stopping and closing the processor");
            processorClient.close();
        }
    
    }
    
  3. 애플리케이션을 시작합니다. 다음 예제와 유사한 로그가 표시됩니다.

    Sent a message to the queue
    Starting the processor
    ...
    Processing message. Id: 6f405435200047069a3caf80893a80bc, Sequence #: 1. Contents: Hello, World!
    Stopping and closing the processor
    

다음 목록에서는 이 코드가 유연하지 않거나 정상적이지 않은 이유를 보여 줍니다.

  • 네임스페이스 및 큐/토픽/구독 이름은 하드 코딩됩니다.
  • Spring 환경에서 구성을 가져오는 데 사용하는 @Value 경우 application.properties 파일에 IDE 힌트를 가질 수 없습니다.
  • 마이크로 서비스 시나리오가 있는 경우 각 프로젝트에서 코드를 복제해야 하며 실수를 하기 쉽고 일관성을 갖기 어렵습니다.

다행히 Spring Cloud Azure에서는 클라이언트 빈을 직접 빌드할 필요가 없습니다. 대신, 빈을 직접 주입하고 이미 익숙한 구성 속성을 사용하여 Service Bus를 구성할 수 있습니다.

또한 Spring Cloud Azure는 다양한 시나리오에 대해 다음과 같은 글로벌 구성을 제공합니다. 자세한 내용은 Spring Cloud Azure 구성의 Azure 서비스 SDK에 대한 전역 구성 섹션을 참조하세요.

  • 프록시 옵션입니다.
  • 다시 시도 옵션입니다.
  • AMQP 전송 클라이언트 옵션입니다.

다른 Azure 클라우드에 연결할 수도 있습니다. 자세한 내용은 다른 Azure 클라우드에 대한 커넥트 참조하세요.

Spring Cloud Azure Service Bus JMS Starter 사용

Spring Cloud Azure Service Bus JMS Starter 모듈은 Service Bus와 Spring JMS 통합을 제공합니다. 다음 비디오에서는 JMS 2.0을 사용하여 Spring JMS 애플리케이션을 Azure Service Bus와 통합하는 방법을 설명합니다.


이 가이드에서는 JMS API용 Spring Cloud Azure Service Bus Starter를 사용하여 Service Bus에 메시지를 보내고 받는 방법을 보여 줍니다.

Service Bus 종속성 추가

Spring Cloud Azure Service Bus JMS Starter 모듈을 설치하려면 pom.xml 파일에 다음 종속성을 추가합니다.

  • Spring Cloud AZURE BOM(청구서)

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.12.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    참고 항목

    Spring Boot 2.x를 사용하는 경우 버전을 .로 설정 spring-cloud-azure-dependencies 해야 합니다 4.18.0. 이 BOM(청구서)은 pom.xml 파일의 섹션에서 구성 <dependencyManagement> 해야 합니다. 이렇게 하면 모든 Spring Cloud Azure 종속성이 동일한 버전을 사용합니다. 이 BOM에 사용되는 버전에 대한 자세한 내용은 어떤 버전의 Spring Cloud Azure를 사용해야 하는지를 참조하세요.

  • Spring Cloud Azure Service Bus JMS 아티팩트:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-servicebus-jms</artifactId>
    </dependency>
    

메시지를 보내고 받도록 애플리케이션 코딩

  1. 다음 예제와 같이 Service Bus에 대한 연결 문자열 및 가격 책정 계층을 구성합니다.

    spring.jms.servicebus.connection-string=<service-bus-namespace-connection-string>
    spring.jms.servicebus.pricing-tier=<service-bus-pricing-tier>
    
  2. 메시지 수신기를 만듭니다.

    Spring은 POJO(일반 이전 Java 개체)에 메시지를 게시하는 수단을 제공합니다. 먼저 다음 예제와 같이 사용자의 이름을 저장하고 검색하는 제네릭 User 클래스를 정의합니다.

    public class User implements Serializable {
    
        private static final long serialVersionUID = -295422703255886286L;
    
        private String name;
    
        public User() {
        }
    
        public User(String name) {
            setName(name);
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }
    

    Serializable는 Spring 프레임워크에서 JmsTemplate 메서드를 send 사용하도록 구현됩니다. 그렇지 않으면 콘텐츠를 텍스트 형식으로 JSON으로 직렬화하도록 사용자 지정된 MessageConverter 콩을 정의해야 합니다. 자세한 내용은 MessageConverter공식 Spring JMS 시작 프로젝트를 참조하세요.

  3. 여기에서 다음 예제와 같이 새 QueueReceiveService Java 클래스를 만들 수 있습니다. 이 클래스는 메시지 수신자를 정의하는 데 사용됩니다.

    @Component
    public class QueueReceiveService {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        @JmsListener(destination = QUEUE_NAME, containerFactory = "jmsListenerContainerFactory")
        public void receiveMessage(User user) {
            System.out.printf("Received a message from %s.", user.getName());
        }
    }
    

    참고 항목

    자리 표시자를 Service Bus 네임스페이 <service-bus-queue-name> 스에 구성된 고유한 큐 이름으로 바꿔야 합니다.

    토픽/구독을 사용하는 경우 매개 변수를 destination 토픽 이름으로 변경합니다 containerFactorytopicJmsListenerContainerFactory. 또한 구독 이름을 설명하는 매개 변수를 추가 subscription 합니다.

  4. 다음 예제와 같이 보낸 사람과 수신자를 연결하여 Spring을 사용하여 메시지를 보내고 받습니다.

    @SpringBootApplication
    @EnableJms
    public class ServiceBusJmsStarterApplication {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        public static void main(String[] args) {
            ConfigurableApplicationContext context = SpringApplication.run(ServiceBusJMSQueueApplication.class, args);
            JmsTemplate jmsTemplate = context.getBean(JmsTemplate.class);
    
            // Send a message with a POJO - the template reuse the message converter
            System.out.println("Sending a user message.");
            jmsTemplate.convertAndSend(QUEUE_NAME, new User("Tom"));
        }
    }
    

    참고 항목

    자리 표시자를 Service Bus 네임스페이 <service-bus-queue-name> 스에 구성된 고유한 큐 이름으로 바꿔야 합니다.

    주석을 추가하여 주석으로 @EnableIntegration 주석이 추가된 @JmsListener메서드의 검색을 트리거하고 메시지 수신기 컨테이너를 숨깁니다.

  5. 애플리케이션을 시작합니다. 다음 예제와 유사한 로그가 표시됩니다.

    Sending a user message.
    Received a message from Tom.
    

기타 정보

자세한 내용은 Service Bus 및 AMQP 1.0에서 JMS API를 사용하는 방법을 참조 하세요.

Spring Messaging Azure Service Bus 사용

Spring Messaging Azure Service Bus 모듈은 Service Bus를 사용하여 Spring Messaging 프레임워크를 지원합니다.

Spring Messaging Azure Service Bus를 사용하는 경우 다음 기능을 사용할 수 있습니다.

  • ServiceBusTemplate: 메시지를 Service Bus 큐 및 토픽에 비동기적으로 동기적으로 보냅니다.
  • @ServiceBusListener: 대상에서 Service Bus 메시지 수신기의 대상으로 메서드를 표시합니다.

이 가이드에서는 Spring Messaging Azure Service Bus를 사용하여 Service Bus에 메시지를 보내고 받는 방법을 보여줍니다.

Service Bus 종속성 추가

Spring Messaging Azure Service Bus 모듈을 설치하려면 pom.xml 파일에 다음 종속성을 추가합니다.

  • Spring Cloud AZURE BOM(청구서)

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.12.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    참고 항목

    Spring Boot 2.x를 사용하는 경우 버전을 .로 설정 spring-cloud-azure-dependencies 해야 합니다 4.18.0. 이 BOM(청구서)은 pom.xml 파일의 섹션에서 구성 <dependencyManagement> 해야 합니다. 이렇게 하면 모든 Spring Cloud Azure 종속성이 동일한 버전을 사용합니다. 이 BOM에 사용되는 버전에 대한 자세한 내용은 어떤 버전의 Spring Cloud Azure를 사용해야 하는지를 참조하세요.

  • Spring Messaging Service Bus 및 Spring Cloud Azure 시작 아티팩트:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter</artifactId>
    </dependency>
    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-messaging-azure-servicebus</artifactId>
    </dependency>
    

메시지를 보내고 받도록 애플리케이션 코딩

  1. 다음 예제와 같이 Service Bus에 대한 네임스페이스 및 큐 유형을 구성합니다.

    spring.cloud.azure.servicebus.namespace=<service-bus-namespace-name>
    spring.cloud.azure.servicebus.entity-type=queue
    

    참고 항목

    토픽/구독을 사용하는 경우 값을 topic.로 변경 spring.cloud.azure.servicebus.entity-type 합니다.

  2. 다음 예제와 같이 새 ConsumerService Java 클래스를 만듭니다. 이 클래스는 메시지 수신자를 정의하는 데 사용됩니다.

    @Service
    public class ConsumerService {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        @ServiceBusListener(destination = QUEUE_NAME)
        public void handleMessageFromServiceBus(String message) {
            System.out.printf("Consume message: %s%n", message);
        }
    
    }
    

    참고 항목

    토픽/구독을 사용하는 경우 토픽 이름으로 주석 매개 변수 destination 를 변경하고 구독 이름을 설명하는 매개 변수를 추가 subscription 합니다.

  3. 다음 예제와 같이 보낸 사람과 수신자를 연결하여 Spring을 사용하여 메시지를 보내고 받습니다.

    @SpringBootApplication
    @EnableAzureMessaging
    public class Application {
    
        private static final String QUEUE_NAME = "<service-bus-queue-name>";
    
        public static void main(String[] args) {
            ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class);
            ServiceBusTemplate serviceBusTemplate = applicationContext.getBean(ServiceBusTemplate.class);
            System.out.println("Sending a message to the queue.");
            serviceBusTemplate.sendAsync(QUEUE_NAME, MessageBuilder.withPayload("Hello world").build()).subscribe();
        }
    }
    

    주석을 추가하여 주석으로 @EnableAzureMessaging 주석이 추가된 @ServiceBusListener메서드의 검색을 트리거하고 메시지 수신기 컨테이너를 숨깁니다.

  4. 애플리케이션을 시작합니다. 다음 예제와 유사한 로그가 표시됩니다.

    Sending a message to the queue.
    Consume message: Hello world.
    

Spring Integration Azure Service Bus 사용

Spring Integration Azure Service Bus 모듈은 Service Bus 를 사용하여 Spring Integration 프레임워크를 지원합니다.

Spring 애플리케이션에서 Spring Integration 메시지 채널을 사용하는 경우 채널 어댑터를 사용하여 메시지 채널과 Service Bus 간에 메시지를 라우팅할 수 있습니다.

인바운드 채널 어댑터는 Service Bus 큐 또는 구독에서 메시지 채널로 메시지를 전달합니다. 아웃바운드 채널 어댑터는 메시지 채널의 메시지를 Service Bus 큐 및 토픽에 게시합니다.

이 가이드에서는 Spring Integration Azure Service Bus를 사용하여 Service Bus에 메시지를 보내고 메시지를 받는 방법을 보여줍니다.

Service Bus 종속성 추가

Spring Cloud Azure Service Bus Integration Starter 모듈을 설치하려면 pom.xml 파일에 다음 종속성을 추가합니다.

  • Spring Cloud AZURE BOM(청구서)

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.12.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    참고 항목

    Spring Boot 2.x를 사용하는 경우 버전을 .로 설정 spring-cloud-azure-dependencies 해야 합니다 4.18.0. 이 BOM(청구서)은 pom.xml 파일의 섹션에서 구성 <dependencyManagement> 해야 합니다. 이렇게 하면 모든 Spring Cloud Azure 종속성이 동일한 버전을 사용합니다. 이 BOM에 사용되는 버전에 대한 자세한 내용은 어떤 버전의 Spring Cloud Azure를 사용해야 하는지를 참조하세요.

  • Spring Cloud Azure Service Bus 통합 아티팩트:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-starter-integration-servicebus</artifactId>
    </dependency>
    

메시지를 보내고 받도록 애플리케이션 코딩

  1. 다음 예제와 같이 Service Bus의 네임스페이스를 구성합니다.

    spring.cloud.azure.servicebus.namespace=<your-servicebus-namespace-name>
    
  2. 다음 예제와 같이 새 QueueReceiveConfiguration Java 클래스를 만듭니다. 이 클래스는 메시지 수신자를 정의하는 데 사용됩니다.

    @Configuration
    public class QueueReceiveConfiguration {
    
        private static final String INPUT_CHANNEL = "queue.input";
        private static final String QUEUE_NAME = "<your-servicebus-queue-name>";
        private static final String SERVICE_BUS_MESSAGE_LISTENER_CONTAINER = "queue-listener-container";
    
        /**
         * This message receiver binding with {@link ServiceBusInboundChannelAdapter}
         * via {@link MessageChannel} has name {@value INPUT_CHANNEL}
         */
        @ServiceActivator(inputChannel = INPUT_CHANNEL)
        public void messageReceiver(byte[] payload) {
            String message = new String(payload);
            System.out.printf("New message received: '%s'%n", message);
        }
    
        @Bean(SERVICE_BUS_MESSAGE_LISTENER_CONTAINER)
        public ServiceBusMessageListenerContainer messageListenerContainer(ServiceBusProcessorFactory processorFactory) {
            ServiceBusContainerProperties containerProperties = new ServiceBusContainerProperties();
            containerProperties.setEntityName(QUEUE_NAME);
            return new ServiceBusMessageListenerContainer(processorFactory, containerProperties);
        }
    
        @Bean
        public ServiceBusInboundChannelAdapter queueMessageChannelAdapter(
            @Qualifier(INPUT_CHANNEL) MessageChannel inputChannel,
            @Qualifier(SERVICE_BUS_MESSAGE_LISTENER_CONTAINER) ServiceBusMessageListenerContainer listenerContainer) {
            ServiceBusInboundChannelAdapter adapter = new ServiceBusInboundChannelAdapter(listenerContainer);
            adapter.setOutputChannel(inputChannel);
            return adapter;
        }
    
        @Bean(name = INPUT_CHANNEL)
        public MessageChannel input() {
            return new DirectChannel();
        }
    }
    
  3. 다음 예제와 같이 새 QueueSendConfiguration Java 클래스를 만듭니다. 이 클래스는 메시지 발신자를 정의하는 데 사용됩니다.

    @Configuration
    public class QueueSendConfiguration {
    
        private static final String OUTPUT_CHANNEL = "queue.output";
        private static final String QUEUE_NAME = "<your-servicebus-queue-name>";
    
        @Bean
        @ServiceActivator(inputChannel = OUTPUT_CHANNEL)
        public MessageHandler queueMessageSender(ServiceBusTemplate serviceBusTemplate) {
            serviceBusTemplate.setDefaultEntityType(ServiceBusEntityType.QUEUE);
            DefaultMessageHandler handler = new DefaultMessageHandler(QUEUE_NAME, serviceBusTemplate);
            handler.setSendCallback(new ListenableFutureCallback<Void>() {
                @Override
                public void onSuccess(Void result) {
                    System.out.println("Message was sent successfully.");
                }
    
                @Override
                public void onFailure(Throwable ex) {
                    System.out.println("There was an error sending the message.");
                }
            });
    
            return handler;
        }
    
        /**
         * Message gateway binding with {@link MessageHandler}
         * via {@link MessageChannel} has name {@value OUTPUT_CHANNEL}
         */
        @MessagingGateway(defaultRequestChannel = OUTPUT_CHANNEL)
        public interface QueueOutboundGateway {
            void send(String text);
        }
    }
    
  4. 다음 예제와 같이 보낸 사람과 수신자를 연결하여 Spring을 사용하여 메시지를 보내고 받습니다.

    @SpringBootApplication
    @EnableIntegration
    @Configuration(proxyBeanMethods = false)
    public class ServiceBusIntegrationApplication {
    
        public static void main(String[] args) {
            ConfigurableApplicationContext applicationContext = SpringApplication.run(ServiceBusIntegrationApplication.class, args);
            QueueSendConfiguration.QueueOutboundGateway outboundGateway = applicationContext.getBean(QueueSendConfiguration.QueueOutboundGateway.class);
            System.out.println("Sending a message to the queue");
            outboundGateway.send("Hello World");
        }
    
    }
    

    Spring Integration 인프라를 @EnableIntegration 사용하도록 설정하는 주석을 추가해야 합니다.

  5. 애플리케이션을 시작합니다. 다음 예제와 유사한 로그가 표시됩니다.

    Message was sent successfully.
    New message received: 'Hello World'
    

Spring Cloud Stream Service Bus 바인더 사용

Spring Cloud Stream 애플리케이션에서 Service Bus API를 호출하려면 Spring Cloud Azure Service Bus Stream Binder 모듈을 사용합니다.

이 가이드에서는 Spring Cloud Stream Service Bus 바인더를 사용하여 Service Bus에 메시지를 보내고 메시지를 받는 방법을 보여줍니다.

Service Bus 종속성 추가

Spring Cloud Azure Service Bus Stream Binder 모듈을 설치하려면 pom.xml 파일에 다음 종속성을 추가합니다.

  • Spring Cloud AZURE BOM(청구서)

    <dependencyManagement>
       <dependencies>
         <dependency>
           <groupId>com.azure.spring</groupId>
           <artifactId>spring-cloud-azure-dependencies</artifactId>
           <version>5.12.0</version>
           <type>pom</type>
           <scope>import</scope>
           </dependency>
       </dependencies>
    </dependencyManagement>
    

    참고 항목

    Spring Boot 2.x를 사용하는 경우 버전을 .로 설정 spring-cloud-azure-dependencies 해야 합니다 4.18.0. 이 BOM(청구서)은 pom.xml 파일의 섹션에서 구성 <dependencyManagement> 해야 합니다. 이렇게 하면 모든 Spring Cloud Azure 종속성이 동일한 버전을 사용합니다. 이 BOM에 사용되는 버전에 대한 자세한 내용은 어떤 버전의 Spring Cloud Azure를 사용해야 하는지를 참조하세요.

  • Spring Cloud Azure Service Bus 통합 아티팩트:

    <dependency>
      <groupId>com.azure.spring</groupId>
      <artifactId>spring-cloud-azure-stream-binder-servicebus</artifactId>
    </dependency>
    

메시지를 보내고 받도록 애플리케이션 코딩

  1. 다음 예제와 같이 Service Bus의 네임스페이스를 구성합니다.

    spring.cloud.azure.servicebus.namespace=<service-bus-namespace-name>
    
  2. 메시지 수신기를 만듭니다.

    애플리케이션을 이벤트 싱크로 사용하려면 다음 정보를 지정하여 입력 바인더를 구성합니다.

    • Consumer 메시지 처리 논리를 정의하는 빈을 선언합니다. 예를 들어 다음 콩의 이름은 consume다음과 같습니다Consumer.

      @Bean
      public Consumer<Message<String>> consume() {
          return message -> {
              System.out.printf("New message received: '%s'.%n", message.getPayload());
          };
      }
      
    • 다음 예제와 같이 자리 표시자를 바꿔 <service-bus-queue-name> 서 사용할 이름을 지정 queue 하는 구성을 추가합니다.

      # name for the `Consumer` bean
      spring.cloud.function.definition=consume
      spring.cloud.stream.bindings.consume-in-0.destination=<service-bus-queue-name>
      

      참고 항목

      Service Bus 구독에서 사용하려면 다음 예제와 같이 바인딩 속성을 변경 consume-in-0 해야 합니다.

      spring.cloud.stream.bindings.consume-in-0.destination=<service-bus-topic-name>
      spring.cloud.stream.bindings.consume-in-0.group=<service-bus-subscription-name>
      
  3. 메시지 발신자를 만듭니다.

    애플리케이션을 이벤트 원본으로 사용하려면 다음 정보를 지정하여 출력 바인더를 구성합니다.

    • Supplier 애플리케이션 내에서 메시지가 들어오는 위치를 정의하는 빈을 정의합니다.

      @Bean
      return () -> {
              System.out.println("Sending a message.");
              return MessageBuilder.withPayload("Hello world").build();
          };
      }
      
    • 다음 예제에서 자리 표시자를 바꿔 <your-servicebus-queue-name> 서 보내는 이름을 지정 queue 하는 구성을 추가합니다.

      # "consume" is added from the previous step
      spring.cloud.function.definition=consume;supply
      spring.cloud.stream.bindings.supply-out-0.destination=<your-servicebus-queue-name>
      spring.cloud.stream.servicebus.bindings.supply-out-0.producer.entity-type=queue
      

      참고 항목

      Service Bus 토픽으로 보내려면 다음으로 변경 entity-type 해야 합니다 topic.

  4. 애플리케이션을 시작합니다. 다음 예제와 유사한 로그가 표시됩니다.

    Sending a message.
    New message received: 'Hello world'.
    

Azure Spring Apps에 배포

이제 Spring Boot 애플리케이션을 로컬로 실행했으므로 이제 프로덕션으로 이동해야 합니다. Azure Spring Apps 를 사용하면 코드를 변경하지 않고도 Spring Boot 애플리케이션을 Azure에 쉽게 배포할 수 있습니다. 이 서비스는 개발자가 코드에 집중할 수 있도록 Spring 애플리케이션의 인프라를 관리합니다. Azure Spring Apps는 포괄적인 모니터링 및 진단, 구성 관리, 서비스 검색, CI/CD 통합, 파란색-녹색 배포 등을 사용하여 수명 주기 관리를 제공합니다. Azure Spring Apps에 애플리케이션을 배포하려면 Azure Spring Apps에 첫 번째 애플리케이션 배포를 참조하세요.

다음 단계

참고 항목

Microsoft Azure 에 사용할 수 있는 더 많은 Spring Boot Starter에 대한 자세한 내용은 Spring Cloud Azure란?