虽然activemq+jencks的jms轻量级解决方案已经很好地在psa中work了,尤其spring的JmsTemplate使得代码更简单,但是还是存在问题。
问题来自暑期做psa的时候,linke突然提出要求,需要MDP返回些处理信息,比如处理结果、异常,以便后台监控和前台显示,但是,MDP没有返回值也没法返回异常,当时我只能无奈。
在下载了lingo-1.0-M1后(虽然1.2.1发布了,但是还没有文档支持,所以暂且用1.0),参考其自带的example,了解了它异步函数调用的代码思路。
callback实现了EventListener,提供了返回值和异常的接口,另外涉及到两个方面,首先,callback本身需要轮询,其次,callback可以由实例池管理。
第二个方面并没有利用实例池,而是利用ThreadPoolExecutor来newFixedThreadPool,管理不同的异步调用线程,来完成对callback的调度。
encoding="UTF-8"?>
BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
class="org.activemq.spring.BrokerFactoryBean">
<property name="config"
value="classpath:activemq.xml"
/>
</bean>
class="org.activemq.ActiveMQConnectionFactory">
<property
name="brokerURL">
<value>tcp://localhost:61616</value>
</property>
</bean>
class="org.activemq.message.ActiveMQQueue">
<constructor-arg
index="0">
<value>lingo.demo</value>
</constructor-arg>
</bean>
id="invocationFactory"
class="org.logicblaze.lingo.LingoRemoteInvocationFactory">
<constructor-arg>
<bean
class="org.logicblaze.lingo.SimpleMetadataStrategy">
<!-- 允许单向异步调用
-->
<constructor-arg
value="true" />
</bean>
</constructor-arg>
</bean>
<bean id="client"
class="org.logicblaze.lingo.jms.JmsProxyFactoryBean">
<property name="serviceInterface"
value="org.openepo.jms.lingo.MailService"
/>
<property name="connectionFactory"
ref="jmsFactory" />
<property name="destination"
ref="destination" />
-->
<property
name="remoteInvocationFactory"
ref="invocationFactory" />
</bean>
<bean id="server"
class="org.logicblaze.lingo.jms.JmsServiceExporter">
<property name="service"
ref="serverImpl" />
<property name="serviceInterface"
value="org.openepo.jms.lingo.MailService"
/>
<property name="connectionFactory"
ref="jmsFactory" />
<property name="destination"
ref="destination" />
<property name="invocationFactory"
ref="invocationFactory" />
</bean>
<bean id="serverImpl"
class="org.openepo.jms.lingo.MailServiceImpl"
/>
-->
<bean id="asyncManager"
class="org.openepo.jms.lingo.AsyncManager"
singleton="false">
<property name="mailClient" ref="client"
/>
<property name="threadSize" value="5"
/>
</bean>
public void onResult(Object result);
public void stop();
public void onException(Exception e);
}
import java.util.List;
{
private List results = new ArrayList();
private Object semaphore = new Object();
private boolean stopped;
private Exception onException;
private long waitTime = 1000;
public synchronized void onResult(Object result)
{
results.add(result);
synchronized (semaphore) {
semaphore.notifyAll();
}
}
// lifecycle end methods
public void stop() {
stopped = true;
}
{
onException = e;
}
{
return
onException;
}
{
return results;
}
{
return stopped;
}
messageCount) {
System.out.println("Waiting for: " + messageCount +
" responses to arrive");
System.currentTimeMillis();
< 10; i++) {
try {
if (hasReceivedResponses(messageCount))
{
break;
}
synchronized (semaphore) {
semaphore.wait(waitTime);
}
}
catch (InterruptedException e) {
System.out.println("Caught: " + e);
}
}
long end =
System.currentTimeMillis() - start;
System.out.println("End of wait for " + end + " millis");
}
{
return
results.isEmpty();
}
hasReceivedResponses(int messageCount) {
return results.size()
>= messageCount;
}
{
return waitTime;
}
{
this.waitTime =
waitTime;
}
}
public void
asyncSendMail(List<Mail> mails,
ResultListener listener);
}
{
asyncSendMail(List<Mail> mails,
ResultListener listener) {
try {
for (Mail mail : mails) {
sendMail(mail);
Thread.sleep(2000);// 服务端时耗
listener.onResult(mail.getContent() +
" Sended Successfully.");
}
listener.stop();
} catch
(Exception e) {
listener.onException(e);
}
}
Exception {
// 可以取消下面的注释来查看服务端将异常传给客户端
//throw new Exception("Error occurs
on server side.");
}
}
{
private static final long serialVersionUID = 1L;
private String content;
public String getContent() {
return content;
}
{
this.content = content;
}
this.content = content;
}
}
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
10; //callback池大小
(ThreadPoolExecutor) Executors
.newFixedThreadPool(threadSize); //callback池
{
AsyncManager.threadSize = threadSize;
}
{
this.mailClient = mailClient;
}
}
List<Mail> mails)
{
final ResultListenerImpl callBack = new
ResultListenerImpl();
callBack.setWaitTime(2000);
// 异步调用
mailClient.asyncSendMail(mails, callBack);
executor.execute(new Runnable()
{
public void run() {
// callBack 阻塞等待n个消息
callBack.waitForAsyncResponses(mails.size());
// 服务端异常
System.out.println("Server
Exception: "
+
callBack.getOnException().getMessage());
} else
{
// 得到服务端处理结果,打印结果
for (Object result :
callBack.getResults())
{
System.out.println("Result:
" + result);
}
}
}
});
}
}
上面匿名类的run方法中,在callback的waitForAsyncResponses方法结束后,可以检查callback中的信息,进行异常处理等。
@Test
public void test() {
List<Mail> mails = new
ArrayList<Mail>();
mails.add(new Mail("mail1"));
mails.add(new Mail("mail2"));
long startTime = System.currentTimeMillis();
try {
// 异步调用
asyncManager.sendMails(mails);
System.out.println("Cost time "
+ (System.currentTimeMillis() -
startTime) + "ms");
//为查看结果,sleep主线程
Thread.sleep(10000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
多出了许多代码,自然复杂度有所增加,但是lingo-1.2.1后,增加了annotation,减少了callback的代码量。