public class QueueListener implements MessageListener {
public static final ExecutorService executor = Executors.newWorkStealingPool();
public static boolean isActorinit=false;
public static ActorSystem system=null;
private ActorRef myActor=null;
private String _queueName=null;
public QueueListener(String qName){
this._queueName = qName;
if(!isActorinit){
system=ActorSystem.create("Controller");
try {
myActor=system.actorOf(Props.create(MessageExecutor.class.getConstructor(String.class).newInstance(_queueName).getClass()),"mysysActor");
} catch (Exception e) {
// TODO Auto-generated catch block
}
isActorinit=true;
}
}
/*
* (non-Javadoc)
* @see javax.jms.MessageListener#onMessage(javax.jms.Message)
*/
@Override
public void onMessage(Message msg) {
// processRequest(msg);
executeRequest(msg);
}
/** This method will process the message fetch by the listener.
*
* @param msg - javax.jms.Messages parameter get queue message
*/
private void processRequest(Message msg){
String requestData=null;
try {
if(msg instanceof TextMessage){
TextMessage textMessage= (TextMessage) msg;
requestData = textMessage.getText().toString();
}else if(msg instanceof ObjectMessage){
ObjectMessage objMsg = (ObjectMessage) msg;
requestData = objMsg.getObject().toString();
}
MessageProcessor msgProcessor = new MessageProcessor(_queueName, requestData);
executor.submit(msgProcessor);
} catch (JMSException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
private void executeRequest(Message msg){
String requestData=null;
try {
if(msg instanceof TextMessage){
TextMessage textMessage= (TextMessage) msg;
requestData = textMessage.getText().toString();
}else if(msg instanceof ObjectMessage){
ObjectMessage objMsg = (ObjectMessage) msg;
requestData = objMsg.getObject().toString();
}
// MessageExecutor objMessageExecutor=new MessageExecutor(_queueName);
myActor.tell(requestData, ActorRef.noSender());
} catch (JMSException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
使用ExecutorService执行ProcessRequst方法时,此代码工作正常。然而,面对akka actor系统实现的问题。
Exception in thread "Thread-4" java.lang.NullPointerException
at com.syn.jms.listener.QueueListener.executeRequest(QueueListener.java:102)
at com.syn.jms.listener.QueueListener.onMessage(QueueListener.java:59)
at org.apache.qpid.amqp_1_0.jms.impl.SessionImpl$Dispatcher.run(SessionImpl.java:942)
at java.lang.Thread.run(Thread.java:745)
请注意我使用Apache qpid APi与activeMQ进行AMQP协议。
我无法理解这个问题。
答案 0 :(得分:1)
我找到了解决方案,这是由于Actor ref的NPE,同时处理多个输入,每个进程队列都有唯一的actorRef,而且它没有初始化对象。我找到了这个解决方案。
public QueueListener(String actorId,String qName){
this._queueName = qName;
if(!isActorinit){
system=ActorSystem.create(actorId);
isActorinit=true;
}
myActor=system.actorOf( Props.create(MessageExecutor.class, qName),qName);
}
然而,我建议您接触我的解决方案。 Thnaks
答案 1 :(得分:-1)
创建actor需要很少的时间,在创建actor期间,如果你收到消息进行处理,你将获得空指针异常。
在向其发送消息之前,您可能需要检查'myActor'是否为null。或者您可以考虑使用actor生命周期事件来开始处理消息。