如果是手工确认消息,需要在handleDelivery方法中进行相关的确认,代码如下:
//手动确认long deliveryTag = envelope.getDeliveryTag();channel.basicAck(deliveryTag, false);5.8、完整demo5.8.1、发送消息public class Producer { public static void main(String[] args) throws IOException, TimeoutException, NoSuchAlgorithmException, KeyManagementException, URISyntaxException { //连接RabbitMQ服务器 ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); factory.setHost("197.168.24.206"); factory.setPort(5672); //创建一个连接 Connection conn = factory.newConnection(); //获得信道 Channel channel = conn.createChannel(); //声明交换器 channel.exchangeDeclare("ex-hello","direct"); //发送的消息内容 byte[] messageBodyBytes = "Hello, world!".getBytes(); channel.basicPublish("ex-hello", "route-hello", null, messageBodyBytes); //关闭通道 channel.close(); conn.close(); }}5.8.2、接受消息public class Consumer { public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //连接RabbitMQ服务器 ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("/"); factory.setHost("197.168.24.206"); factory.setPort(5672); //创建一个连接 Connection conn = factory.newConnection(); //获得信道 Channel channel = conn.createChannel(); //声明队列 channel.queueDeclare("queue-hello", true, false, false, null); //声明绑定 channel.queueBind("queue-hello", "ex-hello", "route-hello"); //监听队列中的消息 channel.basicConsume("queue-hello",true,new SimpleConsumer(channel)); TimeUnit.SECONDS.sleep(10); channel.close(); conn.close(); }}消息处理类SimpleConsumer
public class SimpleConsumer extends DefaultConsumer { public SimpleConsumer(Channel channel) { super(channel); } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { //接受从队列中发送的消息 System.out.println(consumerTag); System.out.println("-----收到消息了---------------"); System.out.println("消息属性为:"+properties); System.out.println("消息内容为:"+new String(body)); }}
推荐阅读
- 深入理解 Linux 内核中的 RCU 机制
- 深入设计原则-SOLID
- 深入理解 HttpSecurity
- 什么是MQ?什么是RabbitMQ?能做什么?简单理解一下?
- 资深架构师:深入聊聊获取屏幕高度这件事
- 从 Spring Boot 程序启动深入理解 Netty 异步架构原理
- docker安装rabbitmq延时队列插件
- 解密windows系统版本和版本号,深入了解一组简单数字背后的故事
- 详解版 深入浅出 HTTPS
- Linux主流架构运维工作简单剖析
