jms实例(spring整合)
消息发送:
package com.main;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.ibm.mq.jms.MQConnection;
import com.ibm.mq.jms.MQConnectionFactory;
import com.ibm.mq.jms.MQDestination;
import com.ibm.mq.jms.MQMessageProducer;
import com.ibm.mq.jms.MQQueue;
import com.ibm.mq.jms.MQSession;
/**
* 使用JMS发送消息
*
* @author
*/
public class JmsSend
{
/**
* 链接工厂
*/
private MQConnectionFactory mqfactory;
public JmsSend()
{
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]
{
"applicationContext.xml"
});
BeanFactory factory = (BeanFactory)context;
mqfactory = (MQConnectionFactory)factory.getBean("jmsConnectionFactory");
}
/**
*
*/
public void sendData()
{
MQConnection connection = null;
MQSession session = null;
MQMessageProducer producer = null;
try
{
// 创建连接
connection = (MQConnection)mqfactory.createConnection();
connection.start();
// 创建一个Session
session = (MQSession)connection.createSession(false, MQSession.AUTO_ACKNOWLEDGE);
MQDestination destination = new MQQueue("default");
// 创建一个生产者,发送消息
producer = (MQMessageProducer)session.createProducer(destination);
Random r = new Random();
for (int i = 0; i < 100; i++)
{
String message = "放置消息开始!" + r.nextInt(100);
BytesMessage bMessage = session.createBytesMessage();
bMessage.writeBytes(message.getBytes("utf-8"));
producer.send(bMessage);
}
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException("UnsupportedEncodingException", e);
}
catch (JMSException e)
{
throw new RuntimeException("JMSException", e);
}
finally
{
try
{
producer.close();
}
catch (JMSException e)
{
}
try
{
session.close();
}
catch (JMSException e)
{
}
try
{
connection.close();
}
catch (JMSException e)
{
}
}
}
public static void main(String[] args) throws InterruptedException
{
JmsSend send = new JmsSend();
try
{
send.sendData();
}
catch (Exception e)
{
// 处理异常的code,略
}
}
}