MQ 的基本操作(四)-用JMS实现MQ编程

四.用JMS实现MQ编程
上面我们说明了怎样用JMSAdmin Tool定义MQ对象的上下文。我们的最终目的是要用JMS来实现MQ编程,以实现在程序中对MQ队列进行收、发消息。所以,下面我们将重点讨论一下MQ的JMS实现。
如果您对JMS编程很熟悉,那么您也就会用JMS来实现MQ编程,因为用JMS来编写MQ程序与编写一般的JMS程序没有太大的差别。举个例子,当我们想发送一条消息到MQ的队列中,再从该队列中取回消息时,我们编程时主要有四个步骤。首先我们要初始化在程序中要用到的对象,然后才可以发送消息到队列中去,再就是收取消息,最后要清除那些永久对象。这些都和普通的JMS程序相当。程序的源代码如下:

import java.util.Hashtable;
import javax.jms.*;
import javax.naming.*;
import javax.naming.directory.*;

public class sample {
protected QueueConnectionFactory factory=null;
protected QueueConnection connection;
protected QueueSession queueSession;
protected TextMessage outMessage;
protected QueueSender queueSender;
protected QueueReceiver queueReceiver;

public static final String qcfLookup=”EXAMPLEQCF”;
public static final String qLookup=”EXAMPLEQL”;
public static final String icf = “com.sun.jndi.fscontext.RefFSContextFactory”;
public String url =”file:/d:/temp”;

public void sampleInit() throws Exception {
Hashtable environment = new Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, icf);
environment.put(Context.PROVIDER_URL, url);
environment.put(Context.REFERRAL, “throw”);
Context ctx=new InitialDirContext(environment);
factory = (QueueConnectionFactory)ctx.lookup(qcfLookup);
Queue q1=null;
q1=(Queue)ctx.lookup(qLookup);
connection = factory.createQueueConnection();
queueSession = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

queueSender = queueSession.createSender(q1);
queueSender.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
outMessage = queueSession.createTextMessage();
queueReceiver = queueSession.createReceiver(q1);
connection.start();
}
public void sendMessageOut(String message) throws JMSException {
outMessage.setText(message);
queueSender.send(outMessage);
}
public String receiveMessage() throws Exception{
return ((TextMessage)queueReceiver.receive()).getText();
}
public void sampleClose() throws JMSException {
queueSession.close();
connection.close();
}

public static void main(String[] args){
String rec;
sample sp = new sample();
try {
sp.sampleInit();
sp.sendMessageOut(“Hello World!”);
java.lang.Thread.sleep(4000);
rec=sp.receiveMessage();
System.out.println(“Receive text is : “+rec);
sp.sampleClose();
}catch(Exception e) {
e.printStackTrace();
}
}
}

以下文章点击率最高

Loading…

     

如果这文章对你有帮助,请扫左上角微信支付-支付宝,给于打赏,以助博客运营

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注