springboot 发送quenen
时间: 2023-10-19 16:18:06 浏览: 34
可以使用 Spring Boot 提供的 JMS(Java Message Service)支持来发送消息到队列。以下是一个简单的示例:
1. 添加 JMS 依赖
在 pom.xml 文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
```
2. 配置 ActiveMQ 连接
在 application.properties 文件中添加以下配置:
```properties
spring.activemq.broker-url=tcp://localhost:61616
spring.activemq.user=admin
spring.activemq.password=admin
```
3. 创建消息生产者
```java
import javax.jms.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;
@Component
public class MessageProducer {
@Autowired
private JmsTemplate jmsTemplate;
@Autowired
private Queue queue;
public void sendMessage(String message) {
jmsTemplate.convertAndSend(queue, message);
}
}
```
4. 创建消息队列
```java
import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.jms.Queue;
@Configuration
public class JmsConfig {
@Bean
public Queue queue() {
return new ActiveMQQueue("test.queue");
}
}
```
5. 发送消息
在需要发送消息的地方调用 `sendMessage` 方法:
```java
@Autowired
private MessageProducer messageProducer;
messageProducer.sendMessage("Hello, World!");
```
以上就是使用 Spring Boot 发送消息到队列的基本步骤。