RabbitMQ学習ノート2:rabbitmq受信メッセージHelloworld(Java版)送信


WindowsでのRabbitMQ関連サービスのインストールについては、「http://blog.csdn.net/u010416588/article/details/54599341
rabbitmq java clientの導入
以前はローカル(windowsの下)にRabbitMQサーバをインストールしました.次にrabbitmq Java clientを導入します.eclipseでmavenプロジェクトを作成しpom.xmlファイルに依存を追加
<dependency>
  <groupId>com.rabbitmqgroupId>
  <artifactId>amqp-clientartifactId>
  <version>4.0.1version>
dependency>

Alternatively, if you’re using Gradle:
dependencies {
  compile 'com.rabbitmq:amqp-client:4.0.1'
}

JArパッケージダウンロードアドレスhttp://www.rabbitmq.com/java-client.html
二rabbitmqメッセージ送信
2.1メッセージ送信クラスの作成
package com.gta.goldnock.mq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
 * 
* @ClassName: Send
* @Description: TODO(The sender will connect to RabbitMQ, send a single message, then exit.)
* @author yuhuan.gao
* @date 2017 1 19    1:37:19
*
 */
public class Send {
    /*
     *       “hello”
     */
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] argv) throws IOException, TimeoutException{
        //      
        ConnectionFactory factory = new ConnectionFactory();
        //    ,         ,      IP
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        //      
        Channel channel = connection.createChannel();
        //           ,          ‘hello’
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello World!";
        //Declaring a queue is idempotent -                 
        //     byte array, so        
        channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

        //       ,       
        channel.close();
        connection.close();
    }
}

2.2 mainを実行しましたが、メッセージが正常に送信されたかどうかは不明です.rabbit-serverのログの表示
=INFO REPORT==== 19-Jan-2017::14:27:46 ===
accepting AMQP connection <0.19748.19> ([::1]:60445 -> [::1]:5672)

=INFO REPORT==== 19-Jan-2017::14:27:46 ===
closing AMQP connection <0.19748.19> ([::1]:60445 -> [::1]:5672)

2.3プラグインによるサービス管理の表示
RabbitMQ学习笔记二:rabbitmq发送接收消息Helloworld(Java版)_第1张图片 messageは3から4に変わり、メッセージは送信に成功した.
Sending doesn't work!

If this is your first time using RabbitMQ and you don't see the "Sent" message then you may be left scratching your head wondering what could be wrong. Maybe the broker was started without enough free disk space (by default it needs at least 1Gb free) and is therefore refusing to accept messages. Check the broker logfile to confirm and reduce the limit if necessary. The configuration file documentation will show you how to set disk_free_limit.

三rabbitmqメッセージ受信
senderとは異なり、recieverはRabbitMQからメッセージを送信します.senderは単一のメッセージを送信するたびにrecieverがサービスを実行し監視し、メッセージがあると受信します.
3.1メッセージ受信クラスの作成
package com.gta.goldnock.mq;


import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

/**
 * 
* @ClassName: Recv
* @Description: TODO(     )
* @author yuhuan.gao
* @date 2017 1 19    2:33:27
*
 */
public class Recv {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception{
        //      
        ConnectionFactory factory = new ConnectionFactory();
        //    ,         ,      IP
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        //      
        Channel channel = connection.createChannel();
        //         ,       "hello"  
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
        //The extra DefaultConsumer is a class implementing the Consumer interface 
        //we'll use to buffer the messages pushed to us by the server.
        Consumer consumer = new DefaultConsumer(channel){
            //  DefaultConsumer handleDelivery  ,        
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, 
                    AMQP.BasicProperties properties, byte[] body) throws IOException{
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true,consumer);
    }
}
We're about to tell the server to deliver us the messages from the queue. Since it will push us messages asynchronously, we provide a callback in the form of an object that will buffer the messages until we're ready to use them. That is what a DefaultConsumer subclass does.

3.2運転
mainを実行し、正常に実行し、コンソールは次のように印刷されます.
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'
 [x] Received 'Hello World!'

上記の結果は、予想されるように、「hello」キューメッセージを購読すると、前のSenderからxメッセージが受信される.Senderのmainの実行を続行すると、Recvは実行中に自動的にメッセージを受信します.