Posted on 2006-07-27 15:17
Earth 阅读(234)
评论(0) 编辑 收藏 所属分类:
JavaEE5/EJB3
一、定义服务接口,并用@Producer标注
Calculator.java
package
trail.mdpojo;
import
org.jboss.annotation.ejb.Producer;
@Producer
public
interface
Calculator {
public
void
doCalculation (
long
sent,
int
start,
int
end,
double
growthrate,
double
saving);
}
二、定义服务实现,并用@Consumer标注,同MDB一样,如果所监听的消息队列不存在,JBoss会自动创建一个,不需要任何XML配置文件
MdpojoCalculator.java
package
trail.mdpojo;
import
org.jboss.annotation.ejb.Consumer;
import
javax.ejb.
*
;
import
java.sql.Timestamp;
@Consumer(activationConfig
=
{
@ActivationConfigProperty(propertyName
=
"
destinationType
"
,
propertyValue
=
"
javax.jms.Queue
"
),
@ActivationConfigProperty(propertyName
=
"
destination
"
,
propertyValue
=
"
queue/mdpojo
"
)
})
public
class
MdpojoCalculator
implements
Calculator {
public
void
doCalculation (
long
sent,
int
start,
int
end,
double
growthrate,
double
saving) {
double
result
=
calculate (start, end, growthrate, saving);
RecordManager.addRecord (
new
Timestamp(sent), result);
System.out.println (
"
The MD POJO is invoked
"
);
}
//
}
三、Message Driven POJOs的使用
如果要使用MDPOJO,你首先需要从JNDI中查找@Producer接口所对应的stub object,
这个stub object实现了Producer接口的同时还实现了ProducerObject接口。你需要用ProducerObject.getProducerManager()得到一个ProducerManager然后调用manager.connect().它会创建一个JMS连接。接下来就可以使用@Producer中定义的服务了。
calculator.jsp
<%
@ page
import
=
"
trail.mdpojo.*, javax.naming.*, java.text.*,
org.jboss.ejb3.mdb.
*
"
%>
<%
if
(
"
send
"
.equals(request.getParameter (
"
action
"
))) {
int
start
=
Integer.parseInt(request.getParameter (
"
start
"
));
int
end
=
Integer.parseInt(request.getParameter (
"
end
"
));
double
growthrate
=
Double.parseDouble(request.getParameter (
"
growthrate
"
));
double
saving
=
Double.parseDouble(request.getParameter (
"
saving
"
));
//
The sent timestamp acts as the message's ID
long
sent
=
System.currentTimeMillis();
Calculator cal
=
null
;
ProducerManager manager
=
null
;
try
{
InitialContext ctx
=
new
InitialContext();
cal
=
(Calculator) ctx.lookup(
Calculator.
class
.getName());
//
cal = (Calculator) ctx.lookup(
//
"EJB3Trail/MdpojoCalculator/remote");
ProducerObject po
=
(ProducerObject) cal;
manager
=
po.getProducerManager();
}
catch
(Exception e) {
e.printStackTrace ();
}
manager.connect();
//
internally create a JMS connection
try
{
cal.doCalculation(sent, start, end,
growthrate, saving);
}
finally
{
manager.close();
//
clean up the JMS connection
}
%>