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閱讀 134,923評論 18 139
  • ActiveMQ 即時通訊服務 淺析http://www.cnblogs.com/hoojo/p/active_m...
    bboymonk閱讀 1,515評論 0 11
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,954評論 6 342
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,765評論 18 399
  • 一. Java基礎部分.................................................
    wy_sure閱讀 3,835評論 0 11