1 介绍RabbitMQ的图形界面
2 操作前配置
2.1 添加用户
2.2 添加Virtual host
3 代码编写
3.1 生产-消费者模式
public class One2One {
public static void producer() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("ymx");
connectionFactory.setPassword("123");
connectionFactory.setVirtualHost("/one2one");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("hello", true, false, false, null);
channel.basicPublish("", "hello", null, "hello rabbitmq".getBytes());
channel.close();
connection.close();
}
public static void consumer() throws IOException, TimeoutException {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setUsername("ymx");
connectionFactory.setPassword("123");
connectionFactory.setVirtualHost("/one2one");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("hello", true, false, false, null);
channel.basicConsume("hello", true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
}
public static void main(String[] args) throws IOException, TimeoutException {
for (int i = 0; i < 10; i++) {
producer();
}
consumer();
}
}
测试结果:
|