読者です 読者をやめる 読者になる 読者になる

ITお絵かき修行

3歩歩いても忘れないために

RabbitMQ tutorial - Work queues Pattern in Java

RabbitMQのチュートリアル

【お題】
RabbitMQ - RabbitMQ tutorial - Work Queues
f:id:hhhhhskw:20140925233729j:plain


【実行環境】
Windows7 64bit
・RabbitMQ3.5.5
・jdk1.7.0_60


【前提】
・RabbitMQはインストール済
コンパイルする手順は省く


【手順】
1.ProducerクラスとConsumerクラスを作成

●Producer(送信者)

package no2;

import java.io.IOException;

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

public class Producer {

	private final static String QUEUE_NAME = "hello";

	public static void main(String[] args) {

		Connection connection = null;
		Channel channel = null;
		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");
			connection = factory.newConnection();
			channel = connection.createChannel();

			channel.queueDeclare(QUEUE_NAME, false, false, false, null);
			String message = getMessage(args);

                        // メッセージを送信する
			channel.basicPublish("", "hello", null, message.getBytes());
			System.out.println(" [x] Sent '" + message + "'");

		} catch (Throwable th) {
			th.printStackTrace(System.out);
		} finally {

			// AutoClosableは実装していない
			try {
				channel.close();
				connection.close();
			} catch (IOException e) {
				e.printStackTrace(System.out);
			}
		}
	}

	private static String getMessage(String[] strings) {
		if (strings.length < 1) {
			return "Hello World!";
		}
		return joinStrings(strings, " ");
	}

	private static String joinStrings(String[] strings, String delimiter) {
		int length = strings.length;
		if (length == 0) {
			return "";
		}
		StringBuilder words = new StringBuilder(strings[0]);
		for (int i = 1; i < length; i++) {
			words.append(delimiter).append(strings[i]);
		}
		return words.toString();
	}
}


●Consumer(受信者)

package no2;

import java.io.IOException;

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

public class Consumer {

	private final static String QUEUE_NAME = "hello";

	public static void main(String[] args) {

		Connection connection = null;
		Channel channel = null;

		try {
			ConnectionFactory factory = new ConnectionFactory();
			factory.setHost("localhost");
			connection = factory.newConnection();
			channel = connection.createChannel();
			channel.queueDeclare(QUEUE_NAME, false, false, false, null);
			System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

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

			// メッセージを待ち受ける
			while (true) {
				QueueingConsumer.Delivery delivery = consumer.nextDelivery();
				String message = new String(delivery.getBody());

				System.out.println(" [x] Received '" + message + "'");
				doWork(message);
				System.out.println(" [x] Done");
			}

		} catch (Throwable th) {
			th.printStackTrace(System.out);
		} finally {

			// AutoClosableは実装していない
			try {
				channel.close();
				connection.close();
			} catch (IOException e) {
				e.printStackTrace(System.out);
			}
		}
	}

	private static void doWork(String task) throws InterruptedException {
		for (char ch : task.toCharArray()) {
			if (ch == '.') {
				Thread.sleep(1000);
			}
		}
	}
}


資産構成は以下の通り。

D:\workspace\workspace_rabbitmq\Tutorial>tree /f
D:.
│
├─bin
│  │
│  └─no2
│          Consumer.class
│          Producer.class
│
├─lib
│      commons-cli-1.1.jar
│      commons-io-1.2.jar
│      rabbitmq-client.jar
│
└─src
    │
    └─no2
            Consumer.java
            Producer.java


2.コマンドプロンプトを2窓立ち上げ、それぞれConsumerを実行する。

D:\workspace\workspace_rabbitmq\Tutorial>
D:\workspace\workspace_rabbitmq\Tutorial>set CP=./bin;./lib/commons-io-1.2.jar;./lib/commons-cli-1.1.jar;./lib/rabbitmq-client.jar
D:\workspace\workspace_rabbitmq\Tutorial>java -cp %CP% no2/Consumer
 [*] Waiting for messages. To exit press CTRL+C


3.コマンドプロンプトを1窓立ち上げ、Producerを実行する。

D:\workspace\workspace_rabbitmq\Tutorial>
D:\workspace\workspace_rabbitmq\Tutorial>set CP=./bin;./lib/commons-io-1.2.jar;./lib/commons-cli-1.1.jar;./lib/rabbitmq-client.jar
D:\workspace\workspace_rabbitmq\Tutorial>java -cp %CP% no2/Producer
 [x] Sent 'Hello World!'


複数回実行すると、2.で立ち上げたConsumerの実行画面に、
Queueより取得した値が交互に出力される。

D:\workspace\workspace_rabbitmq\Tutorial>java -cp %CP% no2/Consumer
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received 'Hello World!'
 [x] Done
 [x] Received 'Hello World!'
 [x] Done
 [x] Received 'Hello World!'
 [x] Done
 [x] Received 'Hello World!'
 [x] Done