练习 - 从 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=2.4.1.RELEASE -d javaVersion=1.8 | tar -xzvf -

从服务总线队列接收消息

现在,我们将再次添加依赖项和配置。

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

spring-receiver-applicationpom.xml 文件中,在依赖项下添加以下命令:

            <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 属性设置为前面保存的服务总线命名空间的连接字符串。

添加用于从服务总线接收消息的代码

接下来,我们将添加用于从服务总线队列接收消息的业务逻辑。

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 应用程序将成功从服务总线队列收到消息。

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

如果作为发送方的应用程序(见第 4 单元)仍在运行,你可选择以下链接向服务总线队列发送消息:

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

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

Received <HelloOnceAgainAndAgain>