一、准备工作
1.需要在mq服务器上新建一个队列管理器、一个发送队列、一个接收队列、一个服务器通道
2.启动队列管理器(SEND)
strmqm SEND
--启动监听(SL)
runmqlsr -m SL -p 1414 -t tcp &
--用户交互管理界面程序
runmqsc SEND
--创建本地队列
DEFINE QLOCAL (Q1)
--创建的服务器连接通道
DEFINE CHANNEL(C) CHLTYPE (SVRCONN) REPLACE
二、代码如下
package sim;
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.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
/**
* @author Administrator
*
*/
public class Mq_SEND2 {
static MQQueueManager qMgr;
static int CCSID = 1381;
//本地队列
static String queueString = "Q1";
public static void connect() throws MQException {
MQEnvironment.hostname = "9.1.77.196";
MQEnvironment.channel = "C";
MQEnvironment.port = 1414;
MQEnvironment.CCSID = CCSID;
// //MQ中拥有权限的用户名
// MQEnvironment.userID = "mqm";
// //用户名对应的密码
// MQEnvironment.password = "mqm";
qMgr = new MQQueueManager("SEND");
}
public static void sendMsg(String msgStr) {
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT | MQC.MQOO_INQUIRE;
MQQueue queue = null;
try {
// 建立Q1通道的连接
queue = qMgr.accessQueue(queueString, openOptions, null, null, null);
System.out.println("发送消息前的深度为:" queue.getCurrentDepth());
MQMessage msg = new MQMessage();// 要写入队列的消息
msg.format = MQC.MQFMT_STRING;
msg.characterSet = CCSID;
msg.encoding = CCSID;
// msg.writeObject(msgStr); //将消息写入消息对象中
msg.writeString(msgStr);
MQPutMessageOptions pmo = new MQPutMessageOptions();
msg.expiry = -1; // 设置消息用不过期
queue.put(msg, pmo);// 将消息放入队列
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (queue != null) {
try {
queue.close();
} catch (MQException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void receiveMsg() {
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT | MQC.MQOO_INQUIRE;
MQQueue queue = null;
try {
queue = qMgr.accessQueue(queueString, openOptions, null, null, null);
System.out.println("该队列当前的深度为:" queue.getCurrentDepth());
System.out.println("===========================");
int depth = queue.getCurrentDepth();
// 将队列的里的消息读出来
while (depth-- > 0) {
MQMessage msg = new MQMessage();// 要读的队列的消息
MQGetMessageOptions gmo = new MQGetMessageOptions();
queue.get(msg, gmo);
System.out.println("消息的大小为(字节):" msg.getDataLength());
System.out.println("消息的内容:\n" msg.readStringOfByteLength(msg.getDataLength()));
System.out.println("---------------------------");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (queue != null) {
try {
queue.close();
} catch (MQException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) throws MQException {
connect();
sendMsg("发送消息测试");
receiveMsg();
}
|