首先需要导入对应的依赖
com.rabbitmq amqp-client5.6.0
依赖导入完毕后,首先实现生产者
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂
final ConnectionFactory factory = new ConnectionFactory();
//2.设置参数
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("admin");
factory.setUsername("admin");
factory.setPassword("admin");
//3.创建连接connection
final Connection connection = factory.newConnection();
//4.创建channel
final Channel channel = connection.createChannel();
//创建队列
channel.queueDeclare("hello_world",true,false,false,null);
//发送消息
String body = "hello consumer";
channel.basicPublish("","hello_world",null,body.getBytes());
channel.close();
connection.close();
}
其次:实现消费者
public static void main(String[] args) throws IOException, TimeoutException {
//1.创建连接工厂
final ConnectionFactory factory = new ConnectionFactory();
//2.设置参数
factory.setHost("127.0.0.1");
factory.setPort(5672);
factory.setVirtualHost("admin");
factory.setUsername("admin");
factory.setPassword("admin");
//3.创建连接connection
final Connection connection = factory.newConnection();
//4.创建channel
final Channel channel = connection.createChannel();
//创建队列
channel.queueDeclare("hello_world",true,false,false,null);
channel.basicConsume("hello_world",true,new DefaultConsumer(channel) {
//回调方法
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
// super.handleDelivery(consumerTag, envelope, properties, body);
System.out.println("consumerTag==========》》》》"+consumerTag);
System.out.println("Exchange=========>>>>>>>"+envelope.getExchange()+"=====rount======>>>"+envelope.getRoutingKey());
System.out.println("properties================>>>"+properties.getMessageId());
System.out.println("body=============>>>>>>>>>"+ new String(body));
}
});
}
首先启动生产者将消息发送到mq,接着启动消费者读取消息
至此,rabbitMq简单模式就实现了



