我在将一些连接信息传递给可运行线程时遇到问题(使用rabbitmq,但我认为这不是rabbitmq 特有的并且可以应用于任何东西)。我的目标是让一些工作线程处理队列中的一些工作,但我不希望每次都打开和关闭连接的开销。
代码在没有可运行的情况下工作(它实际上是从rabbitmq教程中偷来的)但是一旦我实现一个传递连接的可运行我在doWork()上得到这个错误:
The method doWork(Channel, String) is undefined for the type Worker
如果我从可运行中删除通道并且不发送它那么程序工作很好,但连接信息没有被传递。我能做些什么?
这是我的代码:
//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);
}
}
然后:
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() {