RabbitMq消费者

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;

/**
 * 实现自己的Consumer
 */
public class MyConsumer extends DefaultConsumer {
    public MyConsumer(Channel channel){
        super(channel);
    }
    @Override
    public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
        System.err.println("-----------consume message----------");
        System.err.println("consumerTag: " + consumerTag);
        System.err.println("envelope: " + envelope);
        System.err.println("properties: " + properties);
        System.err.println("body: " + new String(body));
    }
}

以上为处理基类。

import com.rabbitmq.client.*;

import java.io.IOException;


public class RabbitMqReceive {
    //队列名称
    private static final String QUEUE_NAME = "qa";

    public static void main(String[] args)
    {
        try
        {
            //获取连接
            Connection connection = RabbitMqUtil.getConnection();

            //从连接中获取一个通道
            Channel channel = connection.createChannel();

            //声明队列
            channel.queueDeclare(QUEUE_NAME, true, false, false, null);

            //监听队列
            channel.basicConsume(QUEUE_NAME, true, new MyConsumer(channel));
        }
        catch (IOException | ShutdownSignalException | ConsumerCancelledException e)
        {
            e.printStackTrace();
        }
    }
}

 

posted @ 2021-02-25 16:55  都是城市惹的祸  阅读(159)  评论(0)    收藏  举报