我遇到了問題,將一些連接信息傳遞給可運行線程(使用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() {
請在'UpperCase'中命名你的類,'camelCase'中的方法和字段以及'FULL_CAPS'中的靜態最終常量。另請注意[接口總是形容詞,類是名詞](http://www.iwombat.com/standards/JavaStyleGuide.html#Class%20and%20Interface%20Names)。 – adarshr 2012-04-15 16:36:08