针对好多朋友,想熟悉JMS相关开发知识,网上例子写的也比较乱,特手动编写了一个例子和服务器配置,希望大家喜欢,支持我
1) jboss配置Queue消息队列
打开jboss安装目录,找到server/default/deploy/jms下找到文件jbossmq-destinations-service.xml文件
增加配置代码如下:
<mbean code="org.jboss.mq.server.jmx.Queue"
name="jboss.mq.destination:service=Queue,name=testQueue">
<depends optional-attribute-name="DestinationManager">jboss.mq:service=DestinationManager</depends>
</mbean>
启动jboss在jmx-console下,即可查询发布testQueue队列成功的消息,很简单
2)开发发送客户端,拷贝jboss目录下client文件夹下的jbossall-client.jar到项目lib下,编写代码如下
import java.util.Properties;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JmsSender {
public static void main(String[] args) throws JMSException, NamingException {
Properties env = new Properties();
env.put(Context.PROVIDER_URL, "127.0.0.1:1099");
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.inte易做图ces.NamingContextFactory");
env.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.inte易做图ces");
Context context = new InitialContext(env);
QueueConnectionFactory factory = (QueueConnectionFactory)context.lookup("ConnectionFactory");
QueueConnection queueConnection = factory.createQueueConnection();
QueueSession queueSession = queueConnection.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
Queue queue = (Queue) context.lookup("queue/testQueue");
TextMessage message = queueSession.createTextMessage();
message.setText("ddddd");
QueueSender queueSender = queueSession.createSender(queue);
queueSender.send(queue, message);
System.out.println("-------------");
}
}
开发完毕,很简单
3)接收消息端打开如下
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JmsReader {
public static void main(String[] args) throws JMSException, NamingException {
Properties env = new Properties();
env.put(Context.PROVIDER_URL, "localhost:1099");
env.put(Context.INITIAL_CONTEXT_FACTORY,
"org.jnp.inte易做图ces.NamingContextFactory");
env.put(Context.URL_PKG_PREFIXES,
"org.jboss.naming:org.jnp.inte易做图ces");
/*
* 利用参数连接好服务器
*/
InitialContext ic = new InitialContext(env);
QueueConnection cs = ((QueueConnectionFactory) ic
.lookup("ConnectionFactory")).createQueueConnection();
/*
* 配置并连接相应的queue
*/
Queue q = (Queue) ic.lookup("queue/testQueue");
QueueSession qss = cs.createQueueSession(false,QueueSession.AUTO_ACKNOWLEDGE);
QueueReceiver qr = qss.createReceiver(q);
/*
* 启动链接
*/
cs.start();
/*
* 开始接受,然后处理接收到的 message
*/
TextMessage message=(TextMessage)qr.receive();
System.out.println(message.getText());
cs.close();
}
}