我遇到了问题,将一些连接信息传递给可运行线程(使用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