package com.rox;
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import EDU.oswego.cs.dl.util.concurrent.CountDown;
/**
* A complete JMS client example program that sends a
*
* TextMessage to a Queue and asynchronously receives the
*
* message from the same Queue.
*
*
* @author
[email protected]
*
* @version $Revision:$
*
*/
public class SendRecvClient
{
static CountDown done = new CountDown(1);
QueueConnection conn;
QueueSession session;
Queue que;
public static class ExListener implements MessageListener
{
public void onMessage(Message msg)
{
done.release();
TextMessage tm = (TextMessage) msg;
try
{
System.out.println("onMessage, recv text="
+ tm.getText());
}
catch (Throwable t)
{
t.printStackTrace();
}
}
}
public void setupPTP()
throws JMSException, NamingException
{
Properties environment = new Properties();
environment.put(Context.PROVIDER_URL, "localhost:1099");
environment.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
InitialContext iniCtx = new InitialContext(environment);
Object tmp = iniCtx.lookup("ConnectionFactory");
QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
conn = qcf.createQueueConnection();
que = (Queue) iniCtx.lookup("queue/testQueue");
session = conn.createQueueSession(false,
QueueSession.AUTO_ACKNOWLEDGE);
conn.start();
}
public void sendRecvAsync(String text)
throws JMSException, NamingException
{
System.out.println("Begin sendRecvAsync");
// Setup the PTP connection, session
setupPTP();
// Set the async listener
QueueReceiver recv = session.createReceiver(que);
recv.setMessageListener(new ExListener());
// Send a text msg
QueueSender send = session.createSender(que);
TextMessage tm = session.createTextMessage(text);
send.send(tm);
System.out.println("sendRecvAsync, sent text="
+ tm.getText());
send.close();
System.out.println("End sendRecvAsync");
}
public void stop() throws JMSException {
conn.stop();
session.close();
conn.close();
}
public static void main(String args[]) throws Exception
{
SendRecvClient client = new SendRecvClient();
client.sendRecvAsync("A text msg");
client.done.acquire();
client.stop();
System.exit(0);
}
}
红色部分根据需要添加.如果修改默认配置可以查看{JBOSS_HOME}/server/..../deploy/jms下相应的配置文件.
Scott.Stark说了: In the P2P model, a sender delivers messages to a queue and a single receiver pulls the message off of the queue. The receiver does not need to be listening to the queue at the time the message is sent.
在点对点模式中,接收端不需要在发送方发送的时候监听.