《rabbitMQ学习》十一 消息持久化操作

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);
	}
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值