Akka Actors Java竞争消费者

时间:2014-05-02 17:43:13

标签: java apache-camel cluster-computing akka actor

我正在尝试使用Akka和Camel的竞争事件消费者实现。我使用的是Akka 2.3.2和Camel 5.8.0。我将camel连接到ActiveMQ代理并使用生产者从其他端生成消息。在下面的代码中,EventManager是创建使用者池的master,而EventProcessor是消息处理actor。

EventManager.java

    import org.apache.activemq.ActiveMQConnection;
    import org.apache.activemq.camel.component.ActiveMQComponent;
    import org.apache.camel.CamelContext;

    import akka.actor.ActorRef;
    import akka.actor.ActorSystem;
    import akka.actor.Props;
    import akka.actor.UntypedActor;

    import akka.camel.Camel;
    import akka.camel.CamelExtension;
    import akka.japi.Creator;
    import akka.routing.RoundRobinPool;

    public class EventManager {




        private final ActorSystem akkaSystem;

        private CamelContext camelContext = null;

        private ActorRef workRouter;

        public EventManager(ActorSystem system) {
            akkaSystem = system;

            initialize();
        }

        public void initialize() {

            Camel camel = CamelExtension.get(akkaSystem);

            camelContext = camel.context();

            ActiveMQComponent activemqComponent = ActiveMQComponent.activeMQComponent("tcp://localhost:61616");
            activemqComponent.setDeliveryPersistent(false);
            camelContext.addComponent("activemq",activemqComponent );


            int numOfWorkers = 5;

// distributing the message processing across a pool of 5 actors
            ActorRef workRouter =
                      akkaSystem.actorOf(new RoundRobinPool(numOfWorkers).props(Props.create(EventProcessor.class)), 
                        "workRouter");

        }

    }

EventProcessor.java

import org.apache.log4j.Logger;



import akka.actor.UntypedActor;
import akka.camel.CamelMessage;
import akka.camel.javaapi.UntypedConsumerActor;

public class EventProcessor extends UntypedConsumerActor{

    private static final Logger LOGGER = Logger.getLogger(EventProcessor.class);
    public EventProcessor() {

    }

    public void onReceive(Object message) {
        if(message instanceof CamelMessage) {
            CamelMessage camelMessage = (CamelMessage) message;
            String body = camelMessage.getBodyAs(String.class, getCamelContext());
                LOGGER.info("Message handled by :" +this.getSelf().path().name());

                LOGGER.info("Message body:" + body);
        }


    }

    public boolean autoAck() {
        return true;
    }
    public String getEndpointUri() {
        return "activemq:queue:dest";
    }

}

我看到的问题是,消息似乎是由单个actor消耗的,而不是在池中分布。我需要创建一个单独的骆驼路线来分发吗?我还想在不同的物理节点上分发处理。感谢您的投入和最佳实践。

1 个答案:

答案 0 :(得分:0)

尝试在AMQ端点上设置并发使用者

return "activemq:queue:dest?concurrentConsumers=50";

..或在端点上启用异步使用者

return "activemq:queue:dest?asyncConsumer=true";

此外,您似乎得到了错误的版本信息。没有Camel版本5.8。我认为这是AMQ版本。