练习 - 将消息发送到 Azure 服务总线

已完成

在本单元中,你将创建一个 Spring Boot 应用程序,用于将消息发送到 Azure 服务总线队列。 在本地完成以下步骤。

创建 Spring Boot 项目

若要创建 Spring Boot 项目,请使用 Spring Initializr 和以下命令行:

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

将消息发送到服务总线队列

现在,让我们将一些消息发送到服务总线队列。

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

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

		<!-- 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-sender-application\src\main\resources 文件夹中,编辑 application.properties 文件,添加以下参数:

    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,创建 SendController.java 包含以下内容的文件:

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SendController {
    
    private static final String queue = "test-queue-jms";

    @Autowired
    private JmsTemplate jmsTemplate;

    @GetMapping("/messages")
    public String postMessage(@RequestParam String message) {
        jmsTemplate.send(queue, s -> s.createTextMessage(message));
        return message;
    }
}

在本地运行应用程序

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

    mvn spring-boot:run
    
  2. 应用程序启动完成后,可以选择以下链接,将消息发送到服务总线队列。

    http://localhost:8080/messages?message=Hello
    
    http://localhost:8080/messages?message=HelloAgain
    
    http://localhost:8080/messages?message=HelloOnceAgain
    

    可以在消息查询参数中更改字符串值,并将任何文本发送到服务总线队列。

    浏览器将显示作为消息查询字符串参数传递的任何内容,这意味着服务总线正在接受消息。

查看服务总线队列中的消息

注释

虽然查看消息有助于了解消息的发送端,但此步骤是可选的。

在本教程的下一步中,将接收到这些消息。

可以继续在 Azure 门户中的服务总线资源管理器中查看消息:

  1. 返回 Azure 门户,在“实体”下的左侧菜单中选择“队列”。

  2. 选择相应的队列。 例如,此演示的队列是 test-queue-jms

  3. 在左窗格中,选择 “服务总线资源管理器”。

  4. 选择“从头开始速览”。 应会看到使用 HTTP 命令发送的所有三条消息。

    服务总线资源管理器速览体验的屏幕截图。

  5. 选择一条消息以查看底部窗格中的邮件正文。

    Service Bus Explorer 的屏幕截图,其中包含速览的消息。