jms activemq_带有ActiveMQ的JMS

jms activemq

带有ActiveMQ的JMS

JMS是Java消息服务的缩写,它提供了一种以松散耦合,灵活的方式集成应用程序的机制。 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

jms activemq

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/354090.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【EMV L2】SDA静态数据认证处理流程

【静态数据认证】 静态数据认证处理过程中,卡片没有执行任何处理,终端执行的处理流程:1、认证中心公钥的获取终端使用卡片上的认证中心公钥索引(PKI)【TAG:8F,Certification Authority Public K…

java取邮箱前缀_java抓取网页或文件中的邮箱号码

java抓取网页或文件中的邮箱号码发布时间:2020-10-18 08:58:32来源:脚本之家阅读:69作者:java大渣渣本文实例为大家分享了java抓取邮箱号码的具体代码,供大家参考,具体内容如下java抓取文件中邮箱号码的具体…

java btrace_BTrace:Java开发人员工具箱中的隐藏宝石

java btrace这篇文章是关于BTrace的 ,我正在考虑将其作为Java开发人员的隐藏宝藏。 BTrace是用于Java平台的安全,动态跟踪工具。 BTrace可用于动态跟踪正在运行的Java程序(类似于DTrace,适用于OpenSolaris应用程序和OS&#xff09…

xampp浏览php出现乱码,dvwa+xampp搭建显示乱码的问题及解决方案

如图,dvwa显示乱码,解决办法有两个:1、方法一是,临时解决办法,也就是每次都得手动修改:利用浏览器的编码修改2、方法二是:永久方案,那就是修改dvwa的配置文件,修改默认编…

HotSpot的-XshowSettings标志的简单性和价值

一个方便的HotSpot JVM标志 ( 选项为Java启动 java )是-XshowSettings选项。 Oracle Java启动器描述页面中对此选项进行了如下描述 : -XshowSettings : category显示设置并继续。 该选项的可能类别参数包括: all显示所…

Python验证码简单实现(数字和大写字母组成的4位验证码)

#数字和英文大写字母的4位随机数 def checkcode(): #def 定义方法 checkcode() 方法名()import random # 导入包checkcode ""string range(0,4)for i in string:current random.randrange(0,3) #randrange随机数 参数1<随机数<参数2if current ! i:temp …

php haystack,haystack(示例代码)

1、haystack简介Haystack是django的开源全文搜索框架(全文检索不同于特定字段的模糊查询&#xff0c;使用全文检索的效率更高 )&#xff0c;该框架支持Solr,Elasticsearch,Whoosh, Xapian&#xff0c;搜索引擎它是一个可插拔的后端(很像Django的数据库层)&#xff0c;所以几乎你…

fopen php 乱码,如何解决php fgets读取文件乱码的问题

如何解决php fgets读取文件乱码的问题,文件,乱码,简体中文,记事本,页面如何解决php fgets读取文件乱码的问题易采站长站&#xff0c;站长之家为您整理了如何解决php fgets读取文件乱码的问题的相关内容。php fgets乱码的解决办法&#xff1a;首先依次点击“菜单修改->页面属…

一致性哈希算法原理分析及实现

一致性哈希算法常用于负载均衡中要求资源被均匀的分布到所有节点上&#xff0c;并且对资源的请求能快速路由到对应的节点上。具体的举两个场景的例子&#xff1a; 1、MemCache集群&#xff0c;要求存储各种数据均匀的存到集群中的各个节点上&#xff0c;访问这些数据时能快速的…

jsf集成spring_JSF – PrimeFaces和Hibernate集成项目

jsf集成spring本文介绍了如何使用JSF&#xff0c;PrimeFaces和Hibernate开发项目。 下面是一个示例应用程序&#xff1a; 二手技术&#xff1a; JDK 1.6.0_21 Maven的3.0.2 JSF 2.0.3 PrimeFaces 2.2.1 Hibernate3.6.7 MySQL Java连接器5.1.17 MySQL 5.5.8 Apache Tomcat 7.…

帝国 loginjs.php,帝国cms 6.6 后台拿shell

时间:2013-02-27来源:源码库 作者:源码库 文章热度:℃漏洞作者&#xff1a; 付弘雪提交时间&#xff1a; 2013-01-21公开时间&#xff1a; 2013-01-21漏洞类型&#xff1a; 文件上传导致任意代码执行简要描述&#xff1a;帝国cms 6.6版本后台拿shell 比网上流行的方法简单很多由…

带有JSF,Servlet和CDI的DynamicReports和JasperReports

在此示例中&#xff0c;我将展示如何将DynamicReport和JasperReports与Servlet和CDI集成。 工具&#xff1a; TIBCO Jaspersoft Studio-6.0.4。最终版 Eclipse Luna服务版本2&#xff08;4.4.2&#xff09;。 WildFly 8.x应用程序服务器。 这是Eclipse上项目层次结构的屏幕…

swing 聊天气泡背景_Java Swing中的聊天气泡

swing 聊天气泡背景本文将向您解释“如何在Java swing应用程序中绘制聊天气泡&#xff1f;” 聊天气泡与呼出或提示气泡相同。 今天&#xff0c;大多数聊天应用程序都以这种格式显示转换&#xff0c;因此本文将帮助您在用Java swing创建的桌面应用程序中执行相同的操作。 以下课…

jdk7与jdk8环境共存与切换

1&#xff0c;先安装jdk7,配置环境变量JAVA_HOME,然后安装jdk8。 2&#xff0c;安装jdk8后&#xff0c;JAVA_HOME指向未做修改&#xff0c;执行java -version显示还是以前的jdk7版本信息&#xff0c; 3&#xff0c;接下来我们配置环境变量JAVA_HOME,发现配置jdk7的路径,或者配置…

PHP培训选云和数据,送给云和数据郑州分中心PHP培训班全体学员的祝福

在云和数据数百个日日夜夜&#xff0c;郑州PHP培训班的学员们一起成长&#xff0c;从青春懵懂到成熟稳重&#xff0c;从羞涩内敛到侃侃而谈&#xff0c;他们用奋斗和拼搏共同刻画了人生中一段难忘的回忆。12月12日&#xff0c;云和数据郑州分中心PHP培训班毕业典礼&#xff0c;…

cyclicbarrier_Java并发– CyclicBarrier示例

cyclicbarrierJava中的CyclicBarrier是JDK 5中在java.util.Concurrent包上引入的同步器&#xff0c;以及其他并发实用程序&#xff0c;例如Counting Semaphore &#xff0c; BlockingQueue &#xff0c; ConcurrentHashMap等。CyclicBarrier与CountDownLatch类似&#xff0c;我…

php队列失败是指什么,队列是什么意思

队列是一种特殊的线性表。它只允许在表的前端(front)进行删除操作&#xff0c;而在表的后端(rear)进行插入操作&#xff0c;和栈一样&#xff0c;队列是一种操作受限制的线性表&#xff1b;进行插入操作的端称为队尾&#xff0c;进行删除操作的端称为队头&#xff1b;队列中没有…

从In Memory Data Grid,Apache Ignite快速入门

IMDG或内存数据网格不是内存中关系数据库&#xff0c;NOSQL数据库或关系数据库。 它是另一种软件数据存储库。 数据模型分布在单个位置或多个位置的许多服务器上。 这种分布称为数据结构。 这种分布式模型被称为“无共享”架构。 IMDG具有以下特征&#xff1a; 所有服务器可以…

91.91p10.space v.php,luogu P1091 合唱队形

任务计划推了很久才做www从两头开始的单调上升队列没啥可说的#include#includeusing namespace std;#define maxn 110int a[maxn];int f[2][maxn];int ans;int main() {int n;scanf("%d",&n);for(int i 1; i < n; i)scanf("%d",&a[i]);a[0] a…

BZOJ 2097 [Usaco2010 Dec]Exercise 奶牛健美操

【题意】 给出一棵树。现在可以在树中删去m条边&#xff0c;使它变成m1棵树。要求最小化树的直径的最大值。 【题解】 二分答案。$Check$的时候用$DP$&#xff0c;记录当前节点每个儿子的直径$v[i]$&#xff0c;如果$v[i]1>mid$&#xff0c;那么就断掉连向儿子的这条边。如果…