深入掌握J(rèn)MS(十二):MDB
在EJB3中,一個(gè)MDB(消息驅(qū)動(dòng)Bean)就是一個(gè)實(shí)現(xiàn)了MessageListener接口的POJO。下面就是一個(gè)簡(jiǎn)單的MDB。
@MessageDriven(activationConfig={
@ActivationConfigProperty(propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination",
propertyValue="queue/testQueue")})
public class SimpleMDB implements MessageListener {
public void onMessage(Message message) {
try {
System.out.println("Receive Message : " + ((TextMessage)message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
它要求必須標(biāo)注為@MessageDriven。它所監(jiān)聽(tīng)Destination通過(guò)標(biāo)注屬性來(lái)注入。
下面是一個(gè)發(fā)送消息的StatelessBean:
@Remote
public interface IMessageSender {
public void sendMessage(String content) throws Exception;
}
@Stateless
@Remote
public class MessageSender implements IMessageSender {
@Resource(mappedName="ConnectionFactory")
private ConnectionFactory factory;
@Resource(mappedName="queue/testQueue")
private Queue queue;
public void sendMessage(String content) throws Exception {
Connection cn = factory.createConnection();
Session session = cn.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(queue);
producer.send(session.createTextMessage(content));
}
}
這個(gè)EJB只有一個(gè)方法SendMessage。ConnectionFactory和Queue通過(guò)標(biāo)注注入。
接下來(lái)是客戶端:
public class MessageSenderClient {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
props.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.setProperty(Context.PROVIDER_URL, "localhost:2099");
Context context = new InitialContext(props);
IMessageSender messageSender = (IMessageSender) context.lookup("MessageSender/remote");
messageSender.sendMessage("Hello");
}
}
它通過(guò)JNDI查找到上面的EJB,然后調(diào)用sengMessage.
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。