JAVA连接MQ代码_Java连接MQ的实例

package cjf.mq.mqclient;

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;

import com.ibm.mq.MQGetMessageOptions;

public class MQClient {

static MQQueueManager qMgr;

static int CCSID = 1381;//WINGBK,1208:UTF-8

static String queueString = "MQ_QUEUE";

public static void connect() throws MQException {

MQEnvironment.hostname = "";

MQEnvironment.channel = "java.channel";

MQEnvironment.port = 1321;

MQEnvironment.CCSID = CCSID;

qMgr = new MQQueueManager("MQ_TEST");

qMgr.disconnect();

}

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);

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.readLine());

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("fuck MQ");

receiveMsg();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值