rabbitmq生产者消费者

<dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>5.7.0</version>
</dependency>

生产者:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class Procuder {

   
   public static void main(String[] args) throws Exception {
      //1 创建一个ConnectionFactory, 并进行配置
      ConnectionFactory connectionFactory = new ConnectionFactory();
      connectionFactory.setHost("192.168.6.1");
      connectionFactory.setPort(5672);
      connectionFactory.setVirtualHost("/");
      connectionFactory.setUsername("longlong");
      connectionFactory.setPassword("");
      
      //2 通过连接工厂创建连接
      Connection connection = connectionFactory.newConnection();
      
      //3 通过connection创建一个Channel
      Channel channel = connection.createChannel();
      
      //4 通过Channel发送数据
      for(int i=0; i < 5; i++){
         String msg = "Hello RabbitMQ!";
         //1 exchange   2 routingKey
         channel.basicPublish("", "test001", null, msg.getBytes());
      }

      //5 记得要关闭相关的连接
      channel.close();
      connection.close();
   }
}
消费者:
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {

   public static void main(String[] args) throws Exception {
      
      //1 创建一个ConnectionFactory, 并进行配置
      ConnectionFactory connectionFactory = new ConnectionFactory();
      connectionFactory.setHost("192.168.6.1");
      connectionFactory.setPort(5672);
      connectionFactory.setVirtualHost("/");
      connectionFactory.setUsername("longlong");
      connectionFactory.setPassword("");
      
      //2 通过连接工厂创建连接
      Connection connection = connectionFactory.newConnection();
      
      //3 通过connection创建一个Channel
      Channel channel = connection.createChannel();
      
      //4 声明(创建)一个队列
      String queueName = "test001";
      channel.queueDeclare(queueName, true, false, false, null);
      
      //5 创建消费者
      DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
         @Override
         public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            String msg = new String(body);
            System.err.println("消费端: " + msg);
         }
      };
      
      //6 设置Channel
      channel.basicConsume(queueName, true, defaultConsumer);
   }
}

猜你喜欢

转载自blog.csdn.net/qq_33002953/article/details/90144178