Jeffreak
Jeffreak

Reputation: 1

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.

Upvotes: 0

Views: 42

Answers (1)

user11044402
user11044402

Reputation:

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.

Upvotes: 1

Related Questions