springboot 使用MQ原生API创建生产者和消费者
时间: 2023-12-25 12:03:10 浏览: 22
使用MQ原生API创建生产者和消费者可以分为以下几个步骤:
1. 引入MQ客户端依赖
在pom.xml文件中添加如下依赖:
```
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.3</version>
</dependency>
```
2. 创建连接工厂
```java
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
```
3. 创建连接
```java
Connection connection = factory.newConnection();
```
4. 创建通道
```java
Channel channel = connection.createChannel();
```
5. 创建队列
```java
String queueName = "hello";
channel.queueDeclare(queueName, false, false, false, null);
```
6. 创建生产者
```java
String message = "Hello World!";
channel.basicPublish("", queueName, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
```
7. 创建消费者
```java
channel.basicConsume(queueName, true, (consumerTag, message) -> {
String msg = new String(message.getBody(), "UTF-8");
System.out.println("Received message: " + msg);
}, consumerTag -> {});
```
完整代码示例:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ProducerConsumerExample {
public static void main(String[] args) throws Exception {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
factory.setUsername("guest");
factory.setPassword("guest");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
String queueName = "hello";
channel.queueDeclare(queueName, false, false, false, null);
String message = "Hello World!";
channel.basicPublish("", queueName, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.basicConsume(queueName, true, (consumerTag, message) -> {
String msg = new String(message.getBody(), "UTF-8");
System.out.println("Received message: " + msg);
}, consumerTag -> {});
channel.close();
connection.close();
}
}
```