1.连接
package com.utils;
import java.io.IOException;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionUtils {
public static Connection getConnetions() throws IOException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("/vhost_zq");
factory.setUsername("develop");
factory.setPassword("123456");
return factory.newConnection();
}
}
2.生产者
package com.txtransasion;
import com.mmmm.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
public class Send {
/**
* rabbitmq 消息确认机制--事务机制
*
* 首先在rabbitmq中我們可以通過持久化数据来解决rabbitmq服务器的异常的数据丢失的问题;
* 但是生产者将数据发送出去之后,消费者到底有没有接受到信息,rabbitmq服务器默认的情况是不知道。 那么如何解决这种问题呢? 有两种解决方案:
* (1)AMQP实现了事务的机制;
* (2)Confirm模式
*
* 本章主要讲解事务机制 txSelect 、txCommit、txRollback
* ①txSelect:将当前channel设置成为transation模式;
* ②txCommit:事务的提交;
* ③txRollback:回滚;
*/
private static final String QUEUE_NAME = "te_queue";
public static void main(String[] args) throws Exception {
Connection connection = ConnectionUtils.getConnetions();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String msg = "hahahah!!!";
try {
channel.txSelect();
channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
// 如果发布的时候出现异常则发布这个动作会回滚,这样的话消费者不会收到消息的。
int x = 1 / 0;
System.out.println("===send " + msg + "===");
channel.txCommit();
} catch (Exception e) {
channel.txRollback();
System.out.println("tx send msg rollback!!!");
}
channel.close();
connection.close();
}
}
3.消费者
package com.txtransasion;
import java.io.IOException;
import com.mmmm.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.AMQP.BasicProperties;
public class Rec1 {
private static final String QUEUE_NAME = "te_queue";
public static void main(String[] args) throws IOException {
Connection connection = ConnectionUtils.getConnetions();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.basicConsume(QUEUE_NAME, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
System.out.println("recieve msg:" + new String(body, "utf-8"));
};
});
}
}