1 - maven依赖
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>5.7.2</version>
</dependency>
2 - 生产者
public class Provider {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.181.133");
factory.setPort(5672);
factory.setVirtualHost("/ems");
factory.setUsername("root");
factory.setPassword("root");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("onebyone", true, false, false, null);
channel.basicPublish("","onebyone", null,"张三".getBytes());
channel.close();
connection.close();
}
}
3 - 消费者
public class Consumer {
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("192.168.181.133");
factory.setPort(5672);
factory.setVirtualHost("/ems");
factory.setUsername("root");
factory.setPassword("root");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare("onebyone", true, false , false, null);
channel.basicConsume("onebyone", true, new DefaultConsumer(channel){
@Override
public void handleDelivery(java.lang.String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
System.out.println("这是异步");
}
}
4 - 测试
先开启消费者进行阻塞获取消息 在开启生产者 查看消费者状态
|