1.图解

2.生产者
package com.producer;
import com.rabbitmq.client.*;
public class Producer_HelloWorld {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/learning");
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
AMQP.Queue.DeclareOk hello_world = channel.queueDeclare("hello_world", true, false, false, null);
String body = "hello rabbitmq";
channel.basicPublish("", "hello_world", null, body.getBytes());
channel.close();
connection.close();
}
}
3.消费者
package com.consumer;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer_HelloWorld {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/learning");
connectionFactory.setUsername("admin");
connectionFactory.setPassword("admin");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("hello_world", true, false, false, null);
Consumer consumer = new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("consumerTag:" + consumerTag);
System.out.println("exchange:" + envelope.getExchange());
System.out.println("routingKey:" + envelope.getRoutingKey());
System.out.println("properties:" + properties);
System.out.println("body:" + new String(body));
}
};
channel.basicConsume("hello_world", true, consumer);
}
}