我正在使用Play Framework 2.2.2,并且正在使用JavaAkka(Akka Actor System)实现RabbitMQ消费者应用程序。所以我有一个MainActor,它在Play应用程序使用Global.OnStart函数时出现时被初始化。 MainActor创建一个RabbitMQ通道,然后开始从队列中消费。该队列中的每条消息都是另一个队列的名称,该队列必须分配给另一个必须从消息中提到的队列开始消费的子actor或子actor。所以基本上,我有一个订阅了一个RabbitMQ队列的MainActor和由主演员创建的几个子actor,每个子actor都订阅了它们自己的RabbitMQ队列。问题是,出于某种原因,我无法提出超过7名儿童演员。我怀疑这是在等待来自RabbitMQ的消息的儿童演员中的while(真)构造。下面是我的实现:RabbitMQ Play Java Akka
主要演员:
import play.Logger;
import com.typesafe.config.ConfigFactory;
import java.io.IOException;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.ActorRef;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import play.libs.Akka;
import util.RabbitMQConnection;
public class MainActor extends UntypedActor {
@Override
public void onReceive(Object msg) throws Exception {
try{
Connection connection = RabbitMQConnection.getConnection();
Channel channel = connection.createChannel();
String main_queue_name = ConfigFactory.load().getString("rabbitmq.default_queue");
channel.queueDeclare(main_queue_name, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(main_queue_name, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
ActorRef childActor = getContext().actorOf(Props.create(childActor.class));
childActor.tell(message, getSelf());
}
}catch (Exception e){
System.out.println(e.toString());
}
}
}
儿童演员:
import play.Logger;
import com.typesafe.config.ConfigFactory;
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import play.libs.Akka;
import play.libs.Json;
import akka.actor.UntypedActor;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import util.RabbitMQConnection;
public class childActor extends UntypedActor {
@Override
public void onReceive(Object msg) throws Exception {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String queue_name = ow.writeValueAsString(msg);
try{
Connection connection = RabbitMQConnection.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queue_name, false, false, false, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queue_name, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
JsonNode jsonMsg = Json.parse(message);
// Call some function to process the message
}
}catch (Exception e){
System.out.println(e.toString());
}
}
}