帶有ActiveMQ的JMS

帶有ActiveMQ的JMS

JMS是Java Message Service的縮寫,它提供了一種以松散耦合,靈活的方式集成應用程序的機制。 JMS以存儲和轉發的方式跨應用程序異步傳遞數據。 應用程序通過充當中介的MOM(面向消息的中間件)進行通信,而無需直接通信。

JMS體系結構

JMS的主要組件是:

  • JMS Provider:一種消息傳遞系統,它實現JMS接口并提供管理和控制功能
  • 客戶端:發送或接收JMS消息的Java應用程序。 消息發送者稱為生產者,而接收者稱為消費者
  • 消息:在JMS客戶端之間傳遞信息的對象
  • 受管對象:管理員為使用客戶端而創建的預配置JMS對象。

有幾種JMS提供程序可用,例如Apache ActiveMQ和OpenMQ。 在這里,我使用了Apache ActiveMQ。

在Windows上安裝和啟動Apache ActiveMQ

  1. 下載ActiveMQ Windows二進制分發版
  2. 將其提取到所需位置
  3. 使用命令提示符將目錄更改為ActiveMQ安裝文件夾中的bin文件夾,然后運行以下命令以啟動ActiveMQ
  4. activemq

啟動ActiveMQ之后,您可以使用http:// localhost:8161 / admin /訪問管理控制臺并執行管理任務

JMS消息傳遞模型

JMS具有兩種消息傳遞模型,即點對點消息傳遞模型和發布者訂戶消息傳遞模型。

點對點消息傳遞模型

生產者將消息發送到JMS提供程序中的指定隊列,并且只有一個監聽該隊列的使用者才能接收該消息。

示例1和示例2幾乎相似,唯一的區別是示例1在程序內創建隊列,示例2使用jndi.properties文件命名查找和創建隊列。

例子1

package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Producer {public Producer() throws JMSException, NamingException {// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryConnectionFactory conFactory = (ConnectionFactory) jndi.lookup('connectionFactory');Connection connection;// Getting JMS connection from the server and starting itconnection = conFactory.createConnection();try {connection.start();// JMS messages are sent and received using a Session. We will// create here a non-transactional session object. If you want// to use transactions you should set the first parameter to 'true'Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);Destination destination = (Destination) jndi.lookup('MyQueue');// MessageProducer is used for sending messages (as opposed// to MessageConsumer which is used for receiving them)MessageProducer producer = session.createProducer(destination);// We will send a small text message saying 'Hello World!'TextMessage message = session.createTextMessage('Hello World!');// Here we are sending the message!producer.send(message);System.out.println('Sent message '' + message.getText() + ''');} finally {connection.close();}}public static void main(String[] args) throws JMSException {try {BasicConfigurator.configure();new Producer();} catch (NamingException e) {e.printStackTrace();}}
}
package com.eviac.blog.jms;import javax.jms.*;import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.BasicConfigurator;public class Consumer {// URL of the JMS serverprivate static String url = ActiveMQConnection.DEFAULT_BROKER_URL;// Name of the queue we will receive messages fromprivate static String subject = 'MYQUEUE';public static void main(String[] args) throws JMSException {BasicConfigurator.configure();// Getting JMS connection from the serverConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);Connection connection = connectionFactory.createConnection();connection.start();// Creating session for seding messagesSession session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);// Getting the queueDestination destination = session.createQueue(subject);// MessageConsumer is used for receiving (consuming) messagesMessageConsumer consumer = session.createConsumer(destination);// Here we receive the message.// By default this call is blocking, which means it will wait// for a message to arrive on the queue.Message message = consumer.receive();// There are many types of Message and TextMessage// is just one of them. Producer sent us a TextMessage// so we must cast to it to get access to its .getText()// method.if (message instanceof TextMessage) {TextMessage textMessage = (TextMessage) message;System.out.println('Received message '' + textMessage.getText()+ ''');}connection.close();}
}

jndi.properties

# START SNIPPET: jndijava.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory# use the following property to configure the default connector
java.naming.provider.url = vm://localhost# use the following property to specify the JNDI name the connection factory
# should appear as. 
#connectionFactoryNames = connectionFactory, queueConnectionFactory, topicConnectionFactry# register some queues in JNDI using the form
# queue.[jndiName] = [physicalName]
queue.MyQueue = example.MyQueue# register some topics in JNDI using the form
# topic.[jndiName] = [physicalName]
topic.MyTopic = example.MyTopic# END SNIPPET: jndi
package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Producer {public Producer() throws JMSException, NamingException {// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryConnectionFactory conFactory = (ConnectionFactory) jndi.lookup('connectionFactory');Connection connection;// Getting JMS connection from the server and starting itconnection = conFactory.createConnection();try {connection.start();// JMS messages are sent and received using a Session. We will// create here a non-transactional session object. If you want// to use transactions you should set the first parameter to 'true'Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);Destination destination = (Destination) jndi.lookup('MyQueue');// MessageProducer is used for sending messages (as opposed// to MessageConsumer which is used for receiving them)MessageProducer producer = session.createProducer(destination);// We will send a small text message saying 'Hello World!'TextMessage message = session.createTextMessage('Hello World!');// Here we are sending the message!producer.send(message);System.out.println('Sent message '' + message.getText() + ''');} finally {connection.close();}}public static void main(String[] args) throws JMSException {try {BasicConfigurator.configure();new Producer();} catch (NamingException e) {e.printStackTrace();}}
}
package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;import org.apache.log4j.BasicConfigurator;public class Consumer {public Consumer() throws NamingException, JMSException {Connection connection;// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryConnectionFactory conFactory = (ConnectionFactory) jndi.lookup('connectionFactory');// Getting JMS connection from the server and starting it// ConnectionFactory connectionFactory = new// ActiveMQConnectionFactory(url);connection = conFactory.createConnection();// // Getting JMS connection from the server// ConnectionFactory connectionFactory = new// ActiveMQConnectionFactory(url);// Connection connection = connectionFactory.createConnection();try {connection.start();// Creating session for seding messagesSession session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);// Getting the queueDestination destination = (Destination) jndi.lookup('MyQueue');// MessageConsumer is used for receiving (consuming) messagesMessageConsumer consumer = session.createConsumer(destination);// Here we receive the message.// By default this call is blocking, which means it will wait// for a message to arrive on the queue.Message message = consumer.receive();// There are many types of Message and TextMessage// is just one of them. Producer sent us a TextMessage// so we must cast to it to get access to its .getText()// method.if (message instanceof TextMessage) {TextMessage textMessage = (TextMessage) message;System.out.println('Received message '' + textMessage.getText()+ ''');}} finally {connection.close();}}public static void main(String[] args) throws JMSException {BasicConfigurator.configure();try {new Consumer();} catch (NamingException e) {// TODO Auto-generated catch blocke.printStackTrace();}}
}

發布者訂閱者模型

發布者將消息發布到JMS提供程序中的指定主題,并且訂閱該主題的所有訂閱者都將收到該消息。 請注意,只有活動的訂戶才能收到該消息。

點對點模型示例

package com.eviac.blog.jms;import javax.jms.*;
import javax.naming.*;import org.apache.log4j.BasicConfigurator;import java.io.BufferedReader;
import java.io.InputStreamReader;public class DemoPublisherSubscriberModel implements javax.jms.MessageListener {private TopicSession pubSession;private TopicPublisher publisher;private TopicConnection connection;/* Establish JMS publisher and subscriber */public DemoPublisherSubscriberModel(String topicName, String username,String password) throws Exception {// Obtain a JNDI connectionInitialContext jndi = new InitialContext();// Look up a JMS connection factoryTopicConnectionFactory conFactory = (TopicConnectionFactory) jndi.lookup('topicConnectionFactry');// Create a JMS connectionconnection = conFactory.createTopicConnection(username, password);// Create JMS session objects for publisher and subscriberpubSession = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);TopicSession subSession = connection.createTopicSession(false,Session.AUTO_ACKNOWLEDGE);// Look up a JMS topicTopic chatTopic = (Topic) jndi.lookup(topicName);// Create a JMS publisher and subscriberpublisher = pubSession.createPublisher(chatTopic);TopicSubscriber subscriber = subSession.createSubscriber(chatTopic);// Set a JMS message listenersubscriber.setMessageListener(this);// Start the JMS connection; allows messages to be deliveredconnection.start();// Create and send message using topic publisherTextMessage message = pubSession.createTextMessage();message.setText(username + ': Howdy Friends!');publisher.publish(message);}/** A client can register a message listener with a consumer. A message* listener is similar to an event listener. Whenever a message arrives at* the destination, the JMS provider delivers the message by calling the* listener's onMessage method, which acts on the contents of the message.*/public void onMessage(Message message) {try {TextMessage textMessage = (TextMessage) message;String text = textMessage.getText();System.out.println(text);} catch (JMSException jmse) {jmse.printStackTrace();}}public static void main(String[] args) {BasicConfigurator.configure();try {if (args.length != 3)System.out.println('Please Provide the topic name,username,password!');DemoPublisherSubscriberModel demo = new DemoPublisherSubscriberModel(args[0], args[1], args[2]);BufferedReader commandLine = new java.io.BufferedReader(new InputStreamReader(System.in));// closes the connection and exit the system when 'exit' enters in// the command linewhile (true) {String s = commandLine.readLine();if (s.equalsIgnoreCase('exit')) {demo.connection.close();System.exit(0);}}} catch (Exception e) {e.printStackTrace();}}
}

參考: 和ActiveMQ JMS從我們JCG伙伴 Pavithra Siriwardena在EVIAC博客。


翻譯自: https://www.javacodegeeks.com/2012/07/jms-with-activemq.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/371712.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/371712.shtml
英文地址,請注明出處:http://en.pswp.cn/news/371712.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

矩陣分解 java_使用矩陣分解為推薦系統

矩陣分解假設“潛在因素”,例如對用戶的意大利食物的偏好和項目食物的意外性與矩陣中的評級有關 .因此,整個問題類型轉變為矩陣重構問題,存在許多不同的解決方案 . 一個簡單的,可能很慢的解決方案是(除了ALS和其他一些矩陣重建的可…

用戶故事排球教練助手

計劃:估計這個任務需要一周時間 需求分析:作為一名排球教練助手,我需要了解每場每位隊員的技術動作,每場比賽每位隊員的得分情況,以便教練更好的了解到每位隊員的發揮情況和特長。 設計文檔:用戶進入此界面…

TMS320DM642學習----第一篇(硬件連接)

DSP設備型號:SEED-DTK-VPM642(目前實驗室用途:視頻處理,圖像處理方向,預計搭載目標跟蹤以及云臺防抖等算法) 官網鏈接:http://www.seeddsp.com/index.php/Home/Product/detail/name/1/id/174.ht…

字符串內存內部

本文基于我對StackOverflow的回答 。 我正在嘗試解釋String類如何存儲文本,內部存儲和常量池如何工作。 這里要理解的要點是String Java對象與其內容– private value字段下的char[]之間的區別。 String基本上是char[]數組的包裝器,將其封裝并使其無法修…

關于inline-block 元素之間為何會產生間隔

關于inline-block 元素之間為何會產生間隔 現象&#xff1a; <body><input type"text"><input type"text"> </body> 在瀏覽器中的表現&#xff1a; 實時上不僅僅是 inline-block 會導致這種現象。 inline 也會導致。 那問題來了&a…

java 入參 是 枚舉_java 枚舉 參數傳遞

展開全部這樣做是不行的&#xff0c;原因是&#xff1a;Java中的對象實例化都是在堆中&#xff0c;如果是普通的類實例變量&#xff0c;比如在方法636f707962616964757a686964616f313333376166371中定義的普通類實例變量&#xff0c;傳到了方法2中&#xff0c;由于方法1和方法2…

loadView的使用總結

一、loadView 1. loadView什么時候被調用&#xff1f; 每次訪問UIViewController的view&#xff08;如 controller.view、self.view&#xff09;并且view為nil&#xff0c;loadView方法就會被調用 2. 有什么作用 loadView 方法是用來負責創建UIViewController的view 3. 默認實…

數據庫備份 java jar_Java實現數據庫備份并利用ant導入SQL腳本

?數據備份對于經常在運維部署方面的工作者來說&#xff0c;是一件相對簡單的事情&#xff0c;都可以通過某一個SQL工具進行備份&#xff0c;但是如果在項目運行當中&#xff0c;我們需要對數據進行實時&#xff0c;或者是每隔一星期&#xff0c;一個月&#xff0c;等等進行數據…

JSF簡單Ajax示例

今天&#xff0c;我們將看到一些使用JSF的Ajax簡單樣本。 如果要查看有關JSF / Web應用程序的其他文章&#xff0c;請單擊以下鏈接&#xff1a; 重定向后的JSF持久化對象和消息 &#xff0c; 使用JAAS和JSF進行用戶登錄驗證 &#xff0c; JSF&#xff1a;Converter and Bean Au…

常用的好用的window工具

1. FastStone Capture截圖錄屏軟件 百度軟件中心&#xff1a;http://rj.baidu.com/soft/detail/13504.html?ald 注冊企業版&#xff1a; 用戶名&#xff1a;c1ikm 注冊碼&#xff1a;AXMQX-RMMMJ-DBHHF-WIHTV 中文輸入亂碼解決方法&#xff1a; 2. Notepad文本編輯器&#xff…

表分區

http://www.cnblogs.com/leestar54/p/6225821.html轉載于:https://www.cnblogs.com/jouny/p/6262850.html

java飛鴿傳書_feige 飛鴿傳書源代碼java 實現不錯的聯系網絡編程的資料飛鴿傳書的GUI(java實現) - 下載 - 搜珍網...

我的飛鴿傳書/FileFilter.java我的飛鴿傳書/FileNameExtensionFilter.java我的飛鴿傳書/飛鴿傳書/classes/feige/About.class我的飛鴿傳書/飛鴿傳書/classes/feige/ConnectOthers$ReadMessageThread.class我的飛鴿傳書/飛鴿傳書/classes/feige/ConnectOthers.class我的飛鴿傳書…

JAXB和根元素

XmlRootElement是人們習慣于與JAXB&#xff08;JSR-222&#xff09;一起使用的注釋。 目的是將根元素與類唯一關聯。 由于JAXB類映射到復雜類型&#xff0c;因此一個類有可能對應于多個根元素。 在這種情況下&#xff0c;無法使用XmlRootElement &#xff0c;人們開始感到有些困…

python socket模塊實現udp通信_Python基于socket模塊實現UDP通信功能示例

Python基于socket模塊實現UDP通信功能示例本文實例講述了Python基于socket模塊實現UDP通信功能。分享給大家供大家參考&#xff0c;具體如下&#xff1a;一 代碼1、接收端import socket#使用IPV4協議&#xff0c;使用UDP協議傳輸數據ssocket.socket(socket.AF_INET, socket.SOC…

Hibernate緩存基礎知識

最近&#xff0c;我嘗試了休眠緩存。 在這篇文章中&#xff0c;我想分享我的經驗&#xff0c;并指出Hibernate Second Level Cache的一些細節。 在此過程中&#xff0c;我將指導您閱讀一些有助于實現緩存的文章。 讓我們從地面開始。 在休眠狀態下緩存 緩存功能旨在減少必要的…

TP3.2之WHERE組合條件處理

1、條件都是int類型&#xff1a; $User->where(type1 AND status1)->select(); 2、條件包含字符串類型&#xff1a; 使用3.1以上版本的話&#xff0c;使用字符串條件的時候&#xff0c;建議配合預處理機制&#xff0c;確保更加安全&#xff0c; $Model->where("i…

linux-ssh遠程后臺執行腳本-放置后臺執行問題(轉)

寫了一個監控負載的小腳本&#xff08;死循環&#xff0c;測試結束后再kill對應進程&#xff09;&#xff0c;因需要監控多臺服務器&#xff0c;所以在一臺服務器上使用ssh統一執行腳本遇到問題&#xff1a;使用ssh root172.16.146.20 /usr/local/luly/loadavg.sh 2 2 &執行…

python2.7輸入函數_Python2.7的用戶輸入函數有問題,無法讓這些輸入與程序一起工作...

我對python世界還是個新手&#xff0c;雖然我已經用php做了很多工作。。。這是我的案子。。。在我正在用python2.7為我的小程序編寫一些代碼。在在那個程序中&#xff0c;我需要2個用戶輸入&#xff0c;它們都是數字。在第一個數字不得大于11&#xff0c;也不得小于0。在第二個…

創建Java動態代理

Java動態代理機制提供了一種有趣的方式來創建代理實例。 不過&#xff0c;創建動態代理的步驟有些繁瑣&#xff0c;請考慮將代理用于審核服務實例的方法調用所花費的時間– public interface InventoryService {public Inventory create(Inventory inventory);public List<I…