最近做了一个java连接MQ分发消息的的一个小程序,下面是程序代码:
package cn.gov.zjport.khi.dispatcher.mq;
/*
* 子系统名称 : KHI
* 版本信息 : 1.00
* 新建日期 : 2015-3-18 下午11:05:11
* 作者 :乐乐
* 修改历史(修改者):
* Copyright (c) zjport Co., Ltd. 2006. All rights reserved.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.ibm.mq.MQC;
import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.MQSimpleConnectionManager;
/**
*
* @Title: MqOperator.java
* @Description: TODO(MQ操作类)
* @author wull@zjport.gov.cn
* @date 2015-3-18 下午12:54:28
* @version V1.0
*/
public class MqManager {
private static final Logger logger = Logger.getLogger(MqManager.class);
private static final Map<String, MqManager> mqOperators = new HashMap<String, MqManager>();
/** MQ所在主机地址 */
private String hostName;
/** MQ侦听端口号 */
private int port;
/** MQ队列管理器服务器连接通道 */
private String serverChannel;
/** MQ队列管理器字符集 */
private int ccsid = 1381;
/** MQ队列管理器名称 */
private String queueManagerName;
/** MQ队列名称 */
private String queueName;
/** 队列管理器 */
private MQQueueManager mqQueueManager;
private MQSimpleConnectionManager myConnMan;
private MqManager() {
}
// 根据队列管理器名称获取MQ工具实例
public static MqManager getInstance(String id) {
if (id == null || "".equals(id.trim()))
return null;
if (mqOperators.get(id) == null) {
synchronized (id) {
if (mqOperators.get(id) == null) {
mqOperators.put(id, new MqManager());
}
}
}
return mqOperators.get(id);
}
// 获取队列管理器连接
public synchronized MQQueueManager getConnMQmanager() throws MQException {
if (mqQueueManager == null) {
// 链接队列管理器
connect();
} else {
try {
// 尝试获取队列管理器信息
mqQueueManager.getMaximumMessageLength();
} catch (MQException e) {
// 如果失败则重新连接
reconnect();
}
}
return mqQueueManager;
}
// 写入消息
public void put(String queueName, String message) throws IOException, MQException {
put(queueName, message, null);
}
// 写入消息
public void put(String message) throws IOException, MQException {
put(queueName, message, null);
}
// 写入消息
public void put(String message, byte[] messageId) throws IOException, MQException {
put(queueName, message, messageId);
}
// 写入消息
public void put(String queueName, String message, byte[] messageId) throws IOException, MQException {
MQQueue queue = mqQueueManager.accessQueue(queueName, MQC.MQOO_OUTPUT | MQC.MQOO_FAIL_IF_QUIESCING);
try {
putMessage(queue, message, messageId);
} finally {
queue.close();
}
}
// 读取消息
public List<String> get(byte[] messageId) throws IOException, MQException {
return get(queueName, 1, messageId);
}
// 读取消息
public List<String> get(String queueName, byte[] messageId) throws IOException, MQException {
return get(queueName, 1, messageId);
}
// 读取消息
public List<String> get(String queueName, int limitCount, byte[] messageId) throws IOException, MQException {
MQQueue queue = mqQueueManager.accessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT
| MQC.MQOO_INQUIRE);
try {
List<String> messages = getMessages(queue, limitCount, messageId);
return messages;
} finally {
queue.close();
}
}
// 读取消息
public List<String> get(int limitCount) throws IOException, MQException {
return get(queueName, limitCount);
}
// 读取消息
public List<String> get(String queueName, int limitCount) throws IOException, MQException {
return get(queueName, limitCount, null);
}
// 读取消息
public List<Map<String, String>> getMessageAndId(int limitCount) throws IOException, MQException {
return getMessageAndId(queueName, limitCount);
}
// 读取消息
public List<Map<String, String>> getMessageAndId(String queueName, int limitCount) throws IOException, MQException {
MQQueue queue = mqQueueManager.accessQueue(queueName, MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT
| MQC.MQOO_INQUIRE);
try {
List<Map<String, String>> messages = getMessages(queue, limitCount);
return messages;
} finally {
queue.close();
}
}
private List<Map<String, String>> getMessages(MQQueue queue, int limitCount) throws IOException, MQException {
List<Map<String, String>> result = new ArrayList<Map<String, String>>();
int deph = queue.getCurrentDepth();
if (deph > 0) {
logger.info("当前队列深度:" + deph);
}
/** 将队列里的消息读出来 */
while (deph-- > 0 && limitCount-- > 0) {
try {
/** 要读队列的消息 */
result.add(getMessage(queue));
} catch (MQException ex) {
if (ex.reasonCode != 2033) {
logger.error(ex);
break;
}
} catch (Exception e) {
e.printStackTrace();
break;
}
}
return result;
}
private Map<String, String> getMessage(MQQueue queue) throws MQException, IOException {
MQMessage retrievedMessage = new MQMessage();
retrievedMessage.format = MQC.MQFMT_STRING;
retrievedMessage.characterSet = 1200;
queue.get(retrievedMessage);
Map<String, String> result = new HashMap<String, String>();
result.put(new String(retrievedMessage.messageId).trim(),
retrievedMessage.readStringOfByteLength(retrievedMessage.getDataLength()));
return result;
}
// 关闭队列管理器链接
public void closeConnMQmanager() throws MQException {
if (mqQueueManager != null) {
if (mqQueueManager.isConnected()) {
mqQueueManager.disconnect();
if (myConnMan != null) {
myConnMan.setActive(MQSimpleConnectionManager.MODE_INACTIVE);
}
}
}
}
private void putMessage(MQQueue queue, String message, byte[] id) throws IOException, MQException {
/** 要写入队列的消息 */
MQMessage msg = new MQMessage();
msg.characterSet = 1381;
msg.encoding = 546;
msg.format = MQC.MQFMT_STRING;
/** 设置消息用不过期 */
msg.expiry = -1;
msg.messageId = id;
/** 将消息写入消息对象中 */
msg.writeString(message);
queue.put(msg);
}
private List<String> getMessages(MQQueue queue, int limitCount, byte[] id) throws IOException, MQException {
List<String> result = new ArrayList<String>();
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.options = MQC.MQGMO_LOGICAL_ORDER | MQC.MQGMO_ALL_MSGS_AVAILABLE | MQC.MQGMO_WAIT | MQC.MQGMO_SYNCPOINT
| MQC.MQGMO_FAIL_IF_QUIESCING;
gmo.matchOptions = MQC.MQMO_MATCH_GROUP_ID;
int deph = queue.getCurrentDepth();
// if (deph > 0) {
// logger.info("当前队列深度:" + deph);
// }
/** 将队列里的消息读出来 */
while (deph-- > 0 && limitCount-- > 0) {
try {
/** 要读队列的消息 */
result.add(getMessage(queue, gmo, id));
} catch (MQException ex) {
if (ex.reasonCode != 2033) {
logger.error(ex);
break;
}
} catch (Exception e) {
logger.error(e);
break;
}
}
return result;
}
/**
* 读取消息
*
* @param queue
* @param gmo
* @param id
* @return
* @throws MQException
* @throws IOException
*/
private String getMessage(MQQueue queue, MQGetMessageOptions gmo, byte[] id) throws MQException, IOException {
MQMessage retrievedMessage = new MQMessage();
retrievedMessage.characterSet = 1381;
// retrievedMessage.encoding = 540;
retrievedMessage.format = MQC.MQFMT_STRING;
if (id != null) {
retrievedMessage.messageId = id;
queue.get(retrievedMessage);
} else {
queue.get(retrievedMessage, gmo);
}
byte[] rawdata = new byte[retrievedMessage.getMessageLength()];
retrievedMessage.readFully(rawdata);
String message = new String(rawdata);
return message;
}
public void commit() {
try {
mqQueueManager.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void backout() {
try {
mqQueueManager.backout();
} catch (Exception e) {
e.printStackTrace();
}
}
// java连接字符集
private void connect() throws MQException {
MQEnvironment.hostname = this.hostName;
MQEnvironment.port = this.port;
MQEnvironment.channel = this.serverChannel;
MQEnvironment.CCSID = this.ccsid;
// 设置为客户端连接
MQEnvironment.properties.put(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
myConnMan = new MQSimpleConnectionManager();
myConnMan.setActive(MQSimpleConnectionManager.MODE_ACTIVE);
mqQueueManager = new MQQueueManager(queueManagerName, myConnMan);// MQQueueManager(queueManagerName,
// myConnMan);
if (mqQueueManager == null) {
logger.error("Mqmanage中的qMgr是null的");
} else {
logger.info("建立队列管理器连接!主机[" + MQEnvironment.hostname + "]队列管理器:[" + queueManagerName + "]");
}
}
private void reconnect() throws MQException {
logger.info("MQ队列管理器重连");
try {
closeConnMQmanager();
} catch (MQException e) {
logger.error("MQ重连过程中,无法关闭旧的MQ链接");
e.printStackTrace();
}
connect();
}
/** MQ所在主机地址 */
public void setHostName(String hostName) {
this.hostName = hostName;
}
/** MQ侦听端口号 */
public void setPort(int port) {
this.port = port;
}
/** MQ队列管理器名称 */
public void setQueueManagerName(String queueManagerName) {
this.queueManagerName = queueManagerName;
}
/** MQ队列管理器服务器连接通道 */
public void setServerChannel(String serverChannel) {
this.serverChannel = serverChannel;
}
/** MQ队列名称 */
public void setQueueName(String queueName) {
this.queueName = queueName;
}
/** MQ队列管理器字符集 */
public void setCcsid(int ccsid) {
this.ccsid = ccsid;
}
}