行状态。)
好了,现在我们开始建立示例发送程序和接收程序了:
// SimpleSender.java
import java.util.Properties;
import javax.jms.*;
import javax.naming.*;
public class SimpleSender {
public static void main(String argv[]) {
new SimpleSender();
}
public SimpleSender() {
try {
QueueConnectionFactory myQConnFactory;
Queue myQueue;
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
properties.put(Context.PROVIDER_URL, "localhost");
Context ctx = new InitialContext(properties);
myQConnFactory = (QueueConnectionFactory)ctx.lookup
("UIL2ConnectionFactory");
myQueue = (Queue) ctx.lookup("queue/testQueue");
ctx.bind ("SimpleSender", myQueue);
QueueConnection con = myQConnFactory.createQueueConnection();
QueueSession session = con.createQueueSession(false,
Session.AUTO_ACKNOWLEDGE);
TextMessage textMessage = session.createTextMessage();
QueueSender sender = session.createSender(myQueue);
con.start();
for (int i=0; i<10; i++) {
textMessage.setText("Hello World #" + i);
sender.send(textMessage);
}
con.close();
ctx.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
利用JMS建立消息传递系统(4)
时间:2010-05-21
我们有两种接收消息的途径。第一种是使用javax.jms.QueueReceiver的receive()方法向队列同步请求消息。这可能阻塞接收程序,直到它不接收消息为止,或者如何某个消息没有在特定的时间间隔内到达而返回超时操作。第二种是一旦可以访问消息了就异步接收消息,使用javax.jms.MessageListener调用onMessage()方法,它会处理消息的内容。
建立接收程序的很多步骤与建立发送程序的步骤类似:
// SyncReceiver.java
import java.util.Properties;
import javax.jms.*;
import javax.naming.*;
public class SyncReceiver {
public static void main(String argv[])
{
new SyncReceiver();
}
public SyncReceiver() {
try {
QueueConnectionFactory myQConnFactory;
Queue myQueue;
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.interfaces.NamingContextFactory");
properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
properties.put(Context.PROVIDER_URL, "localhost");
Context ctx = new InitialContext(properties);
myQConnFactory = (QueueConnectionFactory)ctx.lookup("UIL2ConnectionFactory");
myQueue = (Queue) ctx.lookup("queue/testQueue");
ctx.bind("SyncReceiver", myQueue);
QueueConnection con = myQConnFactory.createQueueConnection();
QueueSession session = con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
QueueReceiver
|