帮我写个rabbitmq 常用的java工具类
时间: 2023-06-13 09:04:41 浏览: 98
好的,下面是一个 RabbitMQ 常用的 Java 工具类示例:
```java
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.MessageProperties;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class RabbitMQUtil {
// RabbitMQ 服务器地址
private static final String HOST = "localhost";
// RabbitMQ 服务器端口号
private static final int PORT = 5672;
// RabbitMQ 用户名
private static final String USERNAME = "guest";
// RabbitMQ 密码
private static final String PASSWORD = "guest";
// RabbitMQ 默认交换机名称
private static final String DEFAULT_EXCHANGE_NAME = "";
// RabbitMQ 默认队列名称
private static final String DEFAULT_QUEUE_NAME = "default_queue";
private static ConnectionFactory connectionFactory = new ConnectionFactory();
static {
// 设置 RabbitMQ 服务器地址、端口号、用户名和密码
connectionFactory.setHost(HOST);
connectionFactory.setPort(PORT);
connectionFactory.setUsername(USERNAME);
connectionFactory.setPassword(PASSWORD);
}
/**
* 发送消息到指定队列
*
* @param queueName 队列名称
* @param message 消息内容
*/
public static void sendMessage(String queueName, String message) throws IOException, TimeoutException {
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(queueName, true, false, false, null);
// 发送消息到队列中
channel.basicPublish(DEFAULT_EXCHANGE_NAME, queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
channel.close();
connection.close();
}
/**
* 从指定队列中接收消息
*
* @param queueName 队列名称
* @return 接收到的消息内容
*/
public static String receiveMessage(String queueName) throws IOException, TimeoutException {
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
// 声明队列
channel.queueDeclare(queueName, true, false, false, null);
// 从队列中接收消息
channel.basicQos(1);
String message = null;
// 开启手动确认模式
channel.basicConsume(queueName, false, (consumerTag, delivery) -> {
message = new String(delivery.getBody(), "UTF-8");
// 手动确认消息已被接收
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}, consumerTag -> {
});
channel.close();
connection.close();
return message;
}
/**
* 删除指定队列
*
* @param queueName 队列名称
*/
public static void deleteQueue(String queueName) throws IOException, TimeoutException {
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
// 删除队列
channel.queueDelete(queueName);
channel.close();
connection.close();
}
}
```
上面这个工具类提供了 RabbitMQ 常用的三个操作:发送消息、接收消息和删除队列。其中,发送消息和删除队列都比较简单,主要是调用 RabbitMQ 的 API 完成相应操作。而接收消息则需要一些特殊的设置,比如手动确认消息已被接收等。需要注意的是,在使用时需要先安装 RabbitMQ 服务器,并在该服务器上创建相应的队列。
阅读全文