练习 - 从 Azure 服务总线接收消息

已完成

现在,让我们创建一个 Spring Boot 应用程序,该应用程序可以从 Azure 服务总线队列接收消息。

创建 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=3.3.0.RELEASE -d javaVersion=1.8 | tar -xzvf -

从服务总线队列接收消息

在这里,我们再次添加依赖项和配置。

为服务总线 Spring Boot Starter 添加 maven 依赖项

pom.xmlspring-receiver-application 文件中,在依赖项下添加以下命令:

		<!-- https://mvnrepository.com/artifact/com.azure.spring/spring-cloud-azure-starter-servicebus-jms -->
		<dependency>
		    <groupId>com.azure.spring</groupId>
		    <artifactId>spring-cloud-azure-starter-servicebus-jms</artifactId>
		    <version>5.18.0</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
    spring.jms.servicebus.pricing-tier=premium
    
  2. spring.jms.servicebus.connection-string 属性设置为前面保存的服务总线命名空间的连接字符串。

添加代码以从服务总线接收消息

接下来,添加业务逻辑以从服务总线队列接收消息。

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. 切换回文件所在的spring-receiver-application示例pom.xml文件夹的根目录,并运行以下命令来启动 Spring Boot 应用程序。 此步骤假定你已安装 mvn 在 Windows 计算机上,并且它位于 PATH其中。

    mvn spring-boot:run
    
  2. 应用程序启动完成后,控制台窗口中会显示以下日志语句。

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

    这些语句的出现表明 Spring Boot 应用程序已成功从 Service Bus 队列接收消息。

查看整个工作流的运行情况

如果发送方应用程序(从第 4 单元)仍在运行,则可以选择以下链接,将消息发送到服务总线队列:

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

接收方应用程序从服务总线队列接收消息,并将其显示在控制台中。

Received <HelloOnceAgainAndAgain>