1.生产者
package com.cloudtech.web.mq.persistence;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.cloudtech.web.util.RabbitmqUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.MessageProperties;
public class Sender {
private final static String EXCHANGE_NAME="testpersist";
public static void main(String[] args) throws IOException, TimeoutException {
Connection conn = RabbitmqUtils.getConnection();
Channel channel = conn.createChannel();
//声明持久化的交换机
channel.exchangeDeclare(EXCHANGE_NAME, "direct",true,false,null);
//声明持久化消息
channel.basicPublish(EXCHANGE_NAME, "abc", MessageProperties.PERSISTENT_TEXT_PLAIN, "持久化数据".getBytes());
channel.close();
conn.close();
}
}
2.消费者
package com.cloudtech.web.mq.persistence;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.cloudtech.web.util.RabbitmqUtils;
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;
/**
*
* @ClassName: Rerver1
* @Description:
* @author wude
* @date 2018年8月1日
*
*/
public class Rerver1 {
private final static String EXCHANGER_NAME="testpersist"; //定义交换机的名称
private final static String QUEUE_NAME="testpersistqueue1"; //定义队列的名称
public static void main(String[] args) throws IOException, TimeoutException {
Connection conn = RabbitmqUtils.getConnection();
Channel channel = conn.createChannel();
channel.exchangeDeclare(EXCHANGER_NAME, "direct", true, false, null);
//声明持久化的队列
channel.queueDeclare(QUEUE_NAME, true, false, false, null);
channel.queueBind(QUEUE_NAME, EXCHANGER_NAME, "abc");
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
String s = new String(body);
System.out.println("消费者1:"+s);
//确认
//参数2 为false,确认收到消息 true为拒收到消息
channel.basicAck(envelope.getDeliveryTag(), false);
}
};
//注册消费者 参数2 手动确认 代表我们收到消息后,需要手动告诉服务器,我收到消息了
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}