为防止消费者消息没有处理成功rabbit就将queue中的该条消息删除,消费者需要手动向rabbit确认信息是否已正常处理。
import com.example.springcloud.eurekaclinet1demo.uitl.RabbitUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
* 生产者
* Created by py
* 2020/4/19
*/
public class SendRabbit {
final static String queue = "work_queue_durable";
public static void main(String[] args) throws IOException, TimeoutException {
Connection instance = RabbitUtils.getInstance();
Channel channel = instance.createChannel();
//设置rabbit信息持久化,为true时rabbit会将消息写入磁盘中
boolean durable = true;
//PS:rabbit不支持修改已声明的队列,
//若一个队列声明的时候为设置持久化,声明后在设置持久化就会报错,
//想要操作要么把队列删除重新声明该队列,要命声明一个新队列设置持久化
channel.queueDeclare(queue,durable,false,false,null);
int prefetchCount = 1;
//每个消费者发送确认信号之前,消息队列不发送下一个消息过来,一次只处理一个消息
//限制发给同一个消费者不得超过1条消息
channel.basicQos(prefetchCount,false);
// 发送的消息
for (int i = 0; i < 50; i++) {
String msg = "This is work queue!==="+i;
channel.basicPublish("","work_queue",null,msg.getBytes());
}
channel.close();
instance.close();
}
}
/**
* Created by py
* 2020/4/19
*/
public class FristConsumer {
final static String queue = "work_queue_durable";
public static void main(String[] args) throws IOException, TimeoutException {
Connection instance = RabbitUtils.getInstance();
Channel channel = instance.createChannel();
//设置rabbit信息持久化,为true时rabbit会将消息写入磁盘中
boolean durable = true;
//PS:rabbit不支持修改已声明的队列,
//若一个队列声明的时候为设置持久化,声明后在设置持久化就会报错,
//想要操作要么把队列删除重新声明该队列,要命声明一个新队列设置持久化
channel.queueDeclare(queue,durable,false,false,null);
//每个消费者发送确认信号之前,消息队列不发送下一个消息过来,一次只处理一个消息
//限制发给同一个消费者不得超过1条消息
channel.basicQos(1);
DefaultConsumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
String str = new String(body,"utf-8");
System.out.println("FristConsumer==="+str);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//手动回复rabbit消息已处理
channel.basicAck(envelope.getDeliveryTag(),false);
/**
* public void basicNack(long deliveryTag, boolean multiple, boolean requeue)
* deliveryTag: 该条消息的标识
* multiple: 多条消息还是单条消息;false:单条消息
* requeue:该条消息是否重新返回队列;
*/
//channel.basicNack(envelope.getDeliveryTag(),false,false);
}
}
};
//消息的确认模式:禁止自动应答
boolean autoAck = false;
channel.basicConsume("work_queue",autoAck,consumer);
}
}
生产者:
channel.basicQos(prefetchCount,false);
限制发给同一个消费者不得超过1条消息,每个消费者发送确认信号之前,消息队列不发送下一个消息过来,一次只处理一个消息。
消费者:
channel.basicConsume("work_queue",autoAck,consumer);
autoAck = false;消息的确认模式:禁止自动应答改为手动回复,消费者未回复前queue不会将该条消息删除。
channel.basicAck(envelope.getDeliveryTag(),false);
手动回复rabbit消息已处理