1、登录RabbitMQ图形化操作页面:
这是系统默认提供的:
username:guest
password:guest
2、创建一个用户:
3、此时会发现,新创建的用户并没有虚拟机
4、创建一个虚拟机:
5、将之前创建的用户与虚拟机赋予权限:
6、创建一个项目,开始写个Demo进行测试:
1、引入项目依赖:com.rabbitmq amqp-client 5.6.0
2、编写生产者代码:
public class Producer_HelloWorld {
public static void main(String[] args) throws IOException, TimeoutException {
// 1、创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
// 2、设置参数
// ip设置:默认值也是localhost
factory.setHost("localhost");
// port设置 默认值:5672
factory.setPort(5672);
// 虚拟机设置 默认值:/
factory.setVirtualHost("/echo");
// 用户名设置 默认 guest
factory.setUsername("echo");
// 密码设置 默认 guest
factory.setPassword("echo");
// 3、创建连接 Connection
Connection connection = factory.newConnection();
// 4、创建Channel
Channel channel = connection.createChannel();
// 5、创建队列Queue
channel.queueDeclare("hello_world",true,false,false,null);
// 6、发送消息
String bodyStr = "简单模式";
channel.basicPublish("","hello_world",null,bodyStr.getBytes());
// 7、释放资源
channel.close();
connection.close();
}
}
3、编写消费者代码:
public class Consumer_HelloWorld {
public static void main(String[] args) throws IOException, TimeoutException {
// 1、创建连接工厂
ConnectionFactory factory = new ConnectionFactory();
// 2、设置参数
// ip设置:默认值也是localhost
factory.setHost("localhost");
// port设置 默认值:5672
factory.setPort(5672);
// 虚拟机设置 默认值:/
factory.setVirtualHost("/echo");
// 用户名设置 默认 guest
factory.setUsername("echo");
// 密码设置 默认 guest
factory.setPassword("echo");
// 3、创建连接 Connection
Connection connection = factory.newConnection();
// 4、创建Channel
Channel channel = connection.createChannel();
// 5、创建队列Queue
//如果没有一个名字叫hello_world的队列,则会创建该队列,如果有则不会创建
// 由于生产者已经创建了该队列,所以这一行代码可以省略
channel.queueDeclare("hello_world",true,false,false,null);
// 6、创建消费者,并设置消息处理
DefaultConsumer 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("message:" + new String(body));
}
};
// 7、监听消息
channel.basicConsume("hello_world",true,consumer);
// 8、消费者应该一直监听消息,所以不应该关闭连接
}
}
7、测试:
-
运行生产者代码,发送消息
-
在控制页面,切换用户
-
查看队列列表
-
此时有一个队列被创建,而且还有一条消息待消费
-
运行 消费者 代码
-
此时消息已经被消费
此时控制台也打印出了信息: consumerTag:amq.ctag-cIjcCPkClJjb1l-MFBO2Tg Exchange: RoutingKey:hello_world properties:#contentHeader(content-type=null, content-encoding=null, headers=null, delivery-mode=null, priority=null, correlation-id=null, reply-to=null, expiration=null, message-id=null, timestamp=null, type=null, user-id=null, app-id=null, cluster-id=null) message:[B@5a60869
[项目代码链接:https://github.com/Mbm7280/rabbitmq_demo](https://github.com/Mbm7280/rabbitmq_demo)



