深入剖析 rabbitMQ( 六 )

如果是手工确认消息,需要在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));    }}


推荐阅读