Interface package RabbitMQ

1. references

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

2.代码
cn.piesat.task.util Package; 

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 messaging tools
* /
@Component
public class RabbitMQUtil {
Private static Logger rabbitMQUtilLogger = LoggerFactory.getLogger (RabbitMQUtil.class);

/ **
* persistent transmission message to a specified queue
*
* @param uri server connection uri parameter
* @param queueName queue name
* @param msg message body format 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;
}
}
}

Guess you like

Origin www.cnblogs.com/runnerjack/p/12502787.html