Java RabbitMQ可以';我没有收到消息
在本例中,我使用的是与本教程相同的类: 我有两门课: Send.javaJava RabbitMQ可以';我没有收到消息,java,rabbitmq,Java,Rabbitmq,在本例中,我使用的是与本教程相同的类: 我有两门课: Send.java import com.rabbitmq.client.Connection; import com.rabbitmq.client.Channel; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Send { public static final String QUEUE_NAM
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Send {
public static final String QUEUE_NAME="hello";
public static void main(String[] args) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection=null;
Channel channel =null;
try {
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME,false,false,false,null);
String message = "Hello word toto";
channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
System.out.println(" [ x ] Sent '"+message+"'");
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
和receiv类:
import com.rabbitmq.client.*;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
public class Receiv{
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) {
Connection connection=null;
Channel channel=null;
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try {
connection = factory.newConnection();
channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}finally {
try {
channel.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我得到了类似于示例的编译结果,但我没有看到收到的消息
谢谢。您是否向队列发送了消息?我直接使用了频道,但为什么?您会在第一次发送消息时收到消息,因此如果您没有向队列发送任何消息(队列为空),则您将不会收到任何消息谢谢,但在教程()中,我认为他没有使用队列。简单地说,我的意思是,您需要先启动send类,然后再启动另一个类