JMS发送消息工具类MsgQueueSender

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cbjcry/article/details/84552675

JMS工厂和队列JNDI配在配置文件jmsqueue.properties里,内容如下:

connectionFactoryName=ConnectionFactory
queueName=/queues/InstanceQueue

 工具类:

package com.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.naming.InitialContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 目的:读取jmsqueue.properties中消息队列的信息,初始化消息队列,提供发送消息的函数
*
 */
public class MsgQueueSender {
	
	private static final Logger logger = LoggerFactory.getLogger(MsgQueueSender.class);

	private static final MsgQueueSender ms = new MsgQueueSender();
	private Properties info = new Properties();

	/**
	 * jms
	 */
	private QueueConnection conn;
	
	private Queue que;

	private MsgQueueSender() {
		initJMSInfo();
		initMsgQueue();
	}

	/**
	 * 初始化jndi队列
	 * 
	 */
	private void initMsgQueue() {
		
		InitialContext iniCtx;
		try {
			iniCtx = new InitialContext();
			//获取工厂
			Object tmp = iniCtx.lookup(info.getProperty("connectionFactoryName", "ConnectionFactory"));
			QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
			//获取连接
			conn = qcf.createQueueConnection();
			//获取队列
			que = (Queue) iniCtx.lookup(info.getProperty("queueName", "/queues/InstanceQueue"));
			conn.start();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 读取jms配置(包括工厂和队列JNDI)
	 */
	private void initJMSInfo() {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream("jmsqueue.properties");
		if (is != null) {
			try {
				info.load(is);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public static MsgQueueSender getInstance() {
		return ms;
	}
	
	public void sendTextMsg(String msg) throws JMSException{
		QueueSession session = conn.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
    	session.createSender(que).send(session.createTextMessage(msg));
    	session.close();
    }
	
	public void sendObjMsg(Serializable obj) throws JMSException{
		QueueSession session = conn.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
		session.createSender(que).send(session.createObjectMessage(obj));
		session.close();
	}

}

 调用:

try {
			MsgQueueSender.getInstance().sendTextMsg("Hello world!");
		} catch (JMSException e) {
			e.printStackTrace();
		}

 。。

 

 

 

展开阅读全文

没有更多推荐了,返回首页