练习 - 将消息发送到 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-application
的 pom.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>
添加配置参数
在
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
将
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;
}
}
在本地运行应用程序
切换回文件所在的
pom.xml
示例spring-sender-application
文件夹的根目录,并运行以下命令来启动 Spring Boot 应用程序。 此步骤假定你已安装mvn
在 Windows 计算机上,并且它位于PATH
其中。mvn spring-boot:run
应用程序启动完成后,可以选择以下链接,将消息发送到服务总线队列。
http://localhost:8080/messages?message=Hello
http://localhost:8080/messages?message=HelloAgain
http://localhost:8080/messages?message=HelloOnceAgain
可以在消息查询参数中更改字符串值,并将任何文本发送到服务总线队列。
浏览器将显示作为消息查询字符串参数传递的任何内容,这意味着服务总线正在接受消息。
查看服务总线队列中的消息
注释
虽然查看消息有助于了解消息的发送端,但此步骤是可选的。
在本教程的下一步中,将接收到这些消息。
可以继续在 Azure 门户中的服务总线资源管理器中查看消息: