美文网首页
JMS系列(二)-java操作JMS Queue实例

JMS系列(二)-java操作JMS Queue实例

作者: 阿三君 | 来源:发表于2017-10-15 15:35 被阅读0次

    上一篇文章中,介绍了如何在weblogic中创建jms相关资源,下面要介绍如何通过java向jms队列中写入消息以及如何从jms队列中取出消息。
    要使用weblogic的jms,需要引入以下两个包

    • javax.jms.jar
    • wlfullclient.jar
      如果是使用jdeveloper开发,直接引入以下两个Library即可

    消息发送

    java将消息发送到消息队列中,需要经过以下步骤

    • 连接jms服务器
    • 获取连接工厂(Connection Factory)
    • 通过连接工厂创建队列连接(QueueConnection)
    • 通过队列连接创建队列会话(QueueSession)
    • 通过队列会话创建队列生产者(Sender/Product)
    • 创建消息(Message)
    • 通过生产者将消息发送到队列中
      具体代码实现:
    package asan.demo.jms;
    import java.util.Hashtable;
    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 {
        private QueueSender sender = null;
        private QueueSession session = null;
        private static final String JMS_FACTORY_JNDI = "jms/jms_test_connection_factory1";
        private static final String JMS_QUEUE_JNDI = "jms/jms_test_queue";
    
        public JMSSender() {
            super();
        }
    
        public void sendMessage(String msg) {
            TextMessage textMsg;
            try {
                if (this.sender == null) {
                    this.init();
                }
                textMsg = session.createTextMessage();
                textMsg.setText(msg);
                sender.send(textMsg);
            } catch (JMSException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    //    1. 连接jms服务器
    //    2. 获取连接工厂(Connection Factory)
    //    3. 通过连接工厂创建队列连接(QueueConnection)
    //    4. 通过队列连接创建队列会话(QueueSession)
    //    5. 通过队列会话创建队列生产者(Sender/Product)
    //    6. 创建消息(Message)
    //    7. 通过生产者将消息发送到队列中
        private void init() throws NamingException, JMSException {
            Hashtable properties = new Hashtable();
            properties.put(Context.INITIAL_CONTEXT_FACTORY,
                           "weblogic.jndi.WLInitialContextFactory");
            properties.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
            properties.put(Context.SECURITY_PRINCIPAL, "weblogic");
            properties.put(Context.SECURITY_CREDENTIALS, "weblogic1");
            InitialContext ctx = new InitialContext(properties);
            QueueConnectionFactory jmsFactory =
                (QueueConnectionFactory)ctx.lookup(JMS_FACTORY_JNDI);
            QueueConnection jmsConn = jmsFactory.createQueueConnection();
            session = jmsConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = (Queue)ctx.lookup(JMS_QUEUE_JNDI);
            sender = session.createSender(queue);
        }
        
        public static void main(String[]cmd){
            JMSSender sender=new JMSSender();
            sender.sendMessage("hello world");
        }
    }
    

    运行程序后登录console,进入domain->Services->Messaging->JMS Module->jms_test_module->jms_test_queue在Monitoring页面可以看到队列中增加一条消息,点击Show Messages可以查看消息详细内容

    消息接收

    java从消息队列中获取消息,需要经过以下步骤

    • 连接jms服务器
    • 获取连接工厂(Connection Factory)
    • 通过连接工厂创建队列连接(QueueConnection)
    • 通过队列连接创建队列会话(QueueSession)
    • 通过队列会话创建队列消费者(Reciver/Consumer)
    • 接收消息(Message)

    和消息发送到步骤差不多。
    具体代码实现:

    package asan.demo.jms;
    
    import java.util.Hashtable;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageConsumer;
    import javax.jms.Queue;
    import javax.jms.QueueConnection;
    import javax.jms.QueueConnectionFactory;
    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 JMSReciver {
        private MessageConsumer reciver = null;
        private static final String JMS_FACTORY_JNDI = "jms/jms_test_connection_factory1";
        private static final String JMS_QUEUE_JNDI = "jms/jms_test_queue";
        public JMSReciver() {
            super();
        }
        public void reciveMessage() {
            try {
                if (this.reciver == null) {
                    this.init();
                }
                System.out.println("waiting to recive message from jms queue "+JMS_QUEUE_JNDI);
                while(true){
                    Message msg=reciver.receive();
                    if(msg instanceof TextMessage){
                        TextMessage textMsg=(TextMessage)msg;
                        System.out.println("recive jms message:"+textMsg.getText());
                    }
                }
            } catch (JMSException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        //    1. 连接jms服务器
        //    2. 获取连接工厂(Connection Factory)
        //    3. 通过连接工厂创建队列连接(QueueConnection)
        //    4. 通过队列连接创建队列会话(QueueSession)
        //    5. 通过队列会话创建队列消费者(Reciver/Consumer)
        //    6. 接收消息(Message)
        private void init() throws NamingException, JMSException {
            Hashtable properties = new Hashtable();
            properties.put(Context.INITIAL_CONTEXT_FACTORY,
                           "weblogic.jndi.WLInitialContextFactory");
            properties.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
            properties.put(Context.SECURITY_PRINCIPAL, "weblogic");
            properties.put(Context.SECURITY_CREDENTIALS, "weblogic1");
            InitialContext ctx = new InitialContext(properties);
            QueueConnectionFactory jmsFactory =
                (QueueConnectionFactory)ctx.lookup(JMS_FACTORY_JNDI);
            QueueConnection jmsConn = jmsFactory.createQueueConnection();
            QueueSession session = jmsConn.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            Queue queue = (Queue)ctx.lookup(JMS_QUEUE_JNDI);
            reciver = session.createReceiver(queue);
            jmsConn.start();
        }
        
        public static void main(String[]cmd){
            JMSReciver consumer=new JMSReciver();
            consumer.reciveMessage();
        }
    }
    

    运行程序,控制台打印出队列中消息

    JMS客户端

    为了更清楚了解jms消息发送过程,这边写了一个客户端,该客户端有两种模式,当作为生产者可以在控制台输入消息发送到消息队列中,当作为消费者,一旦消息队列中有消息产生,立刻将消息打印到控制台。
    客户端代码如下:

    package asan.demo.jms;
    
    import java.util.Scanner;
    
    public class JMSClient {
        public JMSClient() {
            super();
        }
    
        public static void help() {
            System.out.println("Usage:java -jar JMSClient.jar sender/reciver");
            System.out.println("sender:向jms队列发送消息");
            System.out.println("reciver:从队列中取出消息");
        }
    
        public static void main(String[] cmd) {
            if (cmd.length == 0) {
                help();
                return;
            }
            String mode = cmd[0];
            if ("sender".equalsIgnoreCase(mode)) {
                JMSSender sender = new JMSSender();
                Scanner sc = new Scanner(System.in);
                System.out.println("input you message(input end to exit):");
                while (true) {
                    String msg = sc.nextLine();
                    if ("end".equalsIgnoreCase(msg)) {
                        return;
                    }
                    sender.sendMessage(msg);
                }
            } else {
                JMSReciver consumer = new JMSReciver();
                consumer.reciveMessage();
            }
        }
    }
    

    将代码打包(关于如何打包参考这篇文章),jar名称为JMSClient.jar,执行以下命令将客户端作为生产者运行

    java -jar JMSClient.jar sender
    

    重新打开一个控制台,执行以下命令将客户端作为消费者运行

    java -jar JMSClient.jar reciver
    

    在第一个控制台中输入消息,消息立马在第二个控制台输出


    程序稍加改造就能变成一个实时点对点聊天程序,思路是在weblogic中创建两个队列每个客户端对应一个队列,两个客户端分别向对方队列发送消息并从自己的队列中获取消息。

    相关文章

      网友评论

          本文标题:JMS系列(二)-java操作JMS Queue实例

          本文链接:https://www.haomeiwen.com/subject/qyvfuxtx.html