I’m having problems passing some connection info to a runnable thread(using rabbitmq, but I don’t think this is specific to rabbitmq and can apply to anything). My goal is to have a few worker threads processing some work from a queue but I don’t want the overhead of opening and closing connections each time.
The code works without runnable(its actually stolen from the rabbitmq tutorials) but as soon as I implement a runnable passing a connection I get this error on doWork():
The method doWork(Channel, String) is undefined for the type Worker If I remove Channel from runnable and don’t send it then the program works fine but the connection information is not being passed. What can I do?
Here’s my code:
//this is the standard stuff to start a connection
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
channel.basicQos(1);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume("task_queue", false, consumer);
//end of standard stuff
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
doWork(channel, message);
System.out.println(" [x] Done" );
channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
}
then:
public class doWork implements Runnable{
protected Channel channel = null;
protected String message = null;
public doWork(Channel channel, String message) {
this.channel = channel;
this.message = message;
}
public void run() {
If you moved your code to a Runnable, this means you created a new class. If you want to invoke it, then you should have something like this
But you probably want to move all that to an external Thread, which is done by:
Btw, classes should start with an upper-case letter, it makes the code much more readable.