RabbitMQ接口封裝


1.引用

<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
</dependency>

2.代碼
package cn.piesat.task.util;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
* rabbitMQ收發消息工具類
*/
@Component
public class RabbitMQUtil {
private static Logger rabbitMQUtilLogger = LoggerFactory.getLogger(RabbitMQUtil.class);

/**
* 發送持久化消息到指定的隊列中
*
* @param uri 服務器連接uri參數
* @param queueName 隊列名稱
* @param msg 消息體 json 格式
* @return true: 發送成功, false: 發送失敗
*/
public static boolean sendMsg(String uri, String queueName, String msg) {
boolean isSuccess = false;
Connection connection = null;
Channel channel = null;
try {
ConnectionFactory factory = new ConnectionFactory();
factory.setUri(uri);
connection = factory.newConnection();
if (connection != null) {
channel = connection.createChannel();
if (channel != null) {
AMQP.Queue.DeclareOk declareOk = channel.queueDeclare(queueName, true, false,
false, null);
if (declareOk != null) {
// 構建消息屬性
int deliveryMode = 2; // 1:臨時 2:持久化
AMQP.BasicProperties basicProperties = new AMQP.BasicProperties(null, "text/json",
null, deliveryMode,
null, null,
null, null,
null, null,
null, null,
null, null);

channel.basicPublish("", queueName, false, false, basicProperties, msg.getBytes());
isSuccess = true;
} else {
rabbitMQUtilLogger.error("queue declare error");
}
} else {
connection.close();
rabbitMQUtilLogger.error("create channel error");
}
} else {
rabbitMQUtilLogger.error("create connection error");
}

} catch (Exception e) {
rabbitMQUtilLogger.error(e.toString());
rabbitMQUtilLogger.error(e.getStackTrace().toString());
isSuccess = false;
} finally {
try {
if (channel != null) {
channel.close();
}

if (connection != null) {
connection.close();
}
} catch (Exception e) {
rabbitMQUtilLogger.error("close connection error");
rabbitMQUtilLogger.error(e.toString());
rabbitMQUtilLogger.error(e.getStackTrace().toString());
}

return isSuccess;
}
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM