rabbitMQ学习-初体验(4)

178 阅读1分钟

导包

要想体验rabbimq,只要导入amqp-client这个模块。如下所示。

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

生产队列

public static void main(String[] args) throws IOException, TimeoutException {
    String exchangeName = "exchange_demo"; 
    String queueName = "queue_demo"; 
    ConnectionFactory factory = new ConnectionFactory();   
    factory.setHost(****);   // 输入服务器地址
    factory.setPort(5672);    
    factory.setUsername(****);  // 输入具有创建推送队列权限的用户    factory.setPassword(****);        Connection connection = factory.newConnection();    //创建链接   
     Channel channel = connection.createChannel();     // 创建信道    
    // 创建一个direct、持久化的,非自动删除的交换器    
    channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, null);    
    // 创建一个持久化、非排他的、非自动删除的队列    
    channel.queueDeclare(queueName, true, false, false, null);    
    // 交换机和队列绑定使用routeKEY    
    channel.queueBind(queueName, exchangeName, "demo");    
    String message = "hello world";    
    // 发送消息    
    channel.basicPublish(exchangeName, "demo", MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes(StandardCharsets.UTF_8));   
    channel.close();    
    connection.close();
}

消费队列

public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
     String queueName = "queue_demo";   
     ConnectionFactory factory = new ConnectionFactory();  
     factory.setHost("****");   
     factory.setPort(5672);   
     factory.setUsername("****");  
     factory.setPassword("****");  
     Connection connection = factory.newConnection();    //创建链接    
     Channel channel = connection.createChannel();  // 创建信道    
     channel.basicQos(1);    
     DefaultConsumer c = new DefaultConsumer(channel) {   
         @Override       
         public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { 
               System.out.println("recv message: " + new String(body)); 
               try {          
                  TimeUnit.SECONDS.sleep(1);  
               } catch (InterruptedException e) {  
                  e.printStackTrace();        
               }            
               channel.basicAck(envelope.getDeliveryTag(), false);    
         }   
     };    
     channel.basicConsume(queueName, c); 
     TimeUnit.SECONDS.sleep(5);   
     channel.close();   
     connection.close();
}