RabbitMQ之HelloWorld

120 阅读1分钟

最近在学习RabbitMQ,今天记录一下学习过程,下面是我的代码:

  1. 引入依赖
<dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>3.6.5</version>
</dependency>
  1. 生产者
public static void main(String[] args) throws IOException, TimeoutException {
    // 1.创建connectionFactory
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    connectionFactory.setVirtualHost("/");

    // 2.创建connection
    Connection connection = connectionFactory.newConnection();
    Channel channel = connection.createChannel();
    String queueName = "test001";
    channel.queueDeclare(queueName,false,false,false,null);

    Map<String,Object> headers = new HashMap<>();
    AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
            .headers(headers)
            .deliveryMode(2)
            .contentType("UTF-8")
            .build();

    for (int i = 0; i < 5; i++) {
        String msg = "Hello World!" + i;
        channel.basicPublish("",queueName,properties,msg.getBytes());
    }
}
  1. 消费者
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
    // 1.创建connectionFactory
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("127.0.0.1");
    connectionFactory.setPort(5672);
    connectionFactory.setVirtualHost("/");

    connectionFactory.setAutomaticRecoveryEnabled(true);
    connectionFactory.setConnectionTimeout(3000);

    // 2.创建connection
    Connection connection = connectionFactory.newConnection();
    Channel channel = connection.createChannel();

    String queueName = "test001";
    channel.queueDeclare(queueName,false,false,false,null);

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName,true,consumer);

    while (true){
        Delivery delivery = consumer.nextDelivery();
        String msg = new String(delivery.getBody());
        System.out.println("收到消息:" + msg);
    }
}
  1. 运行结果

image.png