简体   繁体   中英

Is there a better way to use rabbitMQ to consume multithreaded messages?

I am currently learning how to use RabbitMQ to schedule and dispatch jobs to different VM.I am now working on the worker side. The worker on the VM need to do some hard-loading jobs and return to the server if it is successfully done.

I have done some surveys on the official api and also here ,trying to test if it can work.

Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.basicQos(10);
Consumer consumer = new DefaultConsumer(channel) {
    @Override
    public void handleDelivery(String consumerTag, final Envelope envelope, AMQP.BasicProperties properties, final byte[] body) throws IOException {
        Thread th = new Thread() {public void run() {
        try{
        //do some jobs here...
        synchronized (this) {channel.basicAck(envelope.getDeliveryTag(), false);}
        } catch (Exception e) {
            e.printStackTrace();
            try {
                synchronized (this) {channel.basicReject(envelope.getDeliveryTag(), false)}
            } catch (IOException e1) {e1.printStackTrace();}
        }
        };
        th.start();
    }
};
channel.basicConsume(queueName, false, consumer);

This code works for me. But I am just wondering if there is a better and thread-safer way to do it.

How about using an ExecutorService instead of a new thread for every message? Depending on the rate of incoming messages the number of threads created by your approach can grow very large very quickly which could bring down your service.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM