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

上一篇文章中,介绍了如何在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中创建两个队列每个客户端对应一个队列,两个客户端分别向对方队列发送消息并从自己的队列中获取消息。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,397评论 19 139
  • ActiveMQ 即时通讯服务 浅析http://www.cnblogs.com/hoojo/p/active_m...
    bboymonk阅读 5,362评论 0 11
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,054评论 6 342
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,930评论 18 399
  • 一. Java基础部分.................................................
    wy_sure阅读 9,246评论 0 11